1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Extended SQLAlchemy connection class that also includes access to the schema.
10 from typing import Any, Mapping, Sequence, Union, Dict, cast
12 import sqlalchemy as sa
13 from sqlalchemy.ext.asyncio import AsyncConnection
15 from nominatim.db.sqlalchemy_schema import SearchTables
17 class SearchConnection:
18 """ An extended SQLAlchemy connection class, that also contains
19 then table definitions. The underlying asynchronous SQLAlchemy
20 connection can be accessed with the 'connection' property.
21 The 't' property is the collection of Nominatim tables.
24 def __init__(self, conn: AsyncConnection,
26 properties: Dict[str, Any]) -> None:
27 self.connection = conn
28 self.t = tables # pylint: disable=invalid-name
29 self._property_cache = properties
32 async def scalar(self, sql: sa.sql.base.Executable,
33 params: Union[Mapping[str, Any], None] = None
35 """ Execute a 'scalar()' query on the connection.
37 return await self.connection.scalar(sql, params)
40 async def execute(self, sql: sa.sql.base.Executable,
41 params: Union[Mapping[str, Any], Sequence[Mapping[str, Any]], None] = None
42 ) -> 'sa.engine.Result[Any]':
43 """ Execute a 'execute()' query on the connection.
45 return await self.connection.execute(sql, params)
48 async def get_property(self, name: str, cached: bool = True) -> str:
49 """ Get a property from Nominatim's property table.
51 Property values are normally cached so that they are only
52 retrieved from the database when they are queried for the
53 first time with this function. Set 'cached' to False to force
54 reading the property from the database.
56 Raises a ValueError if the property does not exist.
58 if name.startswith('DB:'):
59 raise ValueError(f"Illegal property value '{name}'.")
61 if cached and name in self._property_cache:
62 return cast(str, self._property_cache[name])
64 sql = sa.select(self.t.properties.c.value)\
65 .where(self.t.properties.c.property == name)
66 value = await self.connection.scalar(sql)
69 raise ValueError(f"Property '{name}' not found in database.")
71 self._property_cache[name] = cast(str, value)
73 return cast(str, value)
76 async def get_db_property(self, name: str) -> Any:
77 """ Get a setting from the database. At the moment, only
78 'server_version', the version of the database software, can
79 be retrieved with this function.
81 Raises a ValueError if the property does not exist.
83 if name != 'server_version':
84 raise ValueError(f"DB setting '{name}' not found in database.")
86 return self._property_cache['DB:server_version']