Skip to content

Commit

Permalink
QueryBuilder: Deprecate debug argument and use logger
Browse files Browse the repository at this point in the history
The `QueryBuilder` defined the `debug` flag, which when set to `True`
would cause certain methods to print additional debug information. This
should go through the logging functionality, however, so the print
statements are replaced by a `logger.debug` call.

Since the debug messages can now be activated by configuring the logger
log level, the `debug` argument is no longer needed and is deprecated.
  • Loading branch information
sphuber committed Jun 11, 2023
1 parent add474c commit 8d58bc2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 15 deletions.
2 changes: 0 additions & 2 deletions aiida/orm/implementation/querybuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@

__all__ = ('BackendQueryBuilder',)

QUERYBUILD_LOGGER = AIIDA_LOGGER.getChild('orm.querybuilder')

EntityRelationships: Dict[str, Set[str]] = {
EntityTypes.AUTHINFO.value: {'with_computer', 'with_user'},
EntityTypes.COMMENT.value: {'with_node', 'with_user'},
Expand Down
32 changes: 23 additions & 9 deletions aiida/orm/querybuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
)
import warnings

from aiida.common.log import AIIDA_LOGGER
from aiida.common.warnings import warn_deprecation
from aiida.manage import get_manager
from aiida.orm.entities import EntityTypes
from aiida.orm.implementation.querybuilder import (
Expand All @@ -67,6 +69,8 @@
FilterType = Dict[str, Any] # pylint: disable=invalid-name
OrderByType = Union[dict, List[dict], Tuple[dict, ...]]

LOGGER = AIIDA_LOGGER.getChild('querybuilder')


class Classifier(NamedTuple):
"""A classifier for an entity."""
Expand Down Expand Up @@ -100,7 +104,7 @@ def __init__(
self,
backend: Optional['StorageBackend'] = None,
*,
debug: bool = False,
debug: bool | None = None,
path: Optional[Sequence[Union[str, Dict[str, Any], EntityClsType]]] = (),
filters: Optional[Dict[str, FilterType]] = None,
project: Optional[Dict[str, ProjectType]] = None,
Expand Down Expand Up @@ -160,6 +164,12 @@ def __init__(
self._tags = _QueryTagMap()

# Set the debug level
if debug is not None:
warn_deprecation(
'The `debug` argument is deprecated. Configure the log level of the AiiDA logger instead.', version=3
)
else:
debug = False
self.set_debug(debug)

# Validate & add the query path
Expand Down Expand Up @@ -406,7 +416,7 @@ def append(
try:
self._tags.add(tag, ormclass, cls)
except Exception as exception:
self.debug('Exception caught in append, cleaning up: %s', exception)
LOGGER.debug('Exception caught in append, cleaning up: %s', exception)
self._tags.remove(tag)
raise

Expand All @@ -429,7 +439,7 @@ def append(
if filters is not None:
self.add_filter(tag, filters)
except Exception as exception:
self.debug('Exception caught in append, cleaning up: %s', exception)
LOGGER.debug('Exception caught in append, cleaning up: %s', exception)
self._tags.remove(tag)
self._filters.pop(tag)
raise
Expand All @@ -440,7 +450,7 @@ def append(
if project is not None:
self.add_projection(tag, project)
except Exception as exception:
self.debug('Exception caught in append, cleaning up: %s', exception)
LOGGER.debug('Exception caught in append, cleaning up: %s', exception)
self._tags.remove(tag)
self._filters.pop(tag)
self._projections.pop(tag)
Expand Down Expand Up @@ -495,7 +505,7 @@ def append(
joining_value = self._path[-1]['tag']

except Exception as exception:
self.debug('Exception caught in append (part filters), cleaning up: %s', exception)
LOGGER.debug('Exception caught in append (part filters), cleaning up: %s', exception)
self._tags.remove(tag)
self._filters.pop(tag)
self._projections.pop(tag)
Expand All @@ -512,7 +522,7 @@ def append(
else:
if edge_tag in self._tags:
raise ValueError(f'The tag {edge_tag} is already in use')
self.debug('edge_tag chosen: %s', edge_tag)
LOGGER.debug('edge_tag chosen: %s', edge_tag)

# edge tags do not have an ormclass
self._tags.add(edge_tag)
Expand All @@ -529,7 +539,7 @@ def append(
if edge_project is not None:
self.add_projection(edge_tag, edge_project)
except Exception as exception:
self.debug('Exception caught in append (part joining), cleaning up %s', exception)
LOGGER.debug('Exception caught in append (part joining), cleaning up %s', exception)
self._tags.remove(tag)
self._filters.pop(tag)
self._projections.pop(tag)
Expand Down Expand Up @@ -816,7 +826,7 @@ def add_projection(self, tag_spec: Union[str, EntityClsType], projection_spec: P
"""
tag = self._tags.get(tag_spec)
_projections = []
self.debug('Adding projection of %s: %s', tag_spec, projection_spec)
LOGGER.debug('Adding projection of %s: %s', tag_spec, projection_spec)
if not isinstance(projection_spec, (list, tuple)):
projection_spec = [projection_spec] # type: ignore
for projection in projection_spec:
Expand All @@ -838,7 +848,7 @@ def add_projection(self, tag_spec: Union[str, EntityClsType], projection_spec: P
if not isinstance(val, str):
raise TypeError(f'{val} has to be a string')
_projections.append(_thisprojection)
self.debug('projections have become: %s', _projections)
LOGGER.debug('projections have become: %s', _projections)
self._projections[tag] = _projections

def set_debug(self, debug: bool) -> 'QueryBuilder':
Expand All @@ -848,6 +858,9 @@ def set_debug(self, debug: bool) -> 'QueryBuilder':
:param debug: Turn debug on or off
"""
warn_deprecation(
'`QueryBuilder.set_debug` is deprecated. Configure the log level of the AiiDA logger instead.', version=3
)
if not isinstance(debug, bool):
return TypeError('I expect a boolean')
self._debug = debug
Expand All @@ -859,6 +872,7 @@ def debug(self, msg: str, *objects: Any) -> None:
objects will passed to the format string, e.g. ``msg % objects``
"""
warn_deprecation('`QueryBuilder.debug` is deprecated.', version=3)
if self._debug:
print(f'DEBUG: {msg}' % objects)

Expand Down
8 changes: 4 additions & 4 deletions aiida/storage/psql_dos/orm/querybuilder/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from aiida.common.exceptions import NotExistent
from aiida.orm.entities import EntityTypes
from aiida.orm.implementation.querybuilder import QUERYBUILD_LOGGER, BackendQueryBuilder, QueryDictType
from aiida.orm.implementation.querybuilder import LOGGER, BackendQueryBuilder, QueryDictType

from .joiner import JoinReturn, SqlaJoiner

Expand Down Expand Up @@ -959,7 +959,7 @@ def generate_projections(
tag_to_projected_fields: Dict[str, Dict[str, int]] = {}
projections: List[Tuple[Union[AliasedClass, ColumnElement], bool]] = []

QUERYBUILD_LOGGER.debug('projections data: %s', data['project'])
LOGGER.debug('projections data: %s', data['project'])

if not any(data['project'].values()):
# If user has not set projection,
Expand All @@ -981,7 +981,7 @@ def generate_projections(
for vertex in data['path'][1:]:
edge_tag = vertex.get('edge_tag', None)

QUERYBUILD_LOGGER.debug(
LOGGER.debug(
'Checking projections for edges: This is edge %s from %s, %s of %s',
edge_tag,
vertex.get('tag'),
Expand Down Expand Up @@ -1025,7 +1025,7 @@ def _create_projections(
"""
# Return here if there is nothing to project, reduces number of key in return dictionary
QUERYBUILD_LOGGER.debug('projection for %s: %s', tag, project_dict)
LOGGER.debug('projection for %s: %s', tag, project_dict)
if not project_dict:
return []

Expand Down

0 comments on commit 8d58bc2

Please sign in to comment.