Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
139 kB
diff --git a/dysql/__init__.py b/dysql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..492ed753f2bef5ed18777a39eab6632440176c6c --- /dev/null +++ b/dysql/__init__.py @@ -0,0 +1,60 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +# Public imports +from .mappers import ( + BaseMapper, + DbMapResult, + RecordCombiningMapper, + SingleRowMapper, + SingleColumnMapper, + SingleRowAndColumnMapper, + CountMapper, + KeyValueMapper, +) +from .query_utils import QueryData, QueryDataError, TemplateGenerators +from .connections import ( + sqlexists, + sqlquery, + sqlupdate, +) +from .databases import ( + is_set_current_database_supported, + reset_current_database, + set_current_database, + set_database_init_hook, + set_default_connection_parameters, +) +from .multitenancy import use_database_tenant, tenant_database_manager +from .exceptions import DBNotPreparedError + + +__all__ = [ + "BaseMapper", + "DbMapResult", + "RecordCombiningMapper", + "SingleRowMapper", + "SingleColumnMapper", + "SingleRowAndColumnMapper", + "CountMapper", + "KeyValueMapper", + "QueryData", + "QueryDataError", + "TemplateGenerators", + "sqlexists", + "sqlquery", + "sqlupdate", + "is_set_current_database_supported", + "reset_current_database", + "set_current_database", + "set_database_init_hook", + "set_default_connection_parameters", + "use_database_tenant", + "tenant_database_manager", + "DBNotPreparedError", +] diff --git a/dysql/annotations.py b/dysql/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..4a12d05f604c53466a5e3941a9141c873a2c9a21 --- /dev/null +++ b/dysql/annotations.py @@ -0,0 +1,31 @@ +""" +Copyright 2023 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from typing import TypeVar, Annotated + +from pydantic import BeforeValidator + +# pylint: disable=invalid-name +T = TypeVar("T") + + +def _transform_csv(value: str) -> T: + if not value: + return None + + if isinstance(value, str): + return list(map(str.strip, value.split(","))) + + if isinstance(value, list): + return value + # if we don't have a string or type T we aren't going to be able to transform it + return [value] + + +# Annotation that helps transform a CSV string into a list of type T +FromCSVToList = Annotated[T, BeforeValidator(_transform_csv)] diff --git a/dysql/connections.py b/dysql/connections.py new file mode 100644 index 0000000000000000000000000000000000000000..6c30dd4ced04b3a681f6f6b9e4e7dbf346768131 --- /dev/null +++ b/dysql/connections.py @@ -0,0 +1,269 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import logging +import functools +import inspect +from typing import Type, Union + +import sqlalchemy + +from .databases import DatabaseContainerSingleton +from .mappers import ( + BaseMapper, + DbMapResult, + RecordCombiningMapper, +) +from .query_utils import get_query_data + +logger = logging.getLogger("database") + +# Always initialize a database container, it is never set again +_DATABASE_CONTAINER = DatabaseContainerSingleton() + + +class _ConnectionManager: + _connection: sqlalchemy.engine.base.Connection + + # pylint: disable=unused-argument + def __init__(self, func, isolation_level, transaction, *args, **kwargs): + self._transaction = None + + self._connection = ( + _DATABASE_CONTAINER.current_database.engine.connect().execution_options( + isolation_level=isolation_level + ) + ) + if transaction: + self._transaction = self._connection.begin() + + def __enter__(self): + self._connection.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + # Handle transaction committing/rollback before closing the connection + if exc_type: + logger.error(f"Encountered an error : {exc_val}") + + # Roll back transaction if there is one + if self._transaction: + self._transaction.rollback() + elif self._transaction: + self._transaction.commit() + + # Close the connection + self._connection.__exit__(exc_type, exc_val, exc_tb) + + def execute_query(self, query, params=None) -> sqlalchemy.engine.CursorResult: + """ + Executes the query through the connection with optional parameters. + :param query: The query to run + :param params: The parameters to use + :return: The result proxy object from sqlalchemy + """ + if not params: + params = {} + + if isinstance(params, DbMapResult): + params = params.raw() + + return self._connection.execute(sqlalchemy.text(query), params) + + +def sqlquery( + mapper: Union[BaseMapper, Type[BaseMapper]] = None, + isolation_level: str = "READ_COMMITTED", +): + """ + query allows for defining a parameterize select query that is then executed + :param mapper: a class extending from or an instance of BaseMapper, defaults to + RecordCombiningMapper + :param isolation_level: the isolation level to use for the transaction, defaults to + 'READ_COMMITTED' + :return: Depends on the mapper used, see mapper documentation for more details. + + Examples:: + + # Uses the default RecordCombiningMapper, returns a list of results + @sqlquery() + def get_items(name, date): + return QueryData("SELECT item1, item2, ... FROM item join item_data ... + WHERE name=:name and date before :date"), {'name': name, 'date': date}) + + # Override the mapper to return a list of scalars + @sqlquery(mapper=SingleColumnMapper) + def get_items(): + return QueryData("SELECT item1 FROM item join item_data ...") + + # Override the mapper to return a single (first) result + @sqlquery(mapper=SingleRowMapper) + def get_items(): + return QueryData("SELECT item1, item2, ... FROM item join item_data ...") + + # Override the mapper to return a single result from the the first result + @sqlquery(mapper=CountMapper) + def get_count(): + return QueryData("SELECT count(*) FROM item GROUP BY item1") + """ + + def decorator(func): + def handle_query(*args, **kwargs): + functools.wraps(func, handle_query) + actual_mapper = mapper + if not actual_mapper: + # Default to record combining mapper + actual_mapper = RecordCombiningMapper + + # Handle mapper defined as a class + if inspect.isclass(actual_mapper): + actual_mapper = actual_mapper() + + with _ConnectionManager( + func, isolation_level, False, *args, **kwargs + ) as conn_manager: + data = func(*args, **kwargs) + query, params = get_query_data(data) + records = conn_manager.execute_query(query, params) + return actual_mapper.map_records(records) + + return handle_query + + return decorator + + +def sqlexists(isolation_level="READ_COMMITTED"): + """ + exists query allows for defining a parameterize select query that is + wrapped in an exists clause and then executed + :param isolation_level: the isolation level to use for the transaction, defaults to + 'READ_COMMITTED' + :return: returns a True or False depending on the value returned from + the exists query. If Exists returns 1, True. otherwise, False + Examples:: + + @sqlexists + def get_items_exists(name, date): + return "SELECT 1 FROM item join item_data ... + WHERE name=:name and date before :date", { name=name, date=date} + + @sqlexists + def get_items_exists(): + return "SELECT 1 FROM item WHERE date before now()-100 + + """ + + def decorator(func): + def handle_query(*args, **kwargs): + functools.wraps(func, handle_query) + with _ConnectionManager( + func, isolation_level, False, *args, **kwargs + ) as conn_manager: + data = func(*args, **kwargs) + query, params = get_query_data(data) + + query = query.lstrip() + if query.startswith("SELECT EXISTS"): + query = query.replace("SELECT EXISTS", "SELECT 1 WHERE EXISTS") + if not query.startswith("SELECT 1 WHERE EXISTS"): + query = f"SELECT 1 WHERE EXISTS ( {query} )" + result = conn_manager.execute_query(query, params).scalar() + return result == 1 + + return handle_query + + return decorator + + +def sqlupdate( + isolation_level="READ_COMMITTED", + disable_foreign_key_checks=False, + on_success=None, +): + """ + :param isolation_level should specify whether we can read data from transactions that are not + yet committed defaults to READ_COMMITTED + :param disable_foreign_key_checks Should be used with caution. Only use this if you have + confidence the data you are inserting is going to have everything it needs to satisfy + foreign_key_checks once all the data is applied. Foreign key checks are there to provide + our database with integrety + + That being said, there are times when you are synchronizing data from another source that + you have data that may be difficult to sort ahead of time in order to avoid failing foreign + key constraints this flag helps to deal with cases where the logic may be unnecessarily + complex. + + Note: this will work as expected when a normal transaction completes successfully and if a + transaction rolls back this will be left in a clean state as expected before executing + anything + Examples:: + + @sqlupdate + def insert_example(key_values) + return QueryData("INSERT INTO table(id, value) VALUES (:id, :value)", key_values) + + @sqlupdate + def delete_example(ids) + return QueryData("DELETE FROM table WHERE id=:id", { "id": id }) + + @sqlupdate() + def insert_with_relations(get_last_insert_id = None): + yield QueryData("INSERT INTO table(value) VALUES (:value)", key_values) + id = get_last_insert_id() + yield "INSERT INTO relation_table(id, value) VALUES (:id, :value)", { + "id": id, + "value": "value" + }) + """ + + def update_wrapper(func): + """ + :param func: should return a tuple representing the query followed by the dictionary of key + values for query parameters + """ + + def handle_query(*args, **kwargs): + functools.wraps(func) + with _ConnectionManager( + func, isolation_level, True, *args, **kwargs + ) as conn_manager: + if disable_foreign_key_checks: + conn_manager.execute_query("SET FOREIGN_KEY_CHECKS=0") + last_insert_method = "get_last_insert_id" + if last_insert_method in inspect.signature(func).parameters: + kwargs[last_insert_method] = lambda: conn_manager.execute_query( + "SELECT LAST_INSERT_ID()" + ).scalar() + if inspect.isgeneratorfunction(func): + logger.debug("handling each query before committing transaction") + + for data in func(*args, **kwargs): + query, params = get_query_data(data) + if isinstance(params, list): + for param in params: + conn_manager.execute_query(query, param) + else: + conn_manager.execute_query(query, params) + else: + data = func(*args, **kwargs) + query, params = get_query_data(data) + if isinstance(params, list): + raise Exception("Params must not be a list") + conn_manager.execute_query(query, params) + + if disable_foreign_key_checks: + conn_manager.execute_query("SET FOREIGN_KEY_CHECKS=1") + + if last_insert_method in kwargs: + del kwargs[last_insert_method] + if on_success: + on_success(*args, **kwargs) + + return handle_query + + return update_wrapper diff --git a/dysql/databases.py b/dysql/databases.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0213f8d177b0396703f2276dd56bf4489a6a22 --- /dev/null +++ b/dysql/databases.py @@ -0,0 +1,216 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import contextvars +import logging +from collections import defaultdict +from typing import Callable, Optional + +import sqlalchemy + +from .exceptions import DBNotPreparedError + + +logger = logging.getLogger("database") + +_DEFAULT_CONNECTION_PARAMS_BY_KEY = defaultdict(dict) +CURRENT_DATABASE_VAR = contextvars.ContextVar("dysql_current_database", default="") + + +def set_database_init_hook( + hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None], +) -> None: + """ + Sets an initialization hook whenever a new database is initialized. This method will receive the database name + (may be none) and the sqlalchemy engine as parameters. + + :param hook_method: the hook method + """ + Database.set_init_hook(hook_method) + + +def is_set_current_database_supported() -> bool: + """ + Deprecated, left in for backwards compatibility but always returns true. + :return: True + """ + return True + + +def set_current_database(database_key: str) -> None: + """ + Sets the current database key, may be used for multitenancy. This is only supported on Python 3.7+. This uses + contextvars internally to set the name for the current async context. + :param database_key: the arbitrary database key to use for this async context + """ + CURRENT_DATABASE_VAR.set(database_key) + logger.debug(f"Set current database to {database_key}") + + +def reset_current_database() -> None: + """ + Helper method to reset the current database to the default. Internally, this calls `set_current_database` with + an empty string. + """ + set_current_database("") + + +def _get_current_database_key() -> str: + """ + The current database key, using contextvars (if on python 3.7+) or the default database key. + :return: The current database key + """ + database: Optional[str] = None + if CURRENT_DATABASE_VAR: + database = CURRENT_DATABASE_VAR.get() + if not database and _DEFAULT_CONNECTION_PARAMS_BY_KEY: + # Get first database key + database = next(iter(_DEFAULT_CONNECTION_PARAMS_BY_KEY)) + return database + + +def _validate_param(name: str, value: str) -> None: + if not value: + raise DBNotPreparedError( + f'Database parameter "{name}" is not set or empty and is required' + ) + + +def set_default_connection_parameters( + host: str, + user: str, + password: str, + database: str, + database_key: Optional[str] = None, + port: int = 3306, + pool_size: int = 10, + pool_recycle: int = 3600, + echo_queries: bool = False, + charset: str = "utf8", + collation: Optional[str] = None, +): + """ + Initializes the parameters to use when connecting to the database. This is a subset of the parameters + used by sqlalchemy. These may be overridden by parameters provided in the QueryData, hence the "default". + + :param host: the db host to try to connect to + :param user: user to connect to the database with + :param password: password for given user + :param database: database to connect to + :param database_key: optional database key that may be used for multitenant DBs, defaults to the database name + :param port: the port to connect to (default 3306) + :param pool_size: number of connections to maintain in the connection pool (default 10) + :param pool_recycle: amount of time to wait between resetting the connections + in the pool (default 3600) + :param echo_queries: this tells sqlalchemy to print the queries when set to True (default false) + :param charset: the charset for the sql engine to initialize with. (default utf8) + :param collation: the collation for the sql engine to initialize with. (default is not set) + :exception DBNotPrepareError: happens when required parameters are missing + """ + _validate_param("host", host) + _validate_param("user", user) + _validate_param("password", password) + _validate_param("database", database) + + if not database_key: + database_key = database + _DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key].update(locals()) + + +class Database: + def __init__(self, database_key: Optional[str]) -> None: + self.database = database_key + # Engine is lazy-initialized + self._engine: Optional[sqlalchemy.engine.Engine] = None + + @classmethod + def set_init_hook( + cls, + hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None], + ) -> None: + cls.hook_method = hook_method + + @property + def engine(self) -> sqlalchemy.engine.Engine: + if not self._engine: + connection_params = _DEFAULT_CONNECTION_PARAMS_BY_KEY.get(self.database, {}) + if not connection_params: + raise DBNotPreparedError( + f"No connection parameters found for database key '{self.database}'" + ) + user = connection_params.get("user") + password = connection_params.get("password") + database = connection_params.get("database") + host = connection_params.get("host") + port = connection_params.get("port") + charset = connection_params.get("charset") + collation = connection_params.get("collation") + collation_str = "" + if collation: + collation_str = f"&collation={collation}" + + url = f"mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}?charset={charset}{collation_str}" + self._engine = sqlalchemy.create_engine( + url, + pool_recycle=connection_params.get("pool_recycle"), + pool_size=connection_params.get("pool_size"), + echo=connection_params.get("echo_queries"), + pool_pre_ping=True, + ) + hook_method: Optional[ + Callable[[Optional[str], sqlalchemy.engine.Engine], None] + ] = getattr(self.__class__, "hook_method", None) + if hook_method: + hook_method(database, self._engine) + + return self._engine + + +class DatabaseContainer(dict): + """ + Implementation of a dictionary that always provides a Database class instance, even if the key is missing. + """ + + def __getitem__(self, database: Optional[str]) -> Database: + """ + Override getitem to always return an instance of a database, which includes a lazy-initialized engine. + This also ensures that the database parameters have been initialized before attempting to retrieve a database. + :param database: the database name (may be null for the default database) + :return: a database instance + :raises DBNotPreparedError: when set_default_connection_parameters has not yet been called + """ + if not _DEFAULT_CONNECTION_PARAMS_BY_KEY: + raise DBNotPreparedError( + "Unable to connect to a database, set_default_connection_parameters must first be called" + ) + + if not super().__contains__(database): + super().__setitem__(database, Database(database)) + return super().__getitem__(database) + + @property + def current_database(self) -> Database: + """ + The current database instance, retrieved using contextvars (if python 3.7+) or the default database. + """ + return self.__getitem__(_get_current_database_key()) + + +class DatabaseContainerSingleton(DatabaseContainer): + """ + All instantiations of this class will result in the same instance every time due to the override of + the __new__ method. + """ + + def __new__(cls, *args, **kwargs) -> "DatabaseContainer": + instance = cls.__dict__.get("__instance__") + if instance is not None: + return instance + cls.__instance__ = instance = DatabaseContainer.__new__(cls) + instance.__init__(*args, **kwargs) + return instance diff --git a/dysql/exceptions.py b/dysql/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..19a86e1d679914ddae0692978c25ac2ab30df404 --- /dev/null +++ b/dysql/exceptions.py @@ -0,0 +1,13 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + + +class DBNotPreparedError(Exception): + """ + DB Not Prepared Error + """ diff --git a/dysql/mappers.py b/dysql/mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..f560a6a97725f8e956c22c5b43ae213c834b76b5 --- /dev/null +++ b/dysql/mappers.py @@ -0,0 +1,268 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" +# pylint: disable=too-few-public-methods + +import abc +import logging +from collections import OrderedDict, defaultdict +from typing import Any, Optional, Type + +import sqlalchemy + + +LOGGER = logging.getLogger(__name__) + + +class MapperError(Exception): + pass + + +class DbMapResultBase(abc.ABC): + @classmethod + def get_key_columns(cls): + return ["id"] + + @classmethod + def create_instance(cls, *args, **kwargs) -> "DbMapResultBase": + """ + Called instead of constructor, used to support different ways of + creating objects instead of constructors (if desired). + :return: an instance of the class + """ + return cls(*args, **kwargs) + + @abc.abstractmethod + def map_record(self, record: sqlalchemy.engine.Row) -> None: + """ + Implements logic to handle the mapping of individual record objects from DB records. + :param record: a record row from the database + """ + + @abc.abstractmethod + def raw(self) -> dict: + """ + Retrieves the raw data stored in this object as a dictionary. + :return: the dict representing the object data + """ + + @abc.abstractmethod + def has(self, field: str) -> bool: + """ + Returns true if the field exists in the object. + :param field: the field to check + :return: True if the field exists, false otherwise + """ + + @abc.abstractmethod + def get(self, field: str, default: Any = None) -> Any: + """ + Retrieves the value for the field, returning a default value if the field is not available. + :param field: the field to retrieve + :param default: the default value to return if the field is not available (defaults to None) + :return: the value of the field or the default value + """ + + +class DbMapResult(DbMapResultBase): + def __init__(self, **kwargs): + self.__dict__ = kwargs + # pylint: disable=invalid-name + if not self.__dict__.get("id"): + self.id = None + + def __getitem__(self, field: str) -> Any: + return self.__dict__.get(field) + + def __setitem__(self, field: str, value: Any) -> None: + self.__dict__[field] = value + + def __str__(self) -> str: + return str(self.__dict__) + + def map_record(self, record: sqlalchemy.engine.Row) -> None: + for column, value in record.items(): + self[column] = value + + def raw(self) -> dict: + def get_raw(value: Any) -> dict: + if isinstance(value, DbMapResultBase): + return value.raw() + return value + + raw = {} + for key, value in self.__dict__.items(): + if isinstance(value, list): + raw[key] = list(map(get_raw, value)) + else: + raw[key] = get_raw(value) + # Remove the id field if it was never set + if raw.get("id") is None: + del raw["id"] + return raw + + def has(self, field: str) -> bool: + return self.__dict__.get(field) is not None + + def get(self, field: str, default: Any = None) -> Any: + return self.__dict__.get(field, default) + + +class BaseMapper(metaclass=abc.ABCMeta): + """ + Extend this class and implement the map_records method to map the results from a database query. + """ + + @abc.abstractmethod + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + pass + + +class RecordCombiningMapper(BaseMapper): + """ + Creates one or more mapped results from multiple records. This returns the same or less number + of results as there are records since it potentially combines multiple records with the same + identifier into a single result. + + This depends on ``id`` being a column present in the records. If not, it will return a mapped + result for every row without combining records. Otherwise, a single result is returned for each + unique ``id`` value. + """ + + def __init__(self, record_mapper: Optional[Type[DbMapResultBase]] = DbMapResult): + """ + :param record_mapper: what we are mapping records to. + """ + self.record_mapper = record_mapper + + def _get_lookup(self, record): + """ + Return a lookup key based on a set of defined columns. if the id_columns aren't set we will look for an 'id' + column to maintain older expectations. + :param record: + :return: the value of the 'id' colum if id_columns are not set. the hash of the values from the id_colums. + + Note: if the id_columns contain an invalid column, logs a warning and returns None + """ + key_columns = self.record_mapper.get_key_columns() + if not key_columns: + # preserving older expectations + return None + + values = [] + for column in key_columns: + if column not in record: + # returning none because we don't want to make assumptions about how to handle a complex key + return None + values.append(record[column]) + return hash(tuple(values)) + + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + if not self.record_mapper: + return records + + current_results = OrderedDict() + current_num = 0 + for record in records: + lookup = self._get_lookup(record) + if lookup: + if current_results.get(lookup) is None: + current_results[lookup] = self.record_mapper.create_instance() + current_results[lookup].map_record(record) + else: + current_results[current_num] = self.record_mapper.create_instance() + current_results[current_num].map_record(record) + current_num += 1 + + return list(v for k, v in current_results.items()) + + +class SingleRowMapper(BaseMapper): + """ + Returns a single mapped result from one or more records. The first record is returned even if + there are multiple records from the database. + """ + + def __init__(self, record_mapper: Optional[Type[DbMapResultBase]] = DbMapResult): + self.record_mapper = record_mapper + + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + if not self.record_mapper: + for record in records: + return record + return None + + for record in records: + mapper = self.record_mapper.create_instance() + mapper.map_record(record) + return mapper + return None + + +class SingleColumnMapper(BaseMapper): + """ + Returns the first column value for each record from the database, even if multiple columns are + defined. This will return a list of scalar values. + """ + + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + results = [] + for record in records: + for value in record.values(): + results.append(value) + break + return results + + +class SingleRowAndColumnMapper(BaseMapper): + """ + Returns the first column in the first record from the database, even if multiple records or + columns exist. This will return a single scalar or None if there are no records. + """ + + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + for record in records: + for value in record.values(): + return value + return None + + +class CountMapper(SingleRowAndColumnMapper): + """ + Alias for SingleRowAndColumnMapper, may be used to easily return the result of a count query. + """ + + +class KeyValueMapper(BaseMapper): + """ + :param key_column can be specified to determine what field to map to as the key for are keyed values + :param value_column can be specified to help decide what column to add as a value + :param has_multiple_values_per_key is False by default but when True it tells the keyvalue mapper + the each key may have more than 1 result. this will returns a dictionary of lists when set + + """ + + def __init__(self, key_column=0, value_column=1, has_multiple_values_per_key=False): + if key_column == value_column: + raise MapperError("key and value columns cannot be the same") + + self.key_column = key_column + self.value_column = value_column + self.has_multiple_values_per_key = has_multiple_values_per_key + + def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any: + results = {} + if self.has_multiple_values_per_key: + results = defaultdict(list) + for record in records: + key = record[self.key_column] + value = record[self.value_column] + if self.has_multiple_values_per_key: + results[key].append(value) + else: + results[key] = value + return results diff --git a/dysql/multitenancy.py b/dysql/multitenancy.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb8a769b7cbe3cc0847aef8b5ec6de6b0436988 --- /dev/null +++ b/dysql/multitenancy.py @@ -0,0 +1,69 @@ +""" +Copyright 2025 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import functools +import logging +from typing import Any, Callable, TypeVar +from contextlib import contextmanager + +from dysql.exceptions import DBNotPreparedError +from dysql import ( + set_current_database, + reset_current_database, +) + +LOGGER = logging.getLogger(__name__) + +F = TypeVar("F", bound=Callable[..., Any]) + + +@contextmanager +def tenant_database_manager(database_key: str): + """ + Context manager for temporarily switching to a different database. + + :param database_key: the database key to switch to + :raises DBNotPreparedError: if the database key is not set + """ + if not database_key: + raise DBNotPreparedError( + "Cannot switch to database tenant with empty database key" + ) + + try: + LOGGER.debug(f"Switching to database {database_key}") + set_current_database(database_key) + yield + except Exception as e: + LOGGER.error(f"Error while using database {database_key}: {e}") + raise + finally: + try: + reset_current_database() + LOGGER.debug(f"Reset database context from: {database_key}") + except Exception as e: + LOGGER.error(f"Error resetting database context: {e}") + # Don't re-raise here to avoid masking the original exception + + +def use_database_tenant(database_key: str): + """ + Decorator that switches to a specific database for the duration of the function call. + :param database_key: the database key to use + :return: the decorator function + """ + + def decorator(func: F) -> F: + @functools.wraps(func) + def wrapper(*args, **kwargs): + with tenant_database_manager(database_key): + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/dysql/pydantic_mappers.py b/dysql/pydantic_mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..849ab85107547d474a8bc6968ba95703790845f3 --- /dev/null +++ b/dysql/pydantic_mappers.py @@ -0,0 +1,163 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from typing import Any, Dict, Set + +import sqlalchemy +from pydantic import BaseModel, TypeAdapter + +from .mappers import DbMapResultBase + + +class DbMapResultModel(BaseModel, DbMapResultBase): + """ + Pydantic model that allows for results to be mapped into annotated fields without explicitly + mapping each field. The metadata fields starting with "_" are special fields that allow lists, sets, + and dictionaries to be mapped correctly if more than one record is mapped to an instance. + + Note that validation *does* occur the very first time map_record is called, but not on subsequent runs. Therefore + if you desire better validation for list, set, or dict fields, that must most likely be done outside of pydantic. + + Additionally, lists, sets, and dicts will ignore null values from the database. Therefore you must provide default + values for these fields when used or else validation will fail. + """ + + # List fields that are aggregated into a string of comma seperated values with basic string splitting on commas + _csv_list_fields: Set[str] = set() + # List field that are json objects + _json_fields: Set[str] = set() + # List fields (type does not matter) + _list_fields: Set[str] = set() + # Set fields (type does not matter) + _set_fields: Set[str] = set() + # Dictionary key fields as DB field name => model field name + _dict_key_fields: Dict[str, str] = {} + # Dictionary value fields as model field name => DB field name (this is reversed from _dict_key_fields!) + _dict_value_mappings: Dict[str, str] = {} + + @classmethod + def create_instance(cls, *args, **kwargs) -> "DbMapResultModel": + # Uses the construct method to prevent validation when mapping results + return cls.model_construct(*args, **kwargs) + + def _map_json(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str): + model_field = self.model_fields[field] + value = record[field] + if not value: + return + if not self._has_been_mapped(): + current_dict[field] = TypeAdapter(model_field.annotation).validate_json( + value + ) + + def _map_list(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str): + if record[field] is None: + # Do not map null entries into lists, this may cause problems in the future but it works + # around some other issues when fields are nullable + return + if self._has_been_mapped(): + current_dict[field].append(record[field]) + else: + current_dict[field] = [record[field]] + + def _map_set(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str): + if record[field] is None: + # See note above for lists + return + if self._has_been_mapped(): + current_dict[field].add(record[field]) + else: + current_dict[field] = {record[field]} + + def _map_dict(self, current_dict: dict, record: sqlalchemy.engine.Row, field: str): + model_field_name = self._dict_key_fields[field] + value_field = self._dict_value_mappings[model_field_name] + if record[value_field] is None: + # See note above for lists + return + if self._has_been_mapped(): + current_dict[model_field_name][record[field]] = record[value_field] + else: + current_dict[model_field_name] = {record[field]: record[value_field]} + + def _map_list_from_string( + self, current_dict: dict, record: sqlalchemy.engine.Row, field: str + ): + list_string = record[field] + if not list_string: + # See note above for lists + return + + # force it to be a string + list_string = str(list_string) + values_from_string = list(map(str.strip, list_string.split(","))) + + model_field = self.model_fields[field] + # pre-validates the list we are expecting because we want to ensure all records are validated + values = TypeAdapter(model_field.annotation).validate_python(values_from_string) + + if self._has_been_mapped() and current_dict[field]: + current_dict[field].extend(values) + else: + current_dict[field] = values + + def map_record(self, record: sqlalchemy.engine.Row) -> None: + """ + Implementation of map_record that handles the special "_" prefixed fields listed at the top of this class. + The following rules are used: + - If it is in the _csv_list_fields and is not none, extend the existing list + - If it is in the _list_fields and is not none, append it to the field specified + - If it is in the _set_fields and is not none, add it to the field specified + - If it is in the _dict_key_fields and is not none, add it to the field specified along with the value + from the _dict_value_mappings + - Else add it to the fields to bind to this model + - Remove all DB fields that are present in _dict_value_mappings since they were likely added above + :param record: the DB record + """ + current_dict: dict = self.__dict__ + for field in record.keys(): + if field in self._list_fields: + self._map_list(current_dict, record, field) + elif field in self._csv_list_fields: + self._map_list_from_string(current_dict, record, field) + elif field in self._json_fields: + self._map_json(current_dict, record, field) + elif field in self._set_fields: + self._map_set(current_dict, record, field) + elif field in self._dict_key_fields: + self._map_dict(current_dict, record, field) + else: + # Ignore fields that should have already been set + if not self._has_been_mapped(): + current_dict[field] = record[field] + + # Remove all dict value fields (if present) + for db_field in self._dict_value_mappings.values(): + current_dict.pop(db_field, None) + if self._has_been_mapped(): + # At this point, just update the previous record + self.__dict__.update(current_dict) + else: + # Init takes care of validation and assigning values to each field with conversions in place, etc + self.__init__(**current_dict) # pylint: disable=unnecessary-dunder-call + + def raw(self) -> dict: + return self.model_dump() + + def has(self, field: str) -> bool: + return field in self.__dict__ + + def _has_been_mapped(self): + """ + Tells if a record has already been mapped onto this class or not. + :return: True if map_record has already been called, False otherwise + """ + return bool(self.model_fields_set) + + def get(self, field: str, default: Any = None) -> Any: + return self.__dict__.get(field, default) diff --git a/dysql/query_utils.py b/dysql/query_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d81d94a1887f7f559a46835fe98598e06fa13096 --- /dev/null +++ b/dysql/query_utils.py @@ -0,0 +1,310 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import re + +from typing import Iterable, Optional, Tuple, Union + + +# group 0 - entire string +# group 1 - empty space before template. this helps us ensure we add space to a template but only 1 +# group 2 - template keyword +# group 3 - table_name +# group 4 - column_name +# group 5 - empty space after template. this helps us ensure we add space to a template after but +# only 1 +LIST_TEMPLATE_REGEX = re.compile( + r"(( +)?{(in|not_in|values)__([A-Za-z_]+\.)?([A-Za-z_]+)}( +)?)" +) + + +class TemplateGenerators: + """ + Functions in this class help to return a tuple which contains the query template along with + a dictionary of parameterized values for the query. + """ + + @classmethod + def get_template(cls, name: str): + if name == "in": + return cls.in_column + if name == "not_in": + return cls.not_in_column + if name == "values": + return cls.values + return None + + @staticmethod + def in_column( + name: str, + values: Union[str, Iterable[str]], + legacy_key: str = None, + is_multi_column: bool = False, + ) -> Tuple[str, Optional[dict]]: + """ + Returns query and params for using "IN" SQL queries. + :param name: the field name + :param values: the field values + :param legacy_key: + :param is_multi_column: needed when more than one field is being compared as part of the in statement + :return: a tuple of the query string and the params dictionary + """ + if not values: + return "1 <> 1", None + key_name = TemplateGenerators._get_key(name, legacy_key, is_multi_column) + keys, values = TemplateGenerators._parameterize_list(key_name, values) + if is_multi_column: + keys = f"({keys})" + return f"{name} IN {keys}", values + + @staticmethod + def in_multi_column( + name: str, values: Union[str, Iterable[str]], legacy_key: str = None + ): + """ + A wrapper for in_column with is_multi_column set to true + """ + return TemplateGenerators.in_column(name, values, legacy_key, True) + + @staticmethod + def not_in_column( + name: str, + values: Union[str, Iterable[str]], + legacy_key: str = None, + is_multi_column: bool = False, + ) -> Tuple[str, Optional[dict]]: + """ + Returns query and params for using "NOT IN" SQL queries. + :param name: the field name + :param values: the field values + :param legacy_key: + :param is_multi_column: needed when more than one field is being compared as part of the not in statement + :return: a tuple of the query string and the params dictionary + """ + if not values: + return "1 = 1", None + key_name = TemplateGenerators._get_key(name, legacy_key, is_multi_column) + keys, values = TemplateGenerators._parameterize_list(key_name, values) + if is_multi_column: + keys = f"({keys})" + return f"{name} NOT IN {keys}", values + + @staticmethod + def not_in_multi_column( + name: str, values: Union[str, Iterable[str]], legacy_key: str = None + ): + """ + A wrapper for not_in_column with is_multi_column set to true + """ + return TemplateGenerators.not_in_column(name, values, legacy_key, True) + + @staticmethod + def values( + name: str, + values: Union[str, Iterable[str]], + legacy_key: str = None, + ) -> Tuple[str, Optional[dict]]: + """ + Returns query and params for using "VALUES" SQL queries. + :param name: the field name + :param values: the values + :param legacy_key: + :return: a tuple of the query string and the params dictionary + """ + if not values: + raise ListTemplateException(f"Must have values for {name} template") + key_name = TemplateGenerators._get_key(name, legacy_key, False) + keys, values = TemplateGenerators._parameterize_list(key_name, values) + return f"VALUES {keys}", values + + @staticmethod + def _get_key(key: str, legacy_key: str, is_multi_column: bool) -> str: + key_name = key + if legacy_key: + key_name = legacy_key + if is_multi_column: + key_name = re.sub("[, ()]", "", key_name) + return key_name + + @staticmethod + def _parameterize_inner_list( + key: str, values: Union[str, Iterable[str]] + ) -> Tuple[str, Optional[dict]]: + param_values = {} + parameterized_keys = [] + if not isinstance(values, (list, tuple, set)): + param_values[key] = values + parameterized_keys.append(key) + else: + for index, value in enumerate(values): + parameterized_key = f"{key.replace('.', '_')}_{str(index)}" + param_values[parameterized_key] = value + parameterized_keys.append(parameterized_key) + + return f"( :{', :'.join(parameterized_keys)} )", param_values + + @staticmethod + def _parameterize_list( + key: str, values: Union[str, Iterable[str]] + ) -> Tuple[str, Optional[dict]]: + """ + Build a string with parameterized values and a dictionary + with key value pairs matching the string parameters. + :return a tuple of the parameter string and the dictionary of parameter values + """ + param_values = {} + param_inner_keys = [] + + if isinstance(values, str): + values = tuple((values,)) + + for index, value in enumerate(values): + if isinstance(value, tuple) or key.startswith("values"): + ( + param_string, + inner_param_values, + ) = TemplateGenerators._parameterize_inner_list( + f"{key}_{str(index)}", value + ) + param_values.update(inner_param_values) + param_inner_keys.append(param_string) + else: + return TemplateGenerators._parameterize_inner_list(key, values) + + return ", ".join(param_inner_keys), param_values + + +class ListTemplateException(Exception): + """ + List Template Exception + """ + + +class QueryDataError(Exception): + """ + This exception is thrown when we expect a QueryData object but end up with something different + """ + + +class QueryData: + # pylint: disable=too-few-public-methods + """ + Query data is a wrapper class that allows us to pass back information for a query with more + information and specification. this helps to have template queries with template parameters but + to still have the ability to have query parameters that get parameterized on the query. + """ + + def __init__( + self, + query: str, + query_params: dict = None, + template_params: dict = None, + ): + """ + Constructor. + :param query: the SQL query + :param query_params: object or list of objects containing values to apply to parameters + + examples of a queryparams passed to a QueryData + + Single Object + QueryData( + "SELECT * FROM table WHERE value_a=:value_a and value_b=:value_b", + query_params={'value_a': 1, 'value_b': 'b' } + ) + + List of Objects (Note: this will create a query for each object, it may not be possible or + even desirable but, using template_params will create a single query with the params) + QueryData( + "SELECT * FROM table WHERE value_a=:value_a` and value_b=:value_b", + query_params=[{'value_a': 1, 'value_b': 'b' }, {'value_a': 1, 'value_b': 'b' }] + ) + :param template_params: these are templates that can be added to queries to generate a single + parameterized query. + + examples of current list templates and transformations + + "IN (... )" + QueryData( + "SELECT * FROM table where name {in__name}", + template_params={'in__name' : ['bob','tom','chic']} + ) + {in__actor.name} -> actor.name IN ('bob', 'tom', ' ), + + "NOT IN (... )" + QueryData( + "SELECT * FROM table wher name {in__name}", + template_params={'in__name' : ['bob','tom','chic']} + ) + {not_in__actor.name} -> actor.name NOT IN ('name1','name2',...), + + "VALUES (), (), ()..." + {values__actors} -> VALUES (a1.v1,a1.v2,a1.v3), (a1.v1,a1.v2,a1.v3),... + """ + self.query = query + self.query_params = query_params + self.template_params = template_params + + +def __validate_keys_clean_query(query, template_params): + validated_keys = [] + for groups in re.findall(LIST_TEMPLATE_REGEX, query): + # check first group for the full key + key = f"{groups[2]}__{groups[3] if groups[3] else ''}{groups[4]}" + validated_keys.append(key) + missing_keys = [] + + # validate + if template_params is None or template_params.get(key) is None: + missing_keys.append(key) + elif key == "values" and len(template_params.get(key)) == 0: + missing_keys.append(key) + + if len(missing_keys) > 0: + raise ListTemplateException(f"Missing template keys {missing_keys}") + + # Clean whitespace as templates will add their own padding later on + query = query.replace(groups[0], groups[0].strip()) + return query, validated_keys + + +def __validate_query_and_params(data: QueryData) -> None: + if not isinstance(data, QueryData): + raise QueryDataError( + "SQL annotated methods must return an instance of QueryData for query information" + ) + + +def get_query_data(data: QueryData) -> Tuple[str, dict]: + """ + Retrieves the query and parameters from a QueryData object. + :param data: the query data object + :return: a tuple of the query string and the params + """ + __validate_query_and_params(data) + + params = {} + query, validated_keys = __validate_keys_clean_query( + data.query, data.template_params + ) + + if data.query_params: + params.update(data.query_params) + + for key in validated_keys: + list_template_key, column_name = tuple(key.split("__")) + template_to_use = TemplateGenerators.get_template(list_template_key) + template_query, param_dict = template_to_use( + column_name, data.template_params[key], legacy_key=key + ) + if param_dict: + params.update(param_dict) + query_key = "{" + key + "}" + query = query.replace(query_key, f" {template_query} ") + + return query, params diff --git a/dysql/test/__init__.py b/dysql/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c728d6b57c3fb12322b9120698c97d970bee6fc3 --- /dev/null +++ b/dysql/test/__init__.py @@ -0,0 +1,55 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import Mock + +from dysql import set_default_connection_parameters, databases + + +def setup_mock_engine(mock_create_engine): + """ + build up the basics of a mock engine for the database + :return: mocked engine for use and manipulation in testing + """ + mock_engine = Mock() + mock_engine.connect().execution_options().__enter__ = Mock() + mock_engine.connect().execution_options().__exit__ = Mock() + set_default_connection_parameters("fake", "user", "password", "test") + + # Clear out the databases before attempting to mock anything + databases.DatabaseContainerSingleton().clear() + mock_create_engine.return_value = mock_engine + return mock_engine + + +def verify_query_params(mock_engine, expected_query, expected_args): + verify_query(mock_engine, expected_query) + verify_query_args(mock_engine, expected_args) + + +def verify_query(mock_engine, expected_query): + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + query = execute_call.call_args[0][0].text + assert query == expected_query + + +def verify_query_args(mock_engine, expected_args): + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + query_args = execute_call.call_args[0][1] + + assert query_args + for expected_key in expected_args: + expected_value = expected_args[expected_key] + assert query_args.get(expected_key) + assert expected_value == query_args[expected_key] diff --git a/dysql/test/conftest.py b/dysql/test/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ddc3966643f63ba242456eb72b754b132a8cde --- /dev/null +++ b/dysql/test/conftest.py @@ -0,0 +1,19 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import patch +import pytest + + +@pytest.fixture(name="mock_create_engine") +def mock_create_engine_fixture(): + create_mock = patch("dysql.databases.sqlalchemy.create_engine") + try: + yield create_mock.start() + finally: + create_mock.stop() diff --git a/dysql/test/test_annotations.py b/dysql/test/test_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..f01b6d23da2f639be26c9ba417f4d6a76c564000 --- /dev/null +++ b/dysql/test/test_annotations.py @@ -0,0 +1,68 @@ +""" +Copyright 2023 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from typing import List, Union + +import pytest +from pydantic import BaseModel, ValidationError + +from dysql.annotations import FromCSVToList + + +class StrCSVModel(BaseModel): + values: FromCSVToList[List[str]] + + +class IntCSVModel(BaseModel): + values: FromCSVToList[List[int]] + + +class NullableStrCSVModel(BaseModel): + values: FromCSVToList[Union[List[str], None]] + + +class NullableIntCSVModel(BaseModel): + values: FromCSVToList[Union[List[int], None]] + + +@pytest.mark.parametrize( + "cls, values, expected", + [ + (StrCSVModel, "1,2,3", ["1", "2", "3"]), + (StrCSVModel, "a,b", ["a", "b"]), + (StrCSVModel, "a", ["a"]), + (NullableStrCSVModel, "", None), + (NullableStrCSVModel, None, None), + (StrCSVModel, ["a", "b"], ["a", "b"]), + (StrCSVModel, ["a", "b", "c"], ["a", "b", "c"]), + (IntCSVModel, "1,2,3", [1, 2, 3]), + (IntCSVModel, "1", [1]), + (NullableIntCSVModel, "", None), + (NullableIntCSVModel, None, None), + (IntCSVModel, ["1", "2", "3"], [1, 2, 3]), + (IntCSVModel, ["1", "2", "3", 4, 5], [1, 2, 3, 4, 5]), + ], +) +def test_from_csv_to_list(cls, values, expected): + assert expected == cls(values=values).values + + +@pytest.mark.parametrize( + "cls, values", + [ + (StrCSVModel, ""), + (StrCSVModel, None), + (IntCSVModel, "a,b,c"), + (IntCSVModel, ""), + (IntCSVModel, None), + (IntCSVModel, ["a", "b", "c"]), + ], +) +def test_from_csv_to_list_invalid(cls, values): + with pytest.raises(ValidationError): + cls(values=values) diff --git a/dysql/test/test_database_initialization.py b/dysql/test/test_database_initialization.py new file mode 100644 index 0000000000000000000000000000000000000000..4c226f8a6d301dfdf0bdaf4f2effbdb8e5f1af5f --- /dev/null +++ b/dysql/test/test_database_initialization.py @@ -0,0 +1,240 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest import mock + +import pytest + +import dysql.connections +from dysql import ( + sqlquery, + DBNotPreparedError, + set_default_connection_parameters, + QueryData, + set_database_init_hook, +) +from dysql.test import setup_mock_engine + + +""" +These tests reflect what can happen when dealing with a config passing in a value that may not +have been set. There are some parameters that are absolutely necessary, if they aren't set we +want to make sure we are warning the user in different ways. +""" + + +@sqlquery() +def query(): + """ + This is used to call the code that would initialize the database on the first time. + If there were any failures this is where we would expect to see them. + """ + return QueryData("SELECT * FROM table") + + +@pytest.fixture(autouse=True, name="mock_engine") +def fixture_mock_engine(mock_create_engine): + dysql.databases.DatabaseContainerSingleton().clear() + dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear() + + # Reset the database before the test + dysql.databases.reset_current_database() + + yield setup_mock_engine(mock_create_engine) + + # Reset database after the test as well + dysql.databases.reset_current_database() + + +@pytest.fixture(autouse=True) +def fixture_reset_init_hook(): + yield + if hasattr(dysql.databases.Database, "hook_method"): + delattr(dysql.databases.Database, "hook_method") + + +def test_nothing_set(): + dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear() + with pytest.raises(DBNotPreparedError) as error: + query() + assert ( + str(error.value) + == "Unable to connect to a database, set_default_connection_parameters must first be called" + ) + + +@pytest.mark.parametrize( + "host, user, password, database, failed_field", + [ + (None, "u", "p", "d", "host"), + ("", "u", "p", "d", "host"), + ("h", None, "p", "d", "user"), + ("h", "", "p", "d", "user"), + ("h", "u", None, "d", "password"), + ("h", "u", "", "d", "password"), + ("h", "u", "p", None, "database"), + ("h", "u", "p", "", "database"), + ], +) +def test_fields_required(host, user, password, database, failed_field): + with pytest.raises(DBNotPreparedError) as error: + set_default_connection_parameters(host, user, password, database) + assert ( + str(error.value) + == f'Database parameter "{failed_field}" is not set or empty and is required' + ) + + +def test_minimal_credentials(mock_engine): + set_default_connection_parameters("h", "u", "p", "d") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + + +def test_init_hook(mock_engine): + init_hook = mock.MagicMock() + set_database_init_hook(init_hook) + set_default_connection_parameters("h", "u", "p", "d") + dysql.databases.set_current_database("d") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + init_hook.assert_called_once_with("d", mock_engine) + + +def test_init_hook_multiple_databases(mock_engine): + init_hook = mock.MagicMock() + set_database_init_hook(init_hook) + set_default_connection_parameters("h1", "u1", "p1", "d1") + set_default_connection_parameters("h2", "u2", "p2", "d2") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + dysql.databases.set_current_database("d1") + query() + assert init_hook.call_args_list == [ + mock.call("test", mock_engine), + mock.call("d1", mock_engine), + ] + dysql.databases.set_current_database("d2") + query() + assert init_hook.call_args_list == [ + mock.call("test", mock_engine), + mock.call("d1", mock_engine), + mock.call("d2", mock_engine), + ] + + +def test_current_database_default(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + assert len(db_container) == 0 + mock_engine.connect().execution_options().execute.return_value = [] + query() + + # Only one database is initialized + assert len(db_container) == 1 + assert "test" in db_container + assert db_container.current_database.database == "test" + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_different_charset_collation(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + set_default_connection_parameters( + "host", + "user", + "password", + "database", + charset="other", + collation="other_collation", + ) + assert len(db_container) == 0 + dysql.databases.set_current_database("database") + mock_engine.connect().execution_options().execute.return_value = [] + query() + + # Only one database is initialized + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://user:password@host:3306/database?charset=other&collation=other_collation", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_is_set_current_database_supported(): + # This test only asserts that true is always returned since this method is deprecated + assert dysql.databases.is_set_current_database_supported() + + +def test_current_database_set(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + set_default_connection_parameters("h1", "u1", "p1", "d1", database_key="db1") + dysql.databases.set_current_database("db1") + mock_engine.connect().execution_options().execute.return_value = [] + query() + + assert len(db_container) == 1 + assert "db1" in db_container + assert db_container.current_database.database == "db1" + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://u1:p1@h1:3306/d1?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_current_database_cached(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + mock_engine.connect().execution_options().execute.return_value = [] + query() + + assert len(db_container) == 1 + assert "test" in db_container + assert db_container.current_database.database == "test" + + set_default_connection_parameters("h1", "u1", "p1", "db1") + dysql.databases.set_current_database("db1") + query() + assert len(db_container) == 2 + assert "test" in db_container + assert db_container.current_database.database == "db1" + + # Set back to default + dysql.databases.reset_current_database() + query() + assert len(db_container) == 2 + assert db_container.current_database.database == "test" + + assert mock_create_engine.call_count == 2 + assert mock_create_engine.call_args_list == [ + mock.call( + "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ), + mock.call( + "mysql+mysqlconnector://u1:p1@h1:3306/db1?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ), + ] diff --git a/dysql/test/test_mappers.py b/dysql/test/test_mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..bc59893714eb77ed582f22850d44b7e3aa3daf32 --- /dev/null +++ b/dysql/test/test_mappers.py @@ -0,0 +1,227 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql import ( + RecordCombiningMapper, + SingleRowMapper, + SingleColumnMapper, + SingleRowAndColumnMapper, + CountMapper, + KeyValueMapper, +) +from dysql.mappers import MapperError + + +class TestMappers: + """ + Test Mappers + """ + + @staticmethod + def _unwrap_results(results): + return [r.raw() for r in results] + + def test_record_combining(self): + mapper = RecordCombiningMapper() + assert len(mapper.map_records([])) == 0 + assert self._unwrap_results(mapper.map_records([{"a": 1, "b": 2}])) == [ + {"a": 1, "b": 2} + ] + assert self._unwrap_results( + mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) + ) == [ + {"id": 1, "a": 1, "b": 2, "c": 3}, + {"id": 2, "a": 1, "b": 2}, + ] + + @staticmethod + def test_record_combining_no_record_mapper(): + mapper = RecordCombiningMapper(record_mapper=None) + assert len(mapper.map_records([])) == 0 + assert mapper.map_records([{"a": 1, "b": 2}]) == [{"a": 1, "b": 2}] + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) == [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + + @staticmethod + def test_single_row(): + mapper = SingleRowMapper() + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]).raw() == {"a": 1, "b": 2} + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ).raw() == {"id": 1, "a": 1, "b": 2} + + @staticmethod + def test_single_row_no_record_mapper(): + mapper = SingleRowMapper(record_mapper=None) + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]) == {"a": 1, "b": 2} + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) == {"id": 1, "a": 1, "b": 2} + + @staticmethod + def test_single_column(): + mapper = SingleColumnMapper() + assert len(mapper.map_records([])) == 0 + assert mapper.map_records([{"a": 1, "b": 2}]) == [1] + assert mapper.map_records( + [ + {"id": "myid1", "a": 1, "b": 2}, + {"id": "myid2", "a": 1, "b": 2}, + {"id": "myid3", "c": 3}, + ] + ) == ["myid1", "myid2", "myid3"] + + @staticmethod + @pytest.mark.parametrize( + "mapper", + [ + SingleRowAndColumnMapper(), + # Alias for the other one + CountMapper(), + ], + ) + def test_single_column_and_row(mapper): + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]) == 1 + assert ( + mapper.map_records( + [ + {"id": "myid", "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) + == "myid" + ) + + @staticmethod + @pytest.mark.parametrize( + "mapper, expected", + [ + (KeyValueMapper(), {"a": 4, "b": 7}), + (KeyValueMapper(key_column="column_named_something"), {"a": 4, "b": 7}), + (KeyValueMapper(value_column="column_with_some_value"), {"a": 4, "b": 7}), + ( + KeyValueMapper(has_multiple_values_per_key=True), + {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]}, + ), + ( + KeyValueMapper( + key_column="column_named_something", + has_multiple_values_per_key=True, + ), + {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]}, + ), + ( + KeyValueMapper( + key_column="column_with_some_value", + value_column="column_named_something", + has_multiple_values_per_key=True, + ), + { + 1: ["a"], + 2: ["a"], + 3: ["a", "b"], + 4: ["a", "b"], + 5: ["b"], + 6: ["b"], + 7: ["b"], + }, + ), + ( + KeyValueMapper( + key_column="column_with_some_value", + value_column="column_named_something", + ), + {1: "a", 2: "a", 3: "b", 4: "b", 5: "b", 6: "b", 7: "b"}, + ), + ], + ) + def test_key_mapper_key_has_multiple(mapper, expected): + result = mapper.map_records( + [ + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 1] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 2] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 3] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 4] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 3] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 4] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 5] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 6] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 7] + ), + ] + ) + assert len(result) == len(expected) + assert result == expected + + @staticmethod + def test_key_mapper_key_value_same(): + with pytest.raises( + MapperError, match="key and value columns cannot be the same" + ): + KeyValueMapper(key_column="same", value_column="same") + + +class HelperRow: # pylint: disable=too-few-public-methods + """ + Helper class does the most basic functionality we see when accessing records passed in + """ + + def __init__(self, fields, values): + self.fields = fields + self.values = values + + def __getitem__(self, key): + if isinstance(key, int): + return self.values[key] + return self.values[self.fields.index(key)] diff --git a/dysql/test/test_mariadbmap_tojson.py b/dysql/test/test_mariadbmap_tojson.py new file mode 100644 index 0000000000000000000000000000000000000000..5b3270e40361d7d819f6c91d8b003c6d6ec7415f --- /dev/null +++ b/dysql/test/test_mariadbmap_tojson.py @@ -0,0 +1,47 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import json +import pytest + +from dysql import DbMapResult + + +@pytest.mark.parametrize( + "name, expected_json, mariadb_map", + [ + ( + "basic", + '{"id": 1, "name": "test"}', + DbMapResult(id=1, name="test"), + ), + ( + "basic_with_list", + '{"id": 1, "name": "test", "my_list": ["a", "b", "c"]}', + DbMapResult(id=1, name="test", my_list=["a", "b", "c"]), + ), + ( + "inner_map", + '{"id": 1, "inner_map": {"id": 2, "name": "inner_test"}}', + DbMapResult(id=1, inner_map=DbMapResult(id=2, name="inner_test")), + ), + ( + "inner_list_of_maps", + '{"id": 1, "inner_map_list": [{"id": 2, "name": "inner_test_2"}, {"id": 3, "name": "inner_test_3"}]}', + DbMapResult( + id=1, + inner_map_list=[ + DbMapResult(id=2, name="inner_test_2"), + DbMapResult(id=3, name="inner_test_3"), + ], + ), + ), + ], +) +def test_raw_json_format(name, expected_json, mariadb_map): + assert json.dumps(mariadb_map.raw()) == expected_json, "error with " + name diff --git a/dysql/test/test_pydantic_mappers.py b/dysql/test/test_pydantic_mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..b917d0e8498fcdfbc577be81b07aaa230c47f5b6 --- /dev/null +++ b/dysql/test/test_pydantic_mappers.py @@ -0,0 +1,291 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import json +from typing import Any, Dict, List, Set, Optional +import pytest + +from pydantic import ValidationError + +from dysql import ( + RecordCombiningMapper, + SingleRowMapper, +) +from dysql.pydantic_mappers import DbMapResultModel + + +class ConversionDbModel(DbMapResultModel): + id: int + field_str: str + field_int: int + field_bool: bool + + +class CombiningDbModel(DbMapResultModel): + _list_fields: Set[str] = {"list1"} + _set_fields: Set[str] = {"set1"} + _dict_key_fields: Dict[str, str] = {"key1": "dict1", "key2": "dict2"} + _dict_value_mappings: Dict[str, str] = {"dict1": "val1", "dict2": "val2"} + + id: int = None + list1: List[str] + set1: Set[str] = set() + dict1: Dict[str, Any] = {} + dict2: Dict[str, int] = {} + + +class DefaultListCombiningDbModel(CombiningDbModel): + list1: List[str] = [] + + +class ListWithStringsModel(DbMapResultModel): + _csv_list_fields: Set[str] = {"list1", "list2"} + + id: int + list1: Optional[List[str]] = None + list2: List[int] = [] # help test empty list gets filled + + +class JsonModel(DbMapResultModel): + _json_fields: Set[str] = {"json1", "json2"} + + id: int + json1: dict + json2: Optional[dict] = None + + +class MultiKeyModel(DbMapResultModel): + @classmethod + def get_key_columns(cls): + return ["a", "b"] + + _list_fields = {"c"} + a: int + b: str + c: List[str] + + +def _unwrap_results(results): + return [r.raw() for r in results] + + +def test_field_conversion(): + mapper = SingleRowMapper(record_mapper=ConversionDbModel) + assert mapper.map_records( + [ + {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": 1}, + ] + ).raw() == {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": True} + + +def test_complex_object_record_combining(): + mapper = RecordCombiningMapper(record_mapper=CombiningDbModel) + assert len(mapper.map_records([])) == 0 + assert _unwrap_results( + mapper.map_records( + [ + { + "id": 1, + "list1": "val1", + "set1": "val2", + "key1": "k1", + "val1": "v1", + "key2": "k3", + "val2": 3, + }, + {"id": 2, "list1": "val1"}, + { + "id": 1, + "list1": "val3", + "set1": "val4", + "key1": "k2", + "val1": "v2", + "key2": "k4", + "val2": 4, + }, + ] + ) + ) == [ + { + "id": 1, + "list1": ["val1", "val3"], + "set1": {"val2", "val4"}, + "dict1": {"k1": "v1", "k2": "v2"}, + "dict2": {"k3": 3, "k4": 4}, + }, + { + "id": 2, + "list1": ["val1"], + "set1": set(), + "dict1": {}, + "dict2": {}, + }, + ] + + +def test_record_combining_multi_column_id(): + mapper = RecordCombiningMapper(MultiKeyModel) + assert len(mapper.map_records([])) == 0 + assert _unwrap_results( + mapper.map_records( + [ + {"a": 1, "b": "test", "c": "one"}, + {"a": 1, "b": "test", "c": "two"}, + {"a": 1, "b": "test", "c": "three"}, + {"a": 2, "b": "test", "c": "one"}, + {"a": 2, "b": "test", "c": "two"}, + {"a": 1, "b": "othertest", "c": "one"}, + ] + ) + ) == [ + {"a": 1, "b": "test", "c": ["one", "two", "three"]}, + {"a": 2, "b": "test", "c": ["one", "two"]}, + {"a": 1, "b": "othertest", "c": ["one"]}, + ] + + +def test_complex_object_with_null_values(): + mapper = SingleRowMapper(record_mapper=DefaultListCombiningDbModel) + assert mapper.map_records( + [ + {"id": 1}, + ] + ).raw() == { + "id": 1, + "list1": [], + "set1": set(), + "dict1": {}, + "dict2": {}, + } + + +def test_csv_list_field(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [{"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}] + ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_single_value(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records([{"id": 1, "list1": "a", "list2": "1"}]).raw() == { + "id": 1, + "list1": ["a"], + "list2": [1], + } + + +def test_csv_list_field_empty_string(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records([{"id": 1, "list1": "", "list2": ""}]).raw() == { + "id": 1, + "list1": None, + "list2": [], + } + + +def test_csv_list_field_extends(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b", "list2": "1,2"}, + {"id": 1, "list1": "c,d", "list2": "3,4"}, + ] + )[0].raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_multiple_records_duplicates(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}, + {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}, + ] + )[0].raw() == { + "id": 1, + "list1": ["a", "b", "c", "d", "a", "b", "c", "d"], + "list2": [1, 2, 3, 4, 1, 2, 3, 4], + } + + +def test_csv_list_field_none_in_first_record(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b,c,d", "list2": None}, + {"id": 1, "list1": "e,f,g", "list2": "1,2,3,4"}, + ] + )[0].raw() == { + "id": 1, + "list1": ["a", "b", "c", "d", "e", "f", "g"], + "list2": [1, 2, 3, 4], + } + + +def test_csv_list_field_without_mapping_ignored(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [{"id": 1, "list1": "a,b, c,d", "list2": "1,2,3,4", "list3": "x,y,z"}] + ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_invalid_type(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + with pytest.raises(ValidationError, match="1 validation error for list"): + mapper.map_records( + [ + {"id": 1, "list1": "a,b", "list2": "1,2"}, + {"id": 1, "list1": "c,d", "list2": "3,a"}, + ] + ) + + +def test_json_field(): + mapper = SingleRowMapper(record_mapper=JsonModel) + assert mapper.map_records( + [ + { + "id": 1, + "json1": json.dumps( + {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}} + ), + } + ] + ).model_dump() == { + "id": 1, + "json1": {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}}, + "json2": None, + } + + +@pytest.mark.parametrize( + "json1, json2", + [ + ('{ "json": value', None), + ('{ "json": value', '{ "json": value }'), + ('{ "json": value }', '{ "json": value'), + (None, '{ "json": value'), + ], +) +def test_invalid_json(json1, json2): + with pytest.raises(ValidationError, match="Invalid JSON"): + mapper = SingleRowMapper(record_mapper=JsonModel) + mapper.map_records([{"id": 1, "json1": json1, "json2": json2}]) + + +def test_json_none(): + mapper = SingleRowMapper(record_mapper=JsonModel) + assert mapper.map_records( + [{"id": 1, "json1": '{ "first": "value" }', "json2": None}] + ).model_dump() == { + "id": 1, + "json1": { + "first": "value", + }, + "json2": None, + } diff --git a/dysql/test/test_sql_decorator.py b/dysql/test/test_sql_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..c236dd06f5b85cf5eca0220263a0bb4efd659733 --- /dev/null +++ b/dysql/test/test_sql_decorator.py @@ -0,0 +1,399 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql import ( + sqlupdate, + sqlquery, + DbMapResult, + CountMapper, + SingleRowMapper, + QueryData, + QueryDataError, +) +from dysql.test import setup_mock_engine + + +class TestSqlSelectDecorator: + """ + Test Sql Select Decorator + """ + + @staticmethod + @pytest.fixture + def mock_results(): + return [ + { + "id": 1, + "name": "jack", + "email": "jack@adobe.com", + "hobbies": ["golf", "bikes", "coding"], + }, + { + "id": 2, + "name": "flora", + "email": "flora@adobe.com", + "hobbies": ["golf", "coding"], + }, + { + "id": 3, + "name": "Terrence", + "email": "terrence@adobe.com", + "hobbies": ["coding", "watching tv", "hot dog eating contest"], + }, + ] + + @staticmethod + @pytest.fixture + def mock_engine(mock_results, mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + return mock_engine + + @staticmethod + def test_non_query_data_fails(mock_create_engine): + # This argument forces the fixture setup + _ = mock_create_engine + + @sqlquery() + def select_with_string(): + return "SELECT" + + with pytest.raises(QueryDataError): + select_with_string() + + def test_map_not_specified(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + assert isinstance(list(self._select_all())[0], DbMapResult) + + def test_single(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + result = self._select_single() + assert isinstance(result, DbMapResult) + + def test_count(self, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [ + {"count": 2}, + {"count": 3}, + ] + assert self._select_count() == 2 + + def test_execute_no_params(self, mock_engine): + self._select_all() + mock_engine.connect.return_value.execution_options.return_value.execute.assert_called() + call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args + assert call_args[0][0].text == "SELECT * FROM my_table" + assert call_args[0][1] == {} + + def test_execute_params(self, mock_engine): + self._select_filtered(3) + mock_engine.connect.return_value.execution_options.return_value.execute.assert_called() + + call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args + assert call_args[0][0].text == "SELECT * FROM my_table WHERE id=:id" + assert call_args[0][1] == {"id": 3} + + def test_list_results_map(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [ + mock_results[2] + ] + results = self._select_filtered(3) + + assert len(results) == 1 + assert len(list(results)[0].hobbies) == 3 + + def test_isolation_default(self, mock_engine): + mock_connect = mock_engine.connect.return_value.execution_options + self._select_all() + mock_connect.assert_called_with(isolation_level="READ_COMMITTED") + + def test_isolation_default_read_uncommited(self, mock_engine): + mock_connect = mock_engine.connect.return_value.execution_options + self._select_uncommitted() + mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED") + mock_connect.return_value.execute.assert_called() + + @staticmethod + @sqlquery() + def _select_all(): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + """ + return QueryData("SELECT * FROM my_table") + + @staticmethod + @sqlquery(mapper=SingleRowMapper()) + def _select_single(): + return QueryData("SELECT * FROM my_table") + + @staticmethod + @sqlquery(mapper=CountMapper) + def _select_count(): + return QueryData("SELECT COUNT(*) FROM my_table") + + @staticmethod + @sqlquery() + def _select_filtered(_id): + return QueryData( + "SELECT * FROM my_table WHERE id=:id", query_params={"id": _id} + ) + + @staticmethod + @sqlquery(isolation_level="READ_UNCOMMITTED") + def _select_uncommitted(): + return QueryData("SELECT * FROM uncommitted") + + +class TestSqlUpdateDecorator: + """ + Test Sql Update Decorator + """ + + @staticmethod + @pytest.fixture + def mock_engine(mock_create_engine): + return setup_mock_engine(mock_create_engine) + + @staticmethod + @pytest.fixture + def mock_connect(mock_engine): + return mock_engine.connect.return_value.execution_options + + def test_isolation_default(self, mock_connect): + self._update_something({"id": 1, "value": "test"}) + mock_connect.assert_called_with(isolation_level="READ_COMMITTED") + + def test_isolation_default_read_uncommited(self, mock_connect): + self._update_something_uncommited_isolation({"id": 1, "value": "test"}) + mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED") + mock_connect.return_value.begin.assert_called() + mock_connect.return_value.begin.return_value.commit.assert_called() + mock_connect.return_value.__exit__.assert_called() + + def test_transaction(self, mock_connect): + self._update_something({"id": 1, "value": "test"}) + mock_connect().begin.assert_called() + mock_connect().begin.return_value.commit.assert_called() + mock_connect().__exit__.assert_called() + + def test_transaction_fails(self, mock_connect): + mock_connect().execute.side_effect = Exception("error") + with pytest.raises(Exception): + self._update_something({"id": 1, "value": "test"}) + mock_connect().begin.return_value.commit.assert_not_called() + mock_connect().begin.return_value.rollback.assert_called() + mock_connect().__exit__.assert_called() + + def test_execute_passes_values(self, mock_engine): + values = {"id": 1, "value": "test"} + self._update_something(values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + execute_call_args = execute_call.call_args[0] + assert execute_call_args[0].text == "INSERT something" + assert values == execute_call_args[1] + + def test_execute_query_values_none(self, mock_engine): + self._update_something(None) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + self._expect_args_list(execute_call.call_args_list[0], "INSERT something") + + def test_execute_query_values_not_given(self, mock_engine): + # pylint: disable=unused-argument + self._update_something_no_params() + + def test_execute_multi_yield(self, mock_connect): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + self._update_something_multi_yield(expected_values) + + execute_call = mock_connect().execute + assert execute_call.call_count == 3 + + for call_args in execute_call.call_args_list: + self._expect_args_list(call_args, "INSERT something") + + def test_execute_fails_list_if_multi_false(self): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + with pytest.raises(Exception): + self._update_list_when_multi_false(expected_values) + + def test_execute_multi_yield_and_lists(self, mock_engine): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + other_expected_values = [ + {"id": 5, "value": "test 5"}, + {"id": 6, "value": "test 6"}, + {"id": 7, "value": "test 7"}, + ] + self._update_yield_with_lists(expected_values, other_expected_values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 2 + + self._expect_args_list( + execute_call.call_args_list[0], + "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), " + "( :values__in_2_0, :values__in_2_1 ) ", + ) + self._expect_args_list( + execute_call.call_args_list[1], + "INSERT some more VALUES ( :values__other_0_0, :values__other_0_1 ), " + "( :values__other_1_0, :values__other_1_1 ), ( :values__other_2_0, :values__other_2_1 ) ", + ) + + def test_execute_multi_yield_and_lists_some_no_params(self, mock_engine): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + self._update_yield_with_lists_some_no_params(expected_values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 4 + + self._expect_args_list( + execute_call.call_args_list[0], + "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), " + "( :values__in_2_0, :values__in_2_1 ) ", + ) + self._expect_args_list(execute_call.call_args_list[1], "UPDATE some more") + self._expect_args_list(execute_call.call_args_list[2], "UPDATE some more") + self._expect_args_list(execute_call.call_args_list[3], "DELETE some more") + + def test_set_foreign_key_checks_default(self, mock_engine): + self._update_something_no_params() + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 1 + + def test_set_foreign_key_checks_true(self, mock_engine): + self._update_without_foreign_key_checks() + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 4 + assert execute_call.call_args_list[0][0][0].text == "SET FOREIGN_KEY_CHECKS=0" + assert execute_call.call_args_list[-1][0][0].text == "SET FOREIGN_KEY_CHECKS=1" + + @staticmethod + def _expect_args_list(call_args, expected_query): + assert expected_query == call_args[0][0].text + + @staticmethod + @sqlupdate(disable_foreign_key_checks=True) + def _update_without_foreign_key_checks(): + yield QueryData("INSERT B_RELIES_ON_A") + yield QueryData("INSERT A") + + @staticmethod + @sqlupdate() + def _update_something(values): + return QueryData("INSERT something", query_params=values) + + @staticmethod + @sqlupdate(isolation_level="READ_UNCOMMITTED") + def _update_something_uncommited_isolation(values): + return QueryData(f"INSERT WITH uncommitted {values}") + + @staticmethod + @sqlupdate() + def _update_something_no_params(): + return QueryData("INSERT something") + + @staticmethod + @sqlupdate() + def _update_something_multi_yield(multiple_values): + for values in multiple_values: + yield QueryData("INSERT something", query_params=values) + + @staticmethod + @sqlupdate() + def _update_something_return_list(multiple_values): + return QueryData("INSERT something", query_params=multiple_values) + + @staticmethod + @sqlupdate() + def _update_list_when_multi_false(multiple_values): + return "INSERT something", multiple_values + + @staticmethod + @sqlupdate() + def _update_yield_with_lists(multiple_values, other_values): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + + NOTE: + """ + yield QueryData( + "INSERT some {values__in}", + template_params=_get_template_params("values__in", multiple_values), + ) + yield QueryData( + "INSERT some more {values__other}", + template_params=_get_template_params("values__other", other_values), + ) + + @staticmethod + @sqlupdate() + def _update_yield_with_lists_some_no_params(multiple_values): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + """ + yield QueryData( + "INSERT some {values__in}", + template_params=_get_template_params("values__in", multiple_values), + ) + yield QueryData("UPDATE some more") + yield QueryData("UPDATE some more") + yield QueryData("DELETE some more") + + +def _get_template_params(key, values): + """ + template parameters is handled here as an example of what you might end up + doing. usually data coming in is going to be a list + + :param key: the template key we want to use to build our template with + :param values: the list of objects or mariadbmaps, + :return: a keyed list of tuples or mariadbmaps + """ + if isinstance(values[0], DbMapResult): + return {key: values} + return {key: [(v["id"], v["value"]) for v in values]} diff --git a/dysql/test/test_sql_exists_decorator.py b/dysql/test/test_sql_exists_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..daf56a13c346e1957ab5580acb385035ad3ff102 --- /dev/null +++ b/dysql/test/test_sql_exists_decorator.py @@ -0,0 +1,165 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import Mock + +import pytest + +from dysql import sqlexists, QueryData +from dysql.test import setup_mock_engine + + +TRUE_QUERY = "SELECT 1 from table" +TRUE_QUERY_PARAMS = "SELECT 1 from table where key=:key" +FALSE_QUERY = "SELECT 1 from false_table " +FALSE_QUERY_PARAMS = "SELECT 1 from table where key=:key" +TRUE_PARAMS = {"key": 123} +FALSE_PARAMS = {"key": 456} +SELECT_EXISTS_QUERY = "SELECT 1 WHERE EXISTS ( {} )" +SELECT_EXISTS_NO_WHERE_QUERY = "SELECT EXISTS ( {} )" +EXISTS_QUERIES = { + "true": SELECT_EXISTS_QUERY.format(TRUE_QUERY), + "false": SELECT_EXISTS_QUERY.format(FALSE_QUERY), + "true_params": SELECT_EXISTS_QUERY.format(TRUE_QUERY_PARAMS), + "false_params": SELECT_EXISTS_QUERY.format(FALSE_QUERY_PARAMS), + "true_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(TRUE_QUERY), + "false_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(FALSE_QUERY), +} + + +@pytest.fixture(autouse=True) +def mock_engine_fixture(mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect.return_value.execution_options.return_value.execute.side_effect = _check_query_and_return_result + mock_engine.connect().execution_options().__enter__ = Mock() + mock_engine.connect().execution_options().__exit__ = Mock() + + +def test_exists_true(): + assert _exists_true() + + +def test_exists_false(): + assert not _exists_false() + + +def test_exists_true_params(): + assert _exists_true_params() + + +def test_exists_false_params(): + assert not _exists_false_params() + + +def test_exists_query_contains_with_exists_true(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should match against the same query, should still match + assert _exists_specified("true") + + +def test_exists_query_contains_with_exists_false(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should match against the same query, should still match + assert not _exists_specified("false") + + +def test_exists_without_where_true(): + """ + this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists + query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected + when using `SELECT 1 WHERE EXISTS` + """ + assert _select_exists_no_where_true() + + +def test_exists_witohut_where_false(): + """ + this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists + query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected + when using `SELECT 1 WHERE EXISTS` + """ + assert not _select_exists_no_where_false() + + +def test_exists_query_starts_with_exists_handles_whitespace(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should trim the whitespace and match appropiately + assert _exists_whitespace() + + +@sqlexists() +def _select_exists_no_where_false(): + return QueryData(EXISTS_QUERIES["false_no_where"]) + + +@sqlexists() +def _select_exists_no_where_true(): + return QueryData(EXISTS_QUERIES["true_no_where"]) + + +@sqlexists() +def _exists_specified(key): + return QueryData(EXISTS_QUERIES[key]) + + +@sqlexists() +def _exists_true(): + return QueryData(TRUE_QUERY) + + +@sqlexists() +def _exists_false(): + return QueryData(FALSE_QUERY) + + +@sqlexists() +def _exists_true_params(): + return QueryData(TRUE_QUERY, TRUE_PARAMS) + + +@sqlexists() +def _exists_false_params(): + return QueryData(FALSE_QUERY, FALSE_PARAMS) + + +@sqlexists() +def _exists_whitespace(): + return QueryData( + """ + """ + + TRUE_QUERY + ) + + +def _check_query_and_return_result(query, params): + """ + check that the query matches our expectations + and then set the return value for the scalar call. + scalar() returns either 1 or 0, 1 for true, 0 for false + """ + assert query.text in list(EXISTS_QUERIES.values()) + scalar_mock = Mock() + # default mock responses to true, then we only handle setting false responses + scalar_mock.scalar.return_value = 1 + if query.text == EXISTS_QUERIES["true_params"]: + assert params.get("key") == 123 + if query.text == EXISTS_QUERIES["false_params"]: + assert params.get("key") == 456 + scalar_mock.scalar.return_value = 0 + elif query.text == EXISTS_QUERIES["false"]: + scalar_mock.scalar.return_value = 0 + return scalar_mock diff --git a/dysql/test/test_sql_in_list_templates.py b/dysql/test/test_sql_in_list_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..a12531a4f7638524a120ef1832369d2a92650376 --- /dev/null +++ b/dysql/test/test_sql_in_list_templates.py @@ -0,0 +1,289 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +# pylint: disable=too-many-public-methods +import pytest + +import dysql +from dysql import QueryData, sqlquery +from dysql.test import ( + verify_query, + verify_query_args, + verify_query_params, + setup_mock_engine, +) + + +@pytest.fixture(name="mock_engine", autouse=True) +def mock_engine_fixture(mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect().execution_options().execute.side_effect = lambda x, y: [] + return mock_engine + + +def test_list_in_numbers(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", + template_params={"in__column_a": [1, 2, 3, 4]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ", + { + "in__column_a_0": 1, + "in__column_a_1": 2, + "in__column_a_2": 3, + "in__column_a_3": 4, + }, + ) + + +def test_list_in__strings(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", + template_params={"in__column_a": ["a", "b", "c", "d"]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ", + { + "in__column_a_0": "a", + "in__column_a_1": "b", + "in__column_a_2": "c", + "in__column_a_3": "d", + }, + ) + + +def test_list_not_in_numbers(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": [1, 2, 3, 4]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, " + ":not_in__column_b_2, :not_in__column_b_3 ) ", + { + "not_in__column_b_0": 1, + "not_in__column_b_1": 2, + "not_in__column_b_2": 3, + "not_in__column_b_3": 4, + }, + ) + + +def test_list_not_in_strings(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": ["a", "b", "c", "d"]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, " + ":not_in__column_b_2, :not_in__column_b_3 ) ", + { + "not_in__column_b_0": "a", + "not_in__column_b_1": "b", + "not_in__column_b_2": "c", + "not_in__column_b_3": "d", + }, + ) + + +def test_list_in_handles_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", template_params={"in__column_a": []} + ) + verify_query(mock_engine, "SELECT * FROM table WHERE 1 <> 1 ") + + +def test_list_in_handles_no_param(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a']" + ): + _query("SELECT * FROM table WHERE {in__column_a}") + + +def test_list_in_multiple_lists(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}", + template_params={"in__column_a": ["first", "second"], "in__column_b": [1, 2]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) " + "OR column_b IN ( :in__column_b_0, :in__column_b_1 ) ", + ) + + +def test_list_in_multiple_lists_one_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}", + template_params={"in__column_a": ["first", "second"], "in__column_b": []}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) OR 1 <> 1 ", + ) + + +def test_list_in_multiple_lists_one_missing(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a']" + ): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ", + template_params={"in__column_b": [1, 2]}, + ) + + +def test_list_in_multiple_lists_all_missing(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a','in__column_b']" + ): + _query("SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ") + + +def test_list_not_in_handles_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": []}, + ) + verify_query(mock_engine, "SELECT * FROM table WHERE 1 = 1 ") + + +def test_list_not_in_handles_no_param(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['not_in__column_b']" + ): + _query("SELECT * FROM table WHERE {not_in__column_b} ") + + +def test_list_gives_template_space_before(mock_engine): + _query( + "SELECT * FROM table WHERE{in__space}", template_params={"in__space": [9, 8]} + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) ", + ) + + +def test_list_gives_template_space_after(mock_engine): + _query( + "SELECT * FROM table WHERE {in__space}AND other_condition = 1", + template_params={"in__space": [9, 8]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1", + ) + + +def test_list_gives_template_space_before_and_after(mock_engine): + _query( + "SELECT * FROM table WHERE{in__space}AND other_condition = 1", + template_params={"in__space": [9, 8]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1", + ) + + +def test_in_contains_whitespace(mock_engine): + _query("{in__column_one}", template_params={"in__column_one": [1, 2]}) + verify_query( + mock_engine, " column_one IN ( :in__column_one_0, :in__column_one_1 ) " + ) + + +def test_template_handles_table_qualifier(mock_engine): + """ + when the table is specified with a dot separator, we need to split the table out of the + keyword and the keyword passed in should be passed in without the keyword + + {in__table.column} -> {table}.{in__column} -> table.column IN (:in__column_0, :in__column_1) + :return: + """ + _query( + "SELECT * FROM table WHERE {in__table.column}", + template_params={"in__table.column": [1, 2]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) ", + ) + verify_query_args(mock_engine, {"in__table_column_0": 1, "in__table_column_1": 2}) + + +def test_template_handles_multiple_table_qualifier(mock_engine): + _query( + "SELECT * FROM table WHERE {in__table.column} AND {not_in__other_column}", + template_params={ + "in__table.column": [1, 2], + "not_in__other_column": ["a", "b"], + }, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) " + "AND other_column NOT IN ( :not_in__other_column_0, :not_in__other_column_1 ) ", + ) + verify_query_args( + mock_engine, + { + "in__table_column_0": 1, + "in__table_column_1": 2, + "not_in__other_column_0": "a", + "not_in__other_column_1": "b", + }, + ) + + +def test_empty_in_contains_whitespace(mock_engine): + _query("{in__column_one}", template_params={"in__column_one": []}) + verify_query(mock_engine, " 1 <> 1 ") + + +def test_multiple_templates_same_column_diff_table(mock_engine): + template_params = { + "in__table.status": ["on", "off", "waiting"], + "in__other_table.status": ["success", "partial_success"], + } + expected_params_from_template = { + "in__table_status_0": "on", + "in__table_status_1": "off", + "in__table_status_2": "waiting", + "in__other_table_status_0": "success", + "in__other_table_status_1": "partial_success", + } + + # writing each of these queries out to help see what we expect compared to + # the query we actually sent + _query( + "SELECT * FROM table WHERE {in__table.status} AND {in__other_table.status}", + template_params=template_params, + ) + expected_query = ( + "SELECT * FROM table WHERE table.status IN ( :in__table_status_0, :in__table_status_1, " + ":in__table_status_2 ) AND other_table.status IN ( :in__other_table_status_0, " + ":in__other_table_status_1 ) " + ) + + connection = mock_engine.connect.return_value.execution_options.return_value + execute_call = connection.execute + execute_call.assert_called_once() + assert execute_call.call_args[0][0].text == expected_query + assert execute_call.call_args[0][1] == expected_params_from_template + + +@sqlquery() +def _query(query, query_params=None, template_params=None): + return QueryData(query, query_params=query_params, template_params=template_params) diff --git a/dysql/test/test_sql_insert_templates.py b/dysql/test/test_sql_insert_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..56eb5843657b31b9d8ec3cc684cf33082b448aba --- /dev/null +++ b/dysql/test/test_sql_insert_templates.py @@ -0,0 +1,174 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +import dysql +from dysql import QueryData, sqlupdate, QueryDataError +from dysql.test import ( + verify_query, + verify_query_args, + setup_mock_engine, +) + + +@pytest.fixture(name="mock_engine", autouse=True) +def mock_engine_fixture(mock_create_engine): + initial_id = 0 + + def handle_execute(query=None, args=None): + nonlocal initial_id + if "INSERT INTO get_last(name)" in query.text: + initial_id += 1 + if "SELECT LAST_INSERT_ID()" == query.text: + return type("Result", (), {"scalar": lambda: initial_id}) + return [] + + mock_engine = setup_mock_engine(mock_create_engine) + execute_mock = mock_engine.connect().execution_options().execute + execute_mock.side_effect = handle_execute + return mock_engine + + +def test_insert_non_query_data_fails(): + @sqlupdate() + def select_with_string(): + return "INSERT" + + with pytest.raises(QueryDataError): + select_with_string() + + +def test_insert_single_column(mock_engine): + insert_into_single_value(["Tom", "Jerry"]) + verify_query( + mock_engine, + "INSERT INTO table(name) VALUES ( :values__name_col_0 ), ( :values__name_col_1 ) ", + ) + + +def test_insert_single_column_single_value(mock_engine): + insert_into_single_value("Tom") + verify_query(mock_engine, "INSERT INTO table(name) VALUES ( :values__name_col_0 ) ") + + +def test_insert_single_value_empty(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['values_name_col']" + ): + insert_into_single_value([]) + + +def test_insert_single_value_no_key(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['values_name_col']" + ): + insert_into_single_value(None) + + +def test_insert_multiple_values(mock_engine): + insert_into_multiple_values( + [ + {"name": "Tom", "email": "tom@adobe.com"}, + {"name": "Jerry", "email": "jerry@adobe.com"}, + ] + ) + verify_query( + mock_engine, + "INSERT INTO table(name, email) VALUES ( :values__users_0_0, :values__users_0_1 ), " + "( :values__users_1_0, :values__users_1_1 ) ", + ) + verify_query_args( + mock_engine, + { + "values__users_0_0": "Tom", + "values__users_0_1": "tom@adobe.com", + "values__users_1_0": "Jerry", + "values__users_1_1": "jerry@adobe.com", + }, + ) + + +@pytest.mark.parametrize( + "args", + [ + ([("bob", "bob@email.com")]), + ([("bob", "bob@email.com"), ("tom", "tom@email.com")]), + None, + (), + ], +) +def test_insert_with_callback(args): + def callback(items): + assert items == args + + @sqlupdate(on_success=callback) + def insert(items): + yield QueryData(f"INSERT INTO table(name, email) {items}") + + insert(args) + + +def test_insert_with_callack_not_called(mock_engine): + def callback(): + assert False + + @sqlupdate(on_success=callback) + def insert(): + yield QueryData("INSERT INTO table(name, email)") + + mock_engine.connect().execution_options.return_value.execute.side_effect = ( + Exception() + ) + with pytest.raises(Exception): + insert() + + +@sqlupdate() +def insert_into_multiple_values(users): + yield QueryData( + "INSERT INTO table(name, email) {values__users}", + template_params={"values__users": [(d["name"], d["email"]) for d in users]}, + ) + + +@sqlupdate() +def insert_into_single_value(names): + template_params = {} + if names is not None: + template_params = {"values__name_col": names} + + return QueryData( + "INSERT INTO table(name) {values__name_col}", template_params=template_params + ) + + +def test_last_insert_id(): + @sqlupdate() + def insert(get_last_insert_id=None): + yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')") + assert get_last_insert_id + assert get_last_insert_id() == 1 + yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')") + assert get_last_insert_id() == 2 + + insert() + + +def test_last_insert_id_removed_before_callback(): + def callback(**kwargs): + assert "get_last_insert_id" not in kwargs + + @sqlupdate() + def insert(get_last_insert_id=None): + assert get_last_insert_id + yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')") + yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')") + assert get_last_insert_id() == 2 + + insert() diff --git a/dysql/test/test_template_generators.py b/dysql/test/test_template_generators.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc797f6febfff7b060d9eb05ff5376a822e5098 --- /dev/null +++ b/dysql/test/test_template_generators.py @@ -0,0 +1,222 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql.query_utils import TemplateGenerators, ListTemplateException + + +class TestTemplatesGenerators: + """ + Test we get templates back from Templates + """ + + number_values = [1, 2, 3, 4] + string_values = ["1", "2", "3", "4"] + set_values = {1, 2, 3, 4} + insert_values = [("ironman", 1), ("batman", 2)] + tuple_values = [(1, 2), (3, 4)] + query = "column_a IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )" + + query_with_list_of_tuples = ( + "(column_a, column_b) IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), " + "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))" + ) + not_query_with_list_of_tuples = ( + "(column_a, column_b) NOT IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), " + "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))" + ) + query_with_table = "table.column_a IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )" + not_query = "column_a NOT IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )" + not_query_with_table = "table.column_a NOT IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )" + + test_query_data = ( + "template_function, column_name,column_values,expected_query", + [ + (TemplateGenerators.in_column, "column_a", number_values, query), + ( + TemplateGenerators.in_column, + "table.column_a", + number_values, + query_with_table, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + set_values, + query_with_table, + ), + (TemplateGenerators.in_column, "column_a", string_values, query), + ( + TemplateGenerators.in_column, + "table.column_a", + string_values, + query_with_table, + ), + (TemplateGenerators.in_column, "column_a", [], "1 <> 1"), + ( + TemplateGenerators.in_multi_column, + "(column_a, column_b)", + tuple_values, + query_with_list_of_tuples, + ), + ( + TemplateGenerators.not_in_multi_column, + "(column_a, column_b)", + tuple_values, + not_query_with_list_of_tuples, + ), + (TemplateGenerators.not_in_column, "column_a", number_values, not_query), + ( + TemplateGenerators.not_in_column, + "table.column_a", + number_values, + not_query_with_table, + ), + (TemplateGenerators.not_in_column, "column_a", string_values, not_query), + ( + TemplateGenerators.not_in_column, + "table.column_a", + string_values, + not_query_with_table, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + set_values, + not_query_with_table, + ), + (TemplateGenerators.not_in_column, "column_a", [], "1 = 1"), + ( + TemplateGenerators.values, + "someid", + insert_values, + "VALUES ( :someid_0_0, :someid_0_1 ), ( :someid_1_0, :someid_1_1 )", + ), + ], + ) + + parameter_numbers = { + "column_a_0": number_values[0], + "column_a_1": number_values[1], + "column_a_2": number_values[2], + "column_a_3": number_values[3], + } + with_table_parameter_numbers = { + "table_column_a_0": number_values[0], + "table_column_a_1": number_values[1], + "table_column_a_2": number_values[2], + "table_column_a_3": number_values[3], + } + parameter_strings = { + "column_a_0": string_values[0], + "column_a_1": string_values[1], + "column_a_2": string_values[2], + "column_a_3": string_values[3], + } + with_table_parameter_strings = { + "table_column_a_0": string_values[0], + "table_column_a_1": string_values[1], + "table_column_a_2": string_values[2], + "table_column_a_3": string_values[3], + } + test_params_data = ( + "template_function, column_name,column_values,expected_params", + [ + ( + TemplateGenerators.in_column, + "column_a", + number_values, + parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "column_a", + set_values, + parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + number_values, + with_table_parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "column_a", + string_values, + parameter_strings, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + string_values, + with_table_parameter_strings, + ), + (TemplateGenerators.in_column, "column_a", [], None), + ( + TemplateGenerators.not_in_column, + "column_a", + number_values, + parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + number_values, + with_table_parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "column_a", + string_values, + parameter_strings, + ), + ( + TemplateGenerators.not_in_column, + "column_a", + set_values, + parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + string_values, + with_table_parameter_strings, + ), + (TemplateGenerators.not_in_column, "column_a", [], None), + ( + TemplateGenerators.values, + "someid", + insert_values, + { + "someid_0_0": insert_values[0][0], + "someid_0_1": insert_values[0][1], + "someid_1_0": insert_values[1][0], + "someid_1_1": insert_values[1][1], + }, + ), + ], + ) + + @staticmethod + @pytest.mark.parametrize(*test_query_data) + def test_query(template_function, column_name, column_values, expected_query): + query, _ = template_function(column_name, column_values) + assert query == expected_query + + @staticmethod + @pytest.mark.parametrize(*test_params_data) + def test_params(template_function, column_name, column_values, expected_params): + _, params = template_function(column_name, column_values) + assert params == expected_params + + @staticmethod + def test_insert_none(): + with pytest.raises(ListTemplateException): + TemplateGenerators.values("someid", None) diff --git a/dysql/test/test_test_managers.py b/dysql/test/test_test_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..f52fdd9f4f0dc931377a1c486cda840e4e98c26c --- /dev/null +++ b/dysql/test/test_test_managers.py @@ -0,0 +1,76 @@ +""" +Copyright 2026 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest +from unittest.mock import patch + +from dysql.test_managers import MariaDbTestManager + + +class TestMariaDbTestManager: + """ + Tests for MariaDbTestManager + """ + + @patch.object(MariaDbTestManager, "_run") + def test_create_test_db_without_schema(self, mock_run): + """Test that _create_test_db works without a schema_db_name""" + manager = MariaDbTestManager(db_name="test_db") + manager._create_test_db() + + # Should have called _run twice (DROP and CREATE) + assert mock_run.call_count == 2 + + # Verify DROP command + drop_call = mock_run.call_args_list[0] + assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0] + + # Verify CREATE command + create_call = mock_run.call_args_list[1] + assert "CREATE DATABASE IF NOT EXISTS test_db" in create_call[0][0] + + @patch.object(MariaDbTestManager, "_run") + @pytest.mark.parametrize("command", ["--no-data", "--routines", "source_db"]) + def test_create_test_includes_commands(self, mock_run, command): + """Test that _create_test_db includes --routines flag when copying schema""" + manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db") + manager._create_test_db() + + # Should have called _run three times (DROP, CREATE, and mysqldump) + assert mock_run.call_count == 3 + + # Verify mysqldump command includes command + mysqldump_call = mock_run.call_args_list[2] + mysqldump_command = mysqldump_call[0][0] + + assert "mariadb-dump" in mysqldump_command + assert command in mysqldump_command + + @patch.object(MariaDbTestManager, "_run") + def test_create_test_db_mysqldump_command_format(self, mock_run): + """Test the exact format of the mysqldump command""" + manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db") + manager._create_test_db() + + mysqldump_call = mock_run.call_args_list[2] + mysqldump_command = mysqldump_call[0][0] + + # Verify the command has the correct structure + # mysqldump --no-data --routines -p{password} {schema_db_name} -h{host} | mariadb ... + assert "| mariadb" in mysqldump_command + assert "test_db" in mysqldump_command + + @patch.object(MariaDbTestManager, "_run") + def test_tear_down_test_db(self, mock_run): + """Test that _tear_down_test_db drops the database""" + manager = MariaDbTestManager(db_name="test_db") + manager._tear_down_test_db() + + assert mock_run.call_count == 1 + drop_call = mock_run.call_args_list[0] + assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0] diff --git a/dysql/test_managers.py b/dysql/test_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..21d8d998ed59adab403c0f0f44454f5c7d90d4ad --- /dev/null +++ b/dysql/test_managers.py @@ -0,0 +1,236 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import abc +import logging +import os +import subprocess +from time import sleep +from typing import Optional + +from .connections import sqlquery +from .databases import ( + is_set_current_database_supported, + set_current_database, + set_default_connection_parameters, +) +from .mappers import CountMapper +from .query_utils import QueryData + +LOGGER = logging.getLogger(__name__) + + +class DbTestManagerBase(abc.ABC): + """ + Base class for all test managers. See individual implementations for usage details. + """ + + # pylint: disable=too-many-instance-attributes + + def __init__( + self, + host: str, + username: str, + password: str, + db_name: str, + schema_db_name: Optional[str], + docker_container: Optional[str] = None, + keep_db: bool = False, + **connection_defaults, + ): # pylint: disable=too-many-arguments + """ + Constructor, any unknown kwargs are passed directly to set_default_connection_parameters. + + :param host: the host to access the test database + :param username: the username to access the test database + :param password: the password to access the test database + :param db_name: the name of the test database + :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump) + :param docker_container: the name of the docker container where the database is running (if in docker) + :param keep_db: This prevents teardown from removing the created database after running tests + which can be helpful in debugging + """ + self.host = host + self.username = username + self.password = password + self.db_name = db_name + self.schema_db_name = schema_db_name + self.docker_container = docker_container + self.keep_db = keep_db + self.connection_defaults = connection_defaults + self.in_docker = self._is_running_in_docker() + + @staticmethod + def _is_running_in_docker(): + if os.path.exists("/.dockerenv"): + return True + + if os.path.exists("/proc/1/cgroup"): + with open("/proc/1/cgroup", "rt", encoding="utf8") as fobj: + contents = fobj.read() + for marker in ("docker", "kubepod", "lxc"): + if marker in contents: + return True + return False + + def __enter__(self): + LOGGER.debug(f"Setting up database : {self.db_name}") + # Set the host based on whether we are in buildrunner or not (to test locally) + + self._create_test_db() + set_default_connection_parameters( + self.host, + self.username, + self.password, + self.db_name, + **self.connection_defaults, + ) + + # Set the database if supported by the python runtime + if is_set_current_database_supported(): + set_current_database(self.db_name) + + if self.schema_db_name: + self._wait_for_tables_exist() + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.keep_db: + LOGGER.debug(f"Tearing down database : {self.db_name}") + self._tear_down_test_db() + + @abc.abstractmethod + def _create_test_db(self) -> None: + """ + Must be overridden in implementing classes. Creates the test database from the self.schema_db_name + database (if present) or an empty database desired. + """ + + @abc.abstractmethod + def _get_tables_count(self, db_name: str) -> int: + """ + Must be overridden in implementing classes. Retrieves the current table count for the database. + :param db_name: the database to retrieve the count for + :return: the number of tables present in the database + """ + + @abc.abstractmethod + def _tear_down_test_db(self) -> None: + """ + Must be overridden in implementing classes. Tears down the test database. + """ + + def _wait_for_tables_exist(self) -> None: + """ + Waits for the tables to exist in the new test database. + """ + tables_exist = False + expected_count = self._get_tables_count(self.schema_db_name) + while not tables_exist: + sleep(0.25) + LOGGER.debug("Tables are still not ready") + actual_count = self._get_tables_count(self.db_name) + tables_exist = expected_count == actual_count + + def _run(self, command: str) -> subprocess.CompletedProcess: + """ + Runs a command, wrapping the command in docker commands if necessary. + :param command: the command to run + :return: the completed process information + """ + if not self.in_docker: + command = f"docker exec {self.docker_container} bash -c '{command}'" + + try: + LOGGER.debug(f"Executing : '{command}'") + completed_process = subprocess.run( + command, shell=True, timeout=30, check=True, capture_output=True + ) + LOGGER.debug(f"Executed : {completed_process.stdout}") + + return completed_process + except subprocess.CalledProcessError: + LOGGER.exception(f"Error handling command : {command}") + raise + + +class MariaDbTestManager(DbTestManagerBase): + """ + May be used in testing to copy and create a database and schema. This class works specifically with + Maria/MySQL databases. + + Example: + + @pytest.fixture(scope='module', autouse=True) + def setup_db(self): + # Pass in the database name and any optional params + with MariaDbTestManager(f'testdb_{self.__class__.__name__.lower()}'): + yield + """ + + # pylint: disable=too-few-public-methods + + def __init__( + self, + db_name: str, + schema_db_name: Optional[str] = None, + echo_queries: bool = False, + keep_db: bool = False, + pool_size=3, + charset="utf8", + ): # pylint: disable=too-many-arguments + """ + :param db_name: the name you want for your test database + :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump) + :param echo_queries: True if you want to see queries + :param keep_db: This prevents teardown from removing the created DB after running tests + which can be helpful in debugging + :param charset: This allows you to override the default charset if you need something besides utf8 + """ + super().__init__( + os.getenv("MARIA_HOST", "localhost"), + os.getenv("MARIA_USERNAME", "root"), + os.getenv("MARIA_PASSWORD", "password"), + db_name, + schema_db_name, + port=3306, + echo_queries=echo_queries, + pool_size=pool_size, + docker_container=os.getenv("MARIA_CONTAINER_NAME", "mariadb"), + keep_db=keep_db, + charset=charset, + ) + + def _create_test_db(self) -> None: + self._run( + f'mariadb -p{self.password} -h{self.host} -N -e "DROP DATABASE IF EXISTS {self.db_name}"' + ) + self._run( + f'mariadb -p{self.password} -h{self.host} -s -N -e "CREATE DATABASE IF NOT EXISTS {self.db_name}"' + ) + if self.schema_db_name: + self._run( + f"mariadb-dump --no-data --routines -p{self.password} {self.schema_db_name} -h{self.host} " + f"| mariadb -p{self.password} {self.db_name} -h{self.host}" + ) + + def _tear_down_test_db(self) -> None: + self._run( + f'echo "DROP DATABASE IF EXISTS {self.db_name} " | mariadb -p{self.password} -h{self.host}' + ) + + @sqlquery(mapper=CountMapper()) + def _get_tables_count(self, db_name: str) -> int: + # pylint: disable=unused-argument + return QueryData( + """ + SELECT count(1) + FROM information_schema.TABLES + WHERE TABLE_SCHEMA=:db_name + """, + query_params={"db_name": db_name}, + )
diff --git a/dysql/__init__.py b/dysql/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..492ed753f2bef5ed18777a39eab6632440176c6c
--- /dev/null
+++ b/dysql/__init__.py
@@ -0,0 +1,60 @@
+"""
+Copyright 2021 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+# Public imports
+from .mappers import (
+ BaseMapper,
+ DbMapResult,
+ RecordCombiningMapper,
+ SingleRowMapper,
+ SingleColumnMapper,
+ SingleRowAndColumnMapper,
+ CountMapper,
+ KeyValueMapper,
+)
+from .query_utils import QueryData, QueryDataError, TemplateGenerators
+from .connections import (
+ sqlexists,
+ sqlquery,
+ sqlupdate,
+)
+from .databases import (
+ is_set_current_database_supported,
+ reset_current_database,
+ set_current_database,
+ set_database_init_hook,
+ set_default_connection_parameters,
+)
+from .multitenancy import use_database_tenant, tenant_database_manager
+from .exceptions import DBNotPreparedError
+
+
+__all__ = [
+ "BaseMapper",
+ "DbMapResult",
+ "RecordCombiningMapper",
+ "SingleRowMapper",
+ "SingleColumnMapper",
+ "SingleRowAndColumnMapper",
+ "CountMapper",
+ "KeyValueMapper",
+ "QueryData",
+ "QueryDataError",
+ "TemplateGenerators",
+ "sqlexists",
+ "sqlquery",
+ "sqlupdate",
+ "is_set_current_database_supported",
+ "reset_current_database",
+ "set_current_database",
+ "set_database_init_hook",
+ "set_default_connection_parameters",
+ "use_database_tenant",
+ "tenant_database_manager",
+ "DBNotPreparedError",
+]
diff --git a/dysql/annotations.py b/dysql/annotations.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a12d05f604c53466a5e3941a9141c873a2c9a21
--- /dev/null
+++ b/dysql/annotations.py
@@ -0,0 +1,31 @@
+"""
+Copyright 2023 Adobe
+All Rights Reserved.
+
+NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
+with the terms of the Adobe license agreement accompanying it.
+"""
+
+from typing import TypeVar, Annotated
+
+from pydantic import BeforeValidator
+
+# pylint: disable=invalid-name
+T = TypeVar("T")
+
+
+def _transform_csv(value: str) -> T:
+ if not value:
+ return None
+
+ if isinstance(value, str):
+ return list(map(str.strip, value.split(",")))
+
+ if isinstance(value, list):
+ return value
+ # if we don't have a string or type T we aren't going to be able to transform it
+ return [value]
+