provision.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # testing/provision.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. import collections
  8. import logging
  9. from . import config
  10. from . import engines
  11. from . import util
  12. from .. import exc
  13. from .. import inspect
  14. from ..engine import url as sa_url
  15. from ..sql import ddl
  16. from ..sql import schema
  17. from ..util import compat
  18. log = logging.getLogger(__name__)
  19. FOLLOWER_IDENT = None
  20. class register(object):
  21. def __init__(self):
  22. self.fns = {}
  23. @classmethod
  24. def init(cls, fn):
  25. return register().for_db("*")(fn)
  26. def for_db(self, *dbnames):
  27. def decorate(fn):
  28. for dbname in dbnames:
  29. self.fns[dbname] = fn
  30. return self
  31. return decorate
  32. def __call__(self, cfg, *arg):
  33. if isinstance(cfg, compat.string_types):
  34. url = sa_url.make_url(cfg)
  35. elif isinstance(cfg, sa_url.URL):
  36. url = cfg
  37. else:
  38. url = cfg.db.url
  39. backend = url.get_backend_name()
  40. if backend in self.fns:
  41. return self.fns[backend](cfg, *arg)
  42. else:
  43. return self.fns["*"](cfg, *arg)
  44. def create_follower_db(follower_ident):
  45. for cfg in _configs_for_db_operation():
  46. log.info("CREATE database %s, URI %r", follower_ident, cfg.db.url)
  47. create_db(cfg, cfg.db, follower_ident)
  48. def setup_config(db_url, options, file_config, follower_ident):
  49. # load the dialect, which should also have it set up its provision
  50. # hooks
  51. dialect = sa_url.make_url(db_url).get_dialect()
  52. dialect.load_provisioning()
  53. if follower_ident:
  54. db_url = follower_url_from_main(db_url, follower_ident)
  55. db_opts = {}
  56. update_db_opts(db_url, db_opts)
  57. db_opts["scope"] = "global"
  58. eng = engines.testing_engine(db_url, db_opts)
  59. post_configure_engine(db_url, eng, follower_ident)
  60. eng.connect().close()
  61. cfg = config.Config.register(eng, db_opts, options, file_config)
  62. # a symbolic name that tests can use if they need to disambiguate
  63. # names across databases
  64. if follower_ident:
  65. config.ident = follower_ident
  66. if follower_ident:
  67. configure_follower(cfg, follower_ident)
  68. return cfg
  69. def drop_follower_db(follower_ident):
  70. for cfg in _configs_for_db_operation():
  71. log.info("DROP database %s, URI %r", follower_ident, cfg.db.url)
  72. drop_db(cfg, cfg.db, follower_ident)
  73. def generate_db_urls(db_urls, extra_drivers):
  74. """Generate a set of URLs to test given configured URLs plus additional
  75. driver names.
  76. Given::
  77. --dburi postgresql://db1 \
  78. --dburi postgresql://db2 \
  79. --dburi postgresql://db2 \
  80. --dbdriver=psycopg2 --dbdriver=asyncpg?async_fallback=true
  81. Noting that the default postgresql driver is psycopg2, the output
  82. would be::
  83. postgresql+psycopg2://db1
  84. postgresql+asyncpg://db1
  85. postgresql+psycopg2://db2
  86. postgresql+psycopg2://db3
  87. That is, for the driver in a --dburi, we want to keep that and use that
  88. driver for each URL it's part of . For a driver that is only
  89. in --dbdrivers, we want to use it just once for one of the URLs.
  90. for a driver that is both coming from --dburi as well as --dbdrivers,
  91. we want to keep it in that dburi.
  92. Driver specific query options can be specified by added them to the
  93. driver name. For example, to enable the async fallback option for
  94. asyncpg::
  95. --dburi postgresql://db1 \
  96. --dbdriver=asyncpg?async_fallback=true
  97. """
  98. urls = set()
  99. backend_to_driver_we_already_have = collections.defaultdict(set)
  100. urls_plus_dialects = [
  101. (url_obj, url_obj.get_dialect())
  102. for url_obj in [sa_url.make_url(db_url) for db_url in db_urls]
  103. ]
  104. for url_obj, dialect in urls_plus_dialects:
  105. backend_to_driver_we_already_have[dialect.name].add(dialect.driver)
  106. backend_to_driver_we_need = {}
  107. for url_obj, dialect in urls_plus_dialects:
  108. backend = dialect.name
  109. dialect.load_provisioning()
  110. if backend not in backend_to_driver_we_need:
  111. backend_to_driver_we_need[backend] = extra_per_backend = set(
  112. extra_drivers
  113. ).difference(backend_to_driver_we_already_have[backend])
  114. else:
  115. extra_per_backend = backend_to_driver_we_need[backend]
  116. for driver_url in _generate_driver_urls(url_obj, extra_per_backend):
  117. if driver_url in urls:
  118. continue
  119. urls.add(driver_url)
  120. yield driver_url
  121. def _generate_driver_urls(url, extra_drivers):
  122. main_driver = url.get_driver_name()
  123. extra_drivers.discard(main_driver)
  124. url = generate_driver_url(url, main_driver, "")
  125. yield str(url)
  126. for drv in list(extra_drivers):
  127. if "?" in drv:
  128. driver_only, query_str = drv.split("?", 1)
  129. else:
  130. driver_only = drv
  131. query_str = None
  132. new_url = generate_driver_url(url, driver_only, query_str)
  133. if new_url:
  134. extra_drivers.remove(drv)
  135. yield str(new_url)
  136. @register.init
  137. def generate_driver_url(url, driver, query_str):
  138. backend = url.get_backend_name()
  139. new_url = url.set(
  140. drivername="%s+%s" % (backend, driver),
  141. )
  142. if query_str:
  143. new_url = new_url.update_query_string(query_str)
  144. try:
  145. new_url.get_dialect()
  146. except exc.NoSuchModuleError:
  147. return None
  148. else:
  149. return new_url
  150. def _configs_for_db_operation():
  151. hosts = set()
  152. for cfg in config.Config.all_configs():
  153. cfg.db.dispose()
  154. for cfg in config.Config.all_configs():
  155. url = cfg.db.url
  156. backend = url.get_backend_name()
  157. host_conf = (backend, url.username, url.host, url.database)
  158. if host_conf not in hosts:
  159. yield cfg
  160. hosts.add(host_conf)
  161. for cfg in config.Config.all_configs():
  162. cfg.db.dispose()
  163. @register.init
  164. def drop_all_schema_objects_pre_tables(cfg, eng):
  165. pass
  166. @register.init
  167. def drop_all_schema_objects_post_tables(cfg, eng):
  168. pass
  169. def drop_all_schema_objects(cfg, eng):
  170. drop_all_schema_objects_pre_tables(cfg, eng)
  171. inspector = inspect(eng)
  172. try:
  173. view_names = inspector.get_view_names()
  174. except NotImplementedError:
  175. pass
  176. else:
  177. with eng.begin() as conn:
  178. for vname in view_names:
  179. conn.execute(
  180. ddl._DropView(schema.Table(vname, schema.MetaData()))
  181. )
  182. if config.requirements.schemas.enabled_for_config(cfg):
  183. try:
  184. view_names = inspector.get_view_names(schema="test_schema")
  185. except NotImplementedError:
  186. pass
  187. else:
  188. with eng.begin() as conn:
  189. for vname in view_names:
  190. conn.execute(
  191. ddl._DropView(
  192. schema.Table(
  193. vname,
  194. schema.MetaData(),
  195. schema="test_schema",
  196. )
  197. )
  198. )
  199. util.drop_all_tables(eng, inspector)
  200. if config.requirements.schemas.enabled_for_config(cfg):
  201. util.drop_all_tables(eng, inspector, schema=cfg.test_schema)
  202. util.drop_all_tables(eng, inspector, schema=cfg.test_schema_2)
  203. drop_all_schema_objects_post_tables(cfg, eng)
  204. if config.requirements.sequences.enabled_for_config(cfg):
  205. with eng.begin() as conn:
  206. for seq in inspector.get_sequence_names():
  207. conn.execute(ddl.DropSequence(schema.Sequence(seq)))
  208. if config.requirements.schemas.enabled_for_config(cfg):
  209. for schema_name in [cfg.test_schema, cfg.test_schema_2]:
  210. for seq in inspector.get_sequence_names(
  211. schema=schema_name
  212. ):
  213. conn.execute(
  214. ddl.DropSequence(
  215. schema.Sequence(seq, schema=schema_name)
  216. )
  217. )
  218. @register.init
  219. def create_db(cfg, eng, ident):
  220. """Dynamically create a database for testing.
  221. Used when a test run will employ multiple processes, e.g., when run
  222. via `tox` or `pytest -n4`.
  223. """
  224. raise NotImplementedError(
  225. "no DB creation routine for cfg: %s" % (eng.url,)
  226. )
  227. @register.init
  228. def drop_db(cfg, eng, ident):
  229. """Drop a database that we dynamically created for testing."""
  230. raise NotImplementedError("no DB drop routine for cfg: %s" % (eng.url,))
  231. @register.init
  232. def update_db_opts(db_url, db_opts):
  233. """Set database options (db_opts) for a test database that we created."""
  234. pass
  235. @register.init
  236. def post_configure_engine(url, engine, follower_ident):
  237. """Perform extra steps after configuring an engine for testing.
  238. (For the internal dialects, currently only used by sqlite, oracle, mssql)
  239. """
  240. pass
  241. @register.init
  242. def follower_url_from_main(url, ident):
  243. """Create a connection URL for a dynamically-created test database.
  244. :param url: the connection URL specified when the test run was invoked
  245. :param ident: the pytest-xdist "worker identifier" to be used as the
  246. database name
  247. """
  248. url = sa_url.make_url(url)
  249. return url.set(database=ident)
  250. @register.init
  251. def configure_follower(cfg, ident):
  252. """Create dialect-specific config settings for a follower database."""
  253. pass
  254. @register.init
  255. def run_reap_dbs(url, ident):
  256. """Remove databases that were created during the test process, after the
  257. process has ended.
  258. This is an optional step that is invoked for certain backends that do not
  259. reliably release locks on the database as long as a process is still in
  260. use. For the internal dialects, this is currently only necessary for
  261. mssql and oracle.
  262. """
  263. pass
  264. def reap_dbs(idents_file):
  265. log.info("Reaping databases...")
  266. urls = collections.defaultdict(set)
  267. idents = collections.defaultdict(set)
  268. dialects = {}
  269. with open(idents_file) as file_:
  270. for line in file_:
  271. line = line.strip()
  272. db_name, db_url = line.split(" ")
  273. url_obj = sa_url.make_url(db_url)
  274. if db_name not in dialects:
  275. dialects[db_name] = url_obj.get_dialect()
  276. dialects[db_name].load_provisioning()
  277. url_key = (url_obj.get_backend_name(), url_obj.host)
  278. urls[url_key].add(db_url)
  279. idents[url_key].add(db_name)
  280. for url_key in urls:
  281. url = list(urls[url_key])[0]
  282. ident = idents[url_key]
  283. run_reap_dbs(url, ident)
  284. @register.init
  285. def temp_table_keyword_args(cfg, eng):
  286. """Specify keyword arguments for creating a temporary Table.
  287. Dialect-specific implementations of this method will return the
  288. kwargs that are passed to the Table method when creating a temporary
  289. table for testing, e.g., in the define_temp_tables method of the
  290. ComponentReflectionTest class in suite/test_reflection.py
  291. """
  292. raise NotImplementedError(
  293. "no temp table keyword args routine for cfg: %s" % (eng.url,)
  294. )
  295. @register.init
  296. def prepare_for_drop_tables(config, connection):
  297. pass
  298. @register.init
  299. def stop_test_class_outside_fixtures(config, db, testcls):
  300. pass
  301. @register.init
  302. def get_temp_table_name(cfg, eng, base_name):
  303. """Specify table name for creating a temporary Table.
  304. Dialect-specific implementations of this method will return the
  305. name to use when creating a temporary table for testing,
  306. e.g., in the define_temp_tables method of the
  307. ComponentReflectionTest class in suite/test_reflection.py
  308. Default to just the base name since that's what most dialects will
  309. use. The mssql dialect's implementation will need a "#" prepended.
  310. """
  311. return base_name
  312. @register.init
  313. def set_default_schema_on_connection(cfg, dbapi_connection, schema_name):
  314. raise NotImplementedError(
  315. "backend does not implement a schema name set function: %s"
  316. % (cfg.db.url,)
  317. )