aiida.storage.psql_dos.orm.querybuilder package#

Implementation of QueryBuilder backend.

Submodules#

A module containing the logic for creating joined queries.

class aiida.storage.psql_dos.orm.querybuilder.joiner.JoinReturn(join: Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query], aliased_edge: sqlalchemy.orm.util.AliasedClass | None = None, edge_tag: str = '')[source]#

Bases: object

__annotations__ = {'aliased_edge': typing.Optional[sqlalchemy.orm.util.AliasedClass], 'edge_tag': <class 'str'>, 'join': typing.Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query]}#
__dataclass_fields__ = {'aliased_edge': Field(name='aliased_edge',type=typing.Optional[sqlalchemy.orm.util.AliasedClass],default=None,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'edge_tag': Field(name='edge_tag',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'join': Field(name='join',type=typing.Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}#
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)#
__dict__ = mappingproxy({'__module__': 'aiida.storage.psql_dos.orm.querybuilder.joiner', '__annotations__': {'join': typing.Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query], 'aliased_edge': typing.Optional[sqlalchemy.orm.util.AliasedClass], 'edge_tag': <class 'str'>}, 'aliased_edge': None, 'edge_tag': '', '__dict__': <attribute '__dict__' of 'JoinReturn' objects>, '__weakref__': <attribute '__weakref__' of 'JoinReturn' objects>, '__doc__': "JoinReturn(join: Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query], aliased_edge: Optional[sqlalchemy.orm.util.AliasedClass] = None, edge_tag: str = '')", '__dataclass_params__': _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False), '__dataclass_fields__': {'join': Field(name='join',type=typing.Callable[[sqlalchemy.orm.query.Query], sqlalchemy.orm.query.Query],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'aliased_edge': Field(name='aliased_edge',type=typing.Optional[sqlalchemy.orm.util.AliasedClass],default=None,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'edge_tag': Field(name='edge_tag',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}, '__init__': <function JoinReturn.__init__>, '__repr__': <function JoinReturn.__repr__>, '__eq__': <function JoinReturn.__eq__>, '__hash__': None, '__match_args__': ('join', 'aliased_edge', 'edge_tag')})#
__eq__(other)#

Return self==value.

__hash__ = None#
__init__(join: Callable[[Query], Query], aliased_edge: AliasedClass | None = None, edge_tag: str = '') None#
__match_args__ = ('join', 'aliased_edge', 'edge_tag')#
__module__ = 'aiida.storage.psql_dos.orm.querybuilder.joiner'#
__repr__()#

Return repr(self).

__weakref__#

list of weak references to the object (if defined)

aliased_edge: AliasedClass | None = None#
edge_tag: str = ''#
join: Callable[[Query], Query]#
class aiida.storage.psql_dos.orm.querybuilder.joiner.SqlaJoiner(entity_mapper: _EntityMapper, filter_builder: Callable[[AliasedClass, Dict[str, Any]], BooleanClauseList | None])[source]#

Bases: object

A class containing the logic for SQLAlchemy entities joining entities.

__dict__ = mappingproxy({'__module__': 'aiida.storage.psql_dos.orm.querybuilder.joiner', '__doc__': 'A class containing the logic for SQLAlchemy entities joining entities.', '__init__': <function SqlaJoiner.__init__>, 'get_join_func': <function SqlaJoiner.get_join_func>, '_entity_join_map': <function SqlaJoiner._entity_join_map>, '_join_computer_authinfo': <function SqlaJoiner._join_computer_authinfo>, '_join_user_authinfo': <function SqlaJoiner._join_user_authinfo>, '_join_group_node': <function SqlaJoiner._join_group_node>, '_join_node_group': <function SqlaJoiner._join_node_group>, '_join_node_user': <function SqlaJoiner._join_node_user>, '_join_user_node': <function SqlaJoiner._join_user_node>, '_join_computer_node': <function SqlaJoiner._join_computer_node>, '_join_node_computer': <function SqlaJoiner._join_node_computer>, '_join_group_user': <function SqlaJoiner._join_group_user>, '_join_user_group': <function SqlaJoiner._join_user_group>, '_join_node_comment': <function SqlaJoiner._join_node_comment>, '_join_comment_node': <function SqlaJoiner._join_comment_node>, '_join_node_log': <function SqlaJoiner._join_node_log>, '_join_log_node': <function SqlaJoiner._join_log_node>, '_join_user_comment': <function SqlaJoiner._join_user_comment>, '_join_authinfo_user': <function SqlaJoiner._join_authinfo_user>, '_join_comment_user': <function SqlaJoiner._join_comment_user>, '_join_node_outputs': <function SqlaJoiner._join_node_outputs>, '_join_node_inputs': <function SqlaJoiner._join_node_inputs>, '_join_node_descendants_recursive': <function SqlaJoiner._join_node_descendants_recursive>, '_join_node_ancestors_recursive': <function SqlaJoiner._join_node_ancestors_recursive>, '__dict__': <attribute '__dict__' of 'SqlaJoiner' objects>, '__weakref__': <attribute '__weakref__' of 'SqlaJoiner' objects>, '__annotations__': {}})#
__init__(entity_mapper: _EntityMapper, filter_builder: Callable[[AliasedClass, Dict[str, Any]], BooleanClauseList | None])[source]#

Initialise the class

__module__ = 'aiida.storage.psql_dos.orm.querybuilder.joiner'#
__weakref__#

list of weak references to the object (if defined)

_entity_join_map() Dict[str, Dict[str, Callable[[Any, Any, bool, Dict[str, Any], bool], JoinReturn]]][source]#

Map relationship type keywords to functions The first level defines the entity which has been passed to the qb.append function, and the second defines the relationship with respect to a given tag.

_join_authinfo_user(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased comment

  • entity_to_join – aliased user

_join_comment_node(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased comment

  • entity_to_join – aliased node

_join_comment_user(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased comment

  • entity_to_join – aliased user

_join_computer_authinfo(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – the aliased user you want to join to

  • entity_to_join – the (aliased) node or group in the DB to join with

_join_computer_node(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – the (aliased) computer entity

  • entity_to_join – the (aliased) node entity

_join_group_node(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – The (aliased) ORMclass that is a group in the database

  • entity_to_join – The (aliased) ORMClass that is a node and member of the group

joined_entity and entity_to_join are joined via the table_groups_nodes table. from joined_entity as group to enitity_to_join as node. (enitity_to_join is with_group joined_entity)

_join_group_user(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased dbgroup

  • entity_to_join – aliased dbuser

_join_log_node(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased log

  • entity_to_join – aliased node

_join_node_ancestors_recursive(joined_entity, entity_to_join, isouterjoin: bool, filter_dict: Dict[str, Any], expand_path=False)[source]#

Joining ancestors using the recursive functionality :TODO: Move the filters to be done inside the recursive query (for example on depth) :TODO: Pass an option to also show the path, if this is wanted.

_join_node_comment(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased node

  • entity_to_join – aliased comment

_join_node_computer(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An entity that can use a computer (eg a node)

  • entity_to_join – aliased dbcomputer entity

_join_node_descendants_recursive(joined_entity, entity_to_join, isouterjoin: bool, filter_dict: Dict[str, Any], expand_path=False)[source]#

Joining descendants using the recursive functionality :TODO: Move the filters to be done inside the recursive query (for example on depth) :TODO: Pass an option to also show the path, if this is wanted.

_join_node_group(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – The (aliased) node in the database

  • entity_to_join – The (aliased) Group

joined_entity and entity_to_join are joined via the table_groups_nodes table. from joined_entity as node to enitity_to_join as group. (enitity_to_join is a group with_node joined_entity)

_join_node_inputs(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – The (aliased) ORMclass that is an output

  • entity_to_join – The (aliased) ORMClass that is an input.

joined_entity and entity_to_join are joined with a link from joined_entity as output to enitity_to_join as input (enitity_to_join is with_outgoing joined_entity)

_join_node_log(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased node

  • entity_to_join – aliased log

_join_node_outputs(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – The (aliased) ORMclass that is an input

  • entity_to_join – The (aliased) ORMClass that is an output.

joined_entity and entity_to_join are joined with a link from joined_entity as input to enitity_to_join as output (enitity_to_join is with_incoming joined_entity)

_join_node_user(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – the aliased node

  • entity_to_join – the aliased user to join to that node

_join_user_authinfo(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – the aliased user you want to join to

  • entity_to_join – the (aliased) node or group in the DB to join with

_join_user_comment(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased user

  • entity_to_join – aliased comment

_join_user_group(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – An aliased user

  • entity_to_join – aliased group

_join_user_node(joined_entity, entity_to_join, isouterjoin: bool, **_kw)[source]#
Parameters:
  • joined_entity – the aliased user you want to join to

  • entity_to_join – the (aliased) node or group in the DB to join with

get_join_func(entity_key: str, relationship: str) Callable[[Any, Any, bool, Dict[str, Any], bool], JoinReturn][source]#

Return the function to join two entities

class aiida.storage.psql_dos.orm.querybuilder.joiner._EntityMapper(*args, **kwargs)[source]#

Bases: Protocol

Mapping of implemented entity types.

property AuthInfo: Type[Model]#
property Comment: Type[Model]#
property Computer: Type[Model]#
property Group: Type[Model]#
property Log: Type[Model]#
property Node: Type[Model]#
property User: Type[Model]#
__abstractmethods__ = frozenset({})#
__dict__ = mappingproxy({'__module__': 'aiida.storage.psql_dos.orm.querybuilder.joiner', '__doc__': 'Mapping of implemented entity types.', 'AuthInfo': <property object>, 'Node': <property object>, 'Group': <property object>, 'Link': <property object>, 'User': <property object>, 'Computer': <property object>, 'Comment': <property object>, 'Log': <property object>, 'table_groups_nodes': <property object>, '__dict__': <attribute '__dict__' of '_EntityMapper' objects>, '__weakref__': <attribute '__weakref__' of '_EntityMapper' objects>, '__parameters__': (), '_is_protocol': True, '__subclasshook__': <function Protocol.__init_subclass__.<locals>._proto_hook>, '__init__': <function _no_init_or_replace_init>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})#
__init__(*args, **kwargs)#
__module__ = 'aiida.storage.psql_dos.orm.querybuilder.joiner'#
__parameters__ = ()#
__subclasshook__()#

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__#

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>#
_is_protocol = True#
property table_groups_nodes: Type[Table]#
aiida.storage.psql_dos.orm.querybuilder.joiner._check_dbentities(entities_cls_joined, entities_cls_to_join, relationship: str)[source]#

Type check for entities

Parameters:
  • entities_cls_joined – A tuple of the aliased class passed as joined_entity and the ormclass that was expected

  • entities_cls_joined – A tuple of the aliased class passed as entity_to_join and the ormclass that was expected

  • relationship (str) – The relationship between the two entities to make the Exception comprehensible

Sqla query builder implementation

class aiida.storage.psql_dos.orm.querybuilder.main.BuiltQuery(query: Query, tag_to_alias: Dict[str, AliasedClass | None], tag_to_projected: Dict[str, Dict[str, int]])[source]#

Bases: object

A class to store the query and the corresponding projections.

__annotations__ = {'query': <class 'sqlalchemy.orm.query.Query'>, 'tag_to_alias': typing.Dict[str, typing.Optional[sqlalchemy.orm.util.AliasedClass]], 'tag_to_projected': typing.Dict[str, typing.Dict[str, int]]}#
__dataclass_fields__ = {'query': Field(name='query',type=<class 'sqlalchemy.orm.query.Query'>,default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'tag_to_alias': Field(name='tag_to_alias',type=typing.Dict[str, typing.Optional[sqlalchemy.orm.util.AliasedClass]],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'tag_to_projected': Field(name='tag_to_projected',type=typing.Dict[str, typing.Dict[str, int]],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}#
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)#
__dict__ = mappingproxy({'__module__': 'aiida.storage.psql_dos.orm.querybuilder.main', '__annotations__': {'query': <class 'sqlalchemy.orm.query.Query'>, 'tag_to_alias': typing.Dict[str, typing.Optional[sqlalchemy.orm.util.AliasedClass]], 'tag_to_projected': typing.Dict[str, typing.Dict[str, int]]}, '__doc__': 'A class to store the query and the corresponding projections.', '__dict__': <attribute '__dict__' of 'BuiltQuery' objects>, '__weakref__': <attribute '__weakref__' of 'BuiltQuery' objects>, '__dataclass_params__': _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False), '__dataclass_fields__': {'query': Field(name='query',type=<class 'sqlalchemy.orm.query.Query'>,default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'tag_to_alias': Field(name='tag_to_alias',type=typing.Dict[str, typing.Optional[sqlalchemy.orm.util.AliasedClass]],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'tag_to_projected': Field(name='tag_to_projected',type=typing.Dict[str, typing.Dict[str, int]],default=<dataclasses._MISSING_TYPE object>,default_factory=<dataclasses._MISSING_TYPE object>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}, '__init__': <function BuiltQuery.__init__>, '__repr__': <function BuiltQuery.__repr__>, '__eq__': <function BuiltQuery.__eq__>, '__hash__': None, '__match_args__': ('query', 'tag_to_alias', 'tag_to_projected')})#
__eq__(other)#

Return self==value.

__hash__ = None#
__init__(query: Query, tag_to_alias: Dict[str, AliasedClass | None], tag_to_projected: Dict[str, Dict[str, int]]) None#
__match_args__ = ('query', 'tag_to_alias', 'tag_to_projected')#
__module__ = 'aiida.storage.psql_dos.orm.querybuilder.main'#
__repr__()#

Return repr(self).

__weakref__#

list of weak references to the object (if defined)

query: Query#
tag_to_alias: Dict[str, AliasedClass | None]#
tag_to_projected: Dict[str, Dict[str, int]]#
class aiida.storage.psql_dos.orm.querybuilder.main.SqlaQueryBuilder(backend)[source]#

Bases: BackendQueryBuilder

QueryBuilder to use with SQLAlchemy-backend and schema defined in backends.sqlalchemy.models

property AuthInfo#
property Comment#
property Computer#
property Group#
property Log#
property Node#
property User#
__abstractmethods__ = frozenset({})#
__init__(backend)[source]#
Parameters:

backend – the backend

__module__ = 'aiida.storage.psql_dos.orm.querybuilder.main'#
_abc_impl = <_abc._abc_data object>#
_build(data: QueryDictType) BuiltQuery[source]#

Build the query and return.

_create_order_by(alias: AliasedClass, field_key: str, entityspec: dict) ColumnElement | InstrumentedAttribute[source]#

Build the order_by parameter of the query.

static _get_projectable_entity(alias: AliasedClass, column_name: str, attrpath: List[str], cast: str | None = None) ColumnElement | InstrumentedAttribute[source]#

Return projectable entity for a given alias and column name.

analyze_query(data: QueryDictType, execute: bool = True, verbose: bool = False) str[source]#

Analyze the query and return the result as a string.

as_sql(data: QueryDictType, inline: bool = False) str[source]#

Return the SQL query as a string.

build_filters(alias: AliasedClass, filter_spec: Dict[str, Any]) BooleanClauseList | None[source]#

Recurse through the filter specification and apply filter operations.

Parameters:
  • alias – The alias of the ORM class the filter will be applied on

  • filter_spec – the specification of the filter

Returns:

an sqlalchemy expression.

count(data: QueryDictType) int[source]#

Return the number of results of the query

first(data: QueryDictType) List[Any] | None[source]#

Executes query, asking for one instance.

Returns:

One row of aiida results

get_creation_statistics(user_pk: int | None = None) Dict[str, Any][source]#

Return a dictionary with the statistics of node creation, summarized by day.

Note:

Days when no nodes were created are not present in the returned ctime_by_day dictionary.

Parameters:

user_pk – If None (default), return statistics for all users. If user pk is specified, return only the statistics for the given user.

Returns:

a dictionary as follows:

{
   "total": TOTAL_NUM_OF_NODES,
   "types": {TYPESTRING1: count, TYPESTRING2: count, ...},
   "ctime_by_day": {'YYYY-MMM-DD': count, ...}
}

where in ctime_by_day the key is a string in the format ‘YYYY-MM-DD’ and the value is an integer with the number of nodes created that day.

get_filter_expr(operator: str, value: Any, attr_key: List[str], is_jsonb: bool, alias=None, column=None, column_name=None)[source]#

Applies a filter on the alias given.

Expects the alias of the ORM-class on which to filter, and filter_spec. Filter_spec contains the specification on the filter. Expects:

Parameters:
  • operator – The operator to apply, see below for further details

  • value – The value for the right side of the expression, the value you want to compare with.

  • path – The path leading to the value

  • is_jsonb – Whether the value is in a json-column, or in an attribute like table.

Implemented and valid operators:

  • for any type: * == (compare single value, eg: ‘==’:5.0) * in (compare whether in list, eg: ‘in’:[5, 6, 34]

  • for floats and integers:
    • >

    • <

    • <=

    • >=

  • for strings:
    • like (case - sensitive), for example ‘like’:’node.calc.%’ will match node.calc.relax and node.calc.RELAX and node.calc. but not node.CALC.relax

    • ilike (case - unsensitive) will also match node.CaLc.relax in the above example

    Note

    The character % is a reserved special character in SQL, and acts as a wildcard. If you specifically want to capture a % in the string, use: _%

  • for arrays and dictionaries (only for the SQLAlchemy implementation):

    • contains: pass a list with all the items that the array should contain, or that should be among the keys, eg: ‘contains’: [‘N’, ‘H’])

    • has_key: pass an element that the list has to contain or that has to be a key, eg: ‘has_key’:’N’)

  • for arrays only (SQLAlchemy version):
    • of_length

    • longer

    • shorter

All the above filters invoke a negation of the expression if preceded by ~:

# first example:
filter_spec = {
    'name' : {
        '~in':[
            'halle',
            'lujah'
        ]
    } # Name not 'halle' or 'lujah'
}

# second example:
filter_spec =  {
    'id' : {
        '~==': 2
    }
} # id is not 2
static get_filter_expr_from_column(operator: str, value: Any, column) BinaryExpression[source]#

A method that returns an valid SQLAlchemy expression.

Parameters:
  • operator – The operator provided by the user (‘==’, ‘>’, …)

  • value – The value to compare with, e.g. (5.0, ‘foo’, [‘a’,’b’])

  • column – an instance of sqlalchemy.orm.attributes.InstrumentedAttribute or

static get_filter_expr_from_jsonb(operator: str, value, attr_key: List[str], column=None, column_name=None, alias=None)[source]#

Return a filter expression

get_query(data: QueryDictType) BuiltQuery[source]#

Return the built query.

To avoid unnecessary re-builds of the query, the hashed dictionary representation of this instance is compared to the last query returned, which is cached by its hash.

get_session() Session[source]#

Get the connection to the database

iterall(data: QueryDictType, batch_size: int | None) Iterable[List[Any]][source]#

Return an iterator over all the results of a list of lists.

iterdict(data: QueryDictType, batch_size: int | None) Iterable[Dict[str, Dict[str, Any]]][source]#

Return an iterator over all the results of a list of dictionaries.

query_session(data: QueryDictType) Iterator[BuiltQuery][source]#

Yield the built query, ensuring the session is closed on an exception.

property table_groups_nodes#
to_backend(res) Any[source]#

Convert results to return backend specific objects.

  • convert DbModel instances to BackendEntity instances.

  • convert UUIDs to strings

Parameters:

res – the result returned by the query

:returns:backend compatible instance

aiida.storage.psql_dos.orm.querybuilder.main._create_projections(tag: str, aliases: Dict[str, AliasedClass | None], projection_count: int, project_dict: List[Dict[str, dict]], get_projectable_entity, tag_to_projected_fields, outer_to_inner_schema) List[Tuple[AliasedClass | ColumnElement, bool]][source]#

Build the projections for a given tag.

Parameters:
  • tag – the tag of the node for which to build the projections

  • projection_count – the number of previous projections

  • items_to_project – the list of projections to build, if None, use the projections specified in the query

aiida.storage.psql_dos.orm.querybuilder.main._get_projection(alias: AliasedClass, projectable_entity_name: str, get_projectable_entity, cast: str | None = None, func: str | None = None, **_kw: Any) Tuple[AliasedClass | ColumnElement, bool][source]#
Parameters:
  • alias – An alias for an ormclass

  • projectable_entity_name – User specification of what to project. Appends to query’s entities what the user wants to project (have returned by the query)

  • cast – Cast the value to a different type

  • func – Apply a function to the projection

Returns:

The projection

aiida.storage.psql_dos.orm.querybuilder.main.compile_query(query: Query, literal_binds: bool = False) SQLCompiler[source]#

Compile the query to the SQL executable.

Params literal_binds:

Inline bound parameters (this is normally handled by the Python DBAPI).

aiida.storage.psql_dos.orm.querybuilder.main.generate_joins(data: QueryDictType, aliases: Dict[str, AliasedClass | None], joiner: SqlaJoiner) List[JoinReturn][source]#

Generate the joins for the query.

aiida.storage.psql_dos.orm.querybuilder.main.generate_projections(data: QueryDictType, aliases: Dict[str, AliasedClass | None], outer_to_inner_schema, get_projectable_entity)[source]#

Generate the projections for the query.

aiida.storage.psql_dos.orm.querybuilder.main.get_column(colname: str, alias: AliasedClass) InstrumentedAttribute[source]#

Return the column for a given projection.

aiida.storage.psql_dos.orm.querybuilder.main.get_column_names(alias: AliasedClass) List[str][source]#

Given the backend specific alias, return the column names that correspond to the aliased table.

aiida.storage.psql_dos.orm.querybuilder.main.get_corresponding_properties(entity_table: str, given_properties: List[str], mapper: Dict[str, Dict[str, str]])[source]#

This method returns a list of updated properties for a given list of properties. If there is no update for the property, the given property is returned in the list.

aiida.storage.psql_dos.orm.querybuilder.main.get_corresponding_property(entity_table: str, given_property: str, mapper: Dict[str, Dict[str, str]]) str[source]#

This method returns an updated property for a given a property. If there is no update for the property, the given property is returned.

aiida.storage.psql_dos.orm.querybuilder.main.get_table_name(aliased_class: AliasedClass) str[source]#

Returns the table name given an Aliased class

aiida.storage.psql_dos.orm.querybuilder.main.modify_expansions(alias: AliasedClass, expansions: List[str], outer_to_inner_schema=typing.Dict[str, typing.Dict[str, str]]) List[str][source]#

Modify names of projections if ** was specified.

This is important for the schema having attributes in a different table. In SQLA, the metadata should be changed to _metadata to be in-line with the database schema