userver: en/testsuite/databases/mysql/discover.py Source File
Loading...
Searching...
No Matches
discover.py
1import collections
2import pathlib
3from typing import Any, DefaultDict
4
5from . import classes, utils
6
7
8def find_schemas(
9 schema_dirs: list[pathlib.Path],
10 dbprefix: str = 'testsuite-',
11 extra_schema_args: dict[str, Any] | None = None,
12) -> dict[str, classes.DatabaseConfig]:
13 """Retrieve database schemas from filesystem.
14
15 :param schema_dirs: list of schema paths
16 :param dbprefix: database name internal prefix
17 :param extra_schema_args: for each DB contains list
18 of tables we don't have to truncate and flag for explicit creation
19 example:
20
21 .. code-block:: python
22
23 {
24 'database1': {
25 'create': False,
26 'truncate_non_empty': True,
27 'keep_tables': [
28 'table1', 'table2'
29 ]
30 }
31 }
32
33 :returns: Dictionary where key is dbname and value is
34 ``classes.DatabaseConfig`` instance.
35 """
36 result = {}
37 for path in schema_dirs:
38 if not path.is_dir():
39 continue
40 for dbname, migrations in _scan_path(path).items():
41 full_db_name: str = dbprefix + dbname
42 if extra_schema_args:
43 kwargs: dict = extra_schema_args.get(full_db_name, {})
44 else:
45 kwargs = {}
46 result[dbname] = classes.DatabaseConfig(
47 dbname=full_db_name,
48 migrations=migrations,
49 **kwargs,
50 )
51 return result
52
53
54def _scan_path(
55 schema_path: pathlib.Path,
56) -> DefaultDict[str, list[pathlib.Path]]:
57 result = collections.defaultdict(list)
58 for entry in schema_path.iterdir():
59 if entry.suffix == '.sql' and entry.is_file():
60 result[entry.stem].append(entry)
61 elif entry.is_dir():
62 result[entry.stem].extend(utils.scan_sql_directory(entry))
63 return result