userver: en/testsuite/databases/pgsql/utils.py Source File
Loading...
Searching...
No Matches
utils.py
1import hashlib
2import pathlib
3import typing
4import urllib.parse
5
6
7def scan_sql_directory(root: pathlib.Path) -> list[pathlib.Path]:
8 return [
9 path
10 for path in sorted(root.iterdir())
11 if path.is_file() and path.suffix == '.sql'
12 ]
13
14
15def connstr_replace_dbname(connstr: str, dbname: str) -> str:
16 """Replace dbname in existing connection string."""
17 if connstr.endswith(' dbname='):
18 return connstr + dbname
19 if connstr.startswith('postgresql://'):
20 url = urllib.parse.urlparse(connstr)
21 url = url._replace(path=dbname) # pylint: disable=protected-access
22 return url.geturl()
23 raise RuntimeError(
24 f'Unsupported PostgreSQL connection string format {connstr!r}',
25 )
26
27
28def get_files_hash(paths: typing.Iterable[pathlib.Path]) -> str:
29 result = hashlib.md5()
30 for path in paths:
31 if path.is_dir():
32 files = sorted(
33 child for child in path.rglob('*') if child.is_file()
34 )
35 elif path.is_file():
36 files = [path]
37 else:
38 continue
39
40 for file_path in files:
41 result.update(bytes(str(file_path) + '\n', 'utf8'))
42 with file_path.open('rb') as file:
43 content = file.read()
44 result.update(b'%d\n' % len(content))
45 result.update(content)
46 return result.hexdigest()