diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..95639318d100a5a4a568b326b99090aafbfbba36 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,56 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +from cymple.version import __version__ +sys.path.insert(0, os.path.abspath('..')) + + +# -- Project information ----------------------------------------------------- + +project = 'Cymple' +copyright = '2022, Accenture Labs Israel' +author = 'Accenture Labs Israel' +version = __version__ +release = __version__ + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] \ No newline at end of file diff --git a/src/cymple/__init__.py b/src/cymple/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7b8346ccd3fd826b8b636845d151db26a28280 --- /dev/null +++ b/src/cymple/__init__.py @@ -0,0 +1,7 @@ +"""Cymple - Cypher Modular Pythonic Language Extension +A productivity enhancer for creating Cypher queries in Python +""" + +from .version import __version__ +from .builder import QueryBuilder +from .typedefs import Mapping diff --git a/src/cymple/__main__.py b/src/cymple/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e5261547e01fc89e5e6d60e3119d12c1fb7b1d --- /dev/null +++ b/src/cymple/__main__.py @@ -0,0 +1,6 @@ +"""Package entrypoint when the package is run with -m option""" + +from .version import __version__ + +if __name__ == '__main__': + print('Welcome to Cymple version ' + __version__) diff --git a/src/cymple/builder.py b/src/cymple/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc993eab90f41cf231b738e99425cdb0fcd007b --- /dev/null +++ b/src/cymple/builder.py @@ -0,0 +1,1016 @@ +"""This is the Cymple query builder module.""" + +# pylint: disable=R0901 +# pylint: disable=R0903 +# pylint: disable=W0102 +from typing import List, Union, Dict, Any +from .typedefs import Mapping, Properties + + +class Query(): + """A general query-descripting class .""" + + def __init__(self, query): + """Initialize the query object.""" + self.query = query + + def __str__(self) -> str: + """Implement the str() operator for the query builder.""" + return self.query.strip() + + def __add__(self, other): + """Implement the + operator for the query builder.""" + return Query(self.query.strip() + ' ' + other.query.strip()) + + def __iadd__(self, other): + """Implement the += operator for the query builder.""" + self.query = self.query.strip() + ' ' + other.query.strip() + return self + + def get(self): + """Get the final query string .""" + return str(self) + + def cypher(self, cypher_query_str): + """Concatenate a cypher query string""" + return AnyAvailable(self.query.strip() + ' ' + cypher_query_str.strip()) + + +class QueryStart(Query): + """A class for representing a "QUERY START" clause.""" + + +class Call(Query): + """A class for representing a "CALL" clause.""" + + def call(self): + """Concatenate the "CALL" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: CallAvailable + """ + return CallAvailable(self.query + ' CALL') + + +class Case(Query): + """A class for representing a "CASE" clause.""" + + def case(self, when_then_mapping: Dict[str, Union[List[str], str]], default_result: str, results_ref: str = None, test_expression: str = None): + """Concatenate a CASE clause to the query, to compare a single expression against multiple values or to express multiple conditional statements. + + :param when_then_mapping: A dictionary such that a value represents a literal expression (or a list of + expressions) whose result will be compared to test_expression if given, else is evaluated to a BOOLEAN, and it's key represents the literal expression returned as output if the value matches test_expression if giver, or if the expression evaluates to TRUE. + :type when_then_mapping: Dict[str, Union[List[str], str]] + :param default_result: The expression to return if no value matches the test expression if given, or if all + expressions evaluated as FALSE. + :type default_result: str + :param results_ref: The reference name of the resulted returned values, plus any other desired reference names + to return., defaults to None + :type results_ref: str + :param test_expression: An expression to test the cases against. For example, 'n.name'. Optional., defaults to + None + :type test_expression: str + + :return: A Query object with a query that contains the new clause. + :rtype: CaseAvailable + """ + ret = " CASE" + if test_expression is not None: + ret += f" {test_expression}" + for then, when in when_then_mapping.items(): + if type(when) is not list: + when = [when] + ret += f" WHEN {', '.join(when)} THEN {then}" + ret += f" ELSE {default_result} END" + if results_ref is not None: + ret += f" AS {results_ref}" + return CaseAvailable(self.query + ret) + + +class CaseWhen(Query): + """A class for representing a "CASE WHEN" clause.""" + + def case_when(self, filters: dict, on_true: str, on_false: str, ref_name: str, comparison_operator: str = "=", boolean_operator: str = "AND", **kwargs): + """Concatenate a CASE WHEN clause to the query, created from a list of given property filters. + + :param filters: A dict representing the set of properties to be filtered + :type filters: dict + :param on_true: The query to run when the predicate is true + :type on_true: str + :param on_false: The query to run when the predicate is false + :type on_false: str + :param ref_name: The name which is used to refer to the newly filtered object + :type ref_name: str + :param comparison_operator: A string operator, according to which the comparison between property values is + done, e.g. for "=", we get: property.name = property.value, defaults to "=" + :type comparison_operator: str + :param boolean_operator: The boolean operator to apply between predicates, defaults to "AND" + :type boolean_operator: str + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: CaseWhenAvailable + """ + filt = ' CASE WHEN ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs) + filt += f' THEN {on_true} ELSE {on_false} END AS {ref_name}' + return CaseWhenAvailable(self.query + filt) + + +class Create(Query): + """A class for representing a "CREATE" clause.""" + + def create(self): + """Concatenate the "CREATE" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: CreateAvailable + """ + return CreateAvailable(self.query + ' CREATE') + + +class Delete(Query): + """A class for representing a "DELETE" clause.""" + + def delete(self, ref_name: str): + """Concatenate a DELETE clause for a referenced instance from the DB. + + :param ref_name: The reference name to be used for the delete operation + :type ref_name: str + + :return: A Query object with a query that contains the new clause. + :rtype: DeleteAvailable + """ + ret = f' DELETE {ref_name}' + return DeleteAvailable(self.query + ret) + + def detach_delete(self, ref_name: str): + """Concatenate a DETACH DELETE clause for a referenced instance from the DB. + + :param ref_name: The reference name to be used for the delete operation + :type ref_name: str + + :return: A Query object with a query that contains the new clause. + :rtype: DeleteAvailable + """ + ret = f' DETACH DELETE {ref_name}' + return DeleteAvailable(self.query + ret) + + +class Limit(Query): + """A class for representing a "LIMIT" clause.""" + + def limit(self, limitation: Union[int, str]): + """Concatenate a limit statement. + + :param limitation: A non-negative integer or a string of cypher expression that evaluates to a non-negative + integer (as long as it is not referring to any external variables) + :type limitation: Union[int, str] + + :return: A Query object with a query that contains the new clause. + :rtype: LimitAvailable + """ + ret = f" LIMIT {limitation}" + return LimitAvailable(self.query + ret) + + +class Match(Query): + """A class for representing a "MATCH" clause.""" + + def match(self): + """Concatenate the "MATCH" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: MatchAvailable + """ + return MatchAvailable(self.query + ' MATCH') + + def match_optional(self): + """Concatenate the "MATCH" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: MatchAvailable + """ + return MatchAvailable(self.query + ' OPTIONAL MATCH ') + + +class Merge(Query): + """A class for representing a "MERGE" clause.""" + + def merge(self): + """Concatenate the "MERGE" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: MergeAvailable + """ + return MergeAvailable(self.query + ' MERGE') + + +class Node(Query): + """A class for representing a "NODE" clause.""" + + def node(self, labels: Union[List[str], str] = None, ref_name: str = None, properties: dict = None, **kwargs): + """Concatenate a graph Node, which may be filtered using any label/s and/or property/properties. + + :param labels: The neo4j label (or list of labels) for that node, defaults to None + :type labels: Union[List[str], str] + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the nodes are filtered, defaults to None + :type properties: dict + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: NodeAvailable + """ + if not labels: + labels_string = '' + elif isinstance(labels, str): + labels_string = f': {labels}' + else: + labels_string = f': {": ".join(labels).strip()}' + + if not properties: + property_string = '' + else: + property_string = f' {{{Properties(properties).to_str(**kwargs)}}}' + + ref_name = ref_name or '' + + query = self.query + if not (query.endswith('-') or query.endswith('>') or query.endswith('<')): + query += ' ' + + query += f'({ref_name}{labels_string}{property_string})' + + if isinstance(self, MergeAvailable): + return NodeAfterMergeAvailable(query) + + return NodeAvailable(query) + + +class NodeAfterMerge(Query): + """A class for representing a "NODE AFTER MERGE" clause.""" + + def node(self, labels: Union[List[str], str] = None, ref_name: str = None, properties: dict = None, **kwargs): + """Concatenate a graph Node, which may be filtered using any label/s and/or property/properties. + + :param labels: The neo4j label (or list of labels) for that node, defaults to None + :type labels: Union[List[str], str] + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the nodes are filtered, defaults to None + :type properties: dict + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: NodeAfterMergeAvailable + """ + if not labels: + labels_string = '' + elif isinstance(labels, str): + labels_string = f': {labels}' + else: + labels_string = f': {": ".join(labels).strip()}' + + if not properties: + property_string = '' + else: + property_string = f' {{{Properties(properties).to_str(**kwargs)}}}' + + ref_name = ref_name or '' + + query = self.query + if not (query.endswith('-') or query.endswith('>') or query.endswith('<')): + query += ' ' + + query += f'({ref_name}{labels_string}{property_string})' + + if isinstance(self, MergeAvailable): + return NodeAfterMergeAvailable(query) + + return NodeAvailable(query) + + +class OnCreate(Query): + """A class for representing a "ON CREATE" clause.""" + + def on_create(self): + """Concatenate the "ON CREATE" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: OnCreateAvailable + """ + return OnCreateAvailable(self.query + ' ON CREATE') + + +class OnMatch(Query): + """A class for representing a "ON MATCH" clause.""" + + def on_match(self): + """Concatenate the "ON MATCH" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: OnMatchAvailable + """ + return OnMatchAvailable(self.query + ' ON MATCH') + + +class OperatorEnd(Query): + """A class for representing a "OPERATOR END" clause.""" + + def operator_end(self): + """Concatenate the "OPERATOR END" clause. + + :return: A Query object with a query that contains the new clause. + :rtype: OperatorEndAvailable + """ + return OperatorEndAvailable(self.query + ' )') + + +class OperatorStart(Query): + """A class for representing a "OPERATOR START" clause.""" + + def operator_start(self, operator: str, ref_name: str = None, args: dict = None): + """Concatenate an operator (e.g. ShortestPath), where its result may be given a name for future reference. + + :param operator: The neo4j operator to be used (e.g. ShortestPath) + :type operator: str + :param ref_name: A reference name of the result, to be used later in the rest of the query, defaults to None + :type ref_name: str + :param args: A dict of arguments, to be passed to the operator function, defaults to None + :type args: dict + + :return: A Query object with a query that contains the new clause. + :rtype: OperatorStartAvailable + """ + result_name = '' if ref_name is None else f'{ref_name} = ' + arguments = '' if args is None else f' {args}' + + return OperatorStartAvailable(self.query + f' {result_name}{operator}({arguments}') + + +class OrderBy(Query): + """A class for representing a "ORDER BY" clause.""" + + def order_by(self, sorting_properties: Union[str, List[str]], ascending: bool = True): + """Concatenate an order by statement. + + :param sorting_properties: A string or a list of strings representing the properties based on which to sort. + :type sorting_properties: Union[str, List[str]] + :param ascending: Use ascending sorting (if false, uses descending)., defaults to True + :type ascending: bool + + :return: A Query object with a query that contains the new clause. + :rtype: OrderByAvailable + """ + if type(sorting_properties) != list: + sorting_properties = [sorting_properties] + + ret = f" ORDER BY {', '.join(sorting_properties)}" + ret += " ASC" if ascending else " DESC" + return OrderByAvailable(self.query + ret) + + +class Procedure(Query): + """A class for representing a "PROCEDURE" clause.""" + + def procedure(self, literal_procedure: str): + """Concatenate a literal procedure. + + :param literal_procedure: A string that is evaluated to a cypher procedure + :type literal_procedure: str + + :return: A Query object with a query that contains the new clause. + :rtype: ProcedureAvailable + """ + ret = f" {literal_procedure}" + return ProcedureAvailable(self.query + ret) + + +class Relation(Query): + """A class for representing a "RELATION" clause.""" + + def related(self, label: str = None, ref_name: str = None, properties: dict = None, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate an undirectional (i.e. --) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + None + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAvailable + """ + return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def related_to(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a forward (i.e. -->) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAvailable + """ + return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def related_from(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a backward (i.e. <--) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAvailable + """ + return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a graph Relationship (private method). + + :param direction: The relationship direction, can one of 'forward', 'backward' - otherwise unidirectional + :type direction: str + :param label: The relationship label (type) in the DB + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAvailable + """ + min_hops_str = '' if min_hops == -1 else str(min_hops) + max_hops_str = '' if max_hops == -1 else str(max_hops) + + relation_type = '' if label is None else f': {label}' + relation_ref_name = '' if ref_name is None else f'{ref_name}' + relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else '' + if min_hops == 1 and max_hops == 1: + relation_length = '' + elif min_hops == -1 and max_hops == -1: + relation_length = '*' + elif min_hops == max_hops: + relation_length = f'*{min_hops_str}' + else: + relation_length = f'*{min_hops_str}..{max_hops_str}' + + if relation_ref_name or relation_type or relation_length or relation_properties: + relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]' + else: + relation_str = '' + + if direction == 'forward': + return f'-{relation_str}->' + if direction == 'backward': + return f'<-{relation_str}-' + + return f'-{relation_str}-' + + +class RelationAfterMerge(Query): + """A class for representing a "RELATION AFTER MERGE" clause.""" + + def related(self, label: str = None, ref_name: str = None, properties: dict = None, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate an undirectional (i.e. --) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + None + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAfterMergeAvailable + """ + return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def related_to(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a forward (i.e. -->) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAfterMergeAvailable + """ + return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def related_from(self, label: str = None, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a backward (i.e. <--) graph Relationship, which may be filtered. + + :param label: The relationship label (type) in the DB, defaults to None + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAfterMergeAvailable + """ + return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + """Concatenate a graph Relationship (private method). + + :param direction: The relationship direction, can one of 'forward', 'backward' - otherwise unidirectional + :type direction: str + :param label: The relationship label (type) in the DB + :type label: str + :param ref_name: A reference name to be used later in the rest of the query, defaults to None + :type ref_name: str + :param properties: A dict representing the set of properties by which the relationship is filtered, defaults to + {} + :type properties: dict + :param min_hops: The minimal desired number of hops (set -1 for maximum boundary only), defaults to 1 + :type min_hops: int + :param max_hops: The maximal desired number of hops (set -1 for minimal boundary only), defaults to 1 + :type max_hops: int + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: RelationAfterMergeAvailable + """ + min_hops_str = '' if min_hops == -1 else str(min_hops) + max_hops_str = '' if max_hops == -1 else str(max_hops) + + relation_type = '' if label is None else f': {label}' + relation_ref_name = '' if ref_name is None else f'{ref_name}' + relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else '' + if min_hops == 1 and max_hops == 1: + relation_length = '' + elif min_hops == -1 and max_hops == -1: + relation_length = '*' + elif min_hops == max_hops: + relation_length = f'*{min_hops_str}' + else: + relation_length = f'*{min_hops_str}..{max_hops_str}' + + if relation_ref_name or relation_type or relation_length or relation_properties: + relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]' + else: + relation_str = '' + + if direction == 'forward': + return f'-{relation_str}->' + if direction == 'backward': + return f'<-{relation_str}-' + + return f'-{relation_str}-' + + +class Remove(Query): + """A class for representing a "REMOVE" clause.""" + + def remove(self, properties: Union[str, List[str]]): + """Concatenate a remove by statement. + + :param properties: A string or a list of strings representing the properties to remove. + :type properties: Union[str, List[str]] + + :return: A Query object with a query that contains the new clause. + :rtype: RemoveAvailable + """ + if type(properties) != list: + properties = [properties] + ret = f" REMOVE {', '.join(properties)}" + return RemoveAvailable(self.query + ret) + + +class Return(Query): + """A class for representing a "RETURN" clause.""" + + def return_literal(self, literal: str = None): + """Concatenate a literal RETURN statement. + + :param literal: A Cypher string describing the objects to be returned, referencing name/names which were + defined earlier in the query, defaults to None + :type literal: str + + :return: A Query object with a query that contains the new clause. + :rtype: ReturnAvailable + """ + ret = f' RETURN' + if literal is not None: + ret += f' {literal}' + + return ReturnAvailable(self.query + ret) + + def return_mapping(self, mappings: List[Mapping]): + """Concatenate a RETURN statement for multiple objects. + + :param mappings: The mapping (or a list of mappings) of db property names to code names, to be returned + :type mappings: List[Mapping] + + :return: A Query object with a query that contains the new clause. + :rtype: ReturnAvailable + """ + if not isinstance(mappings, list): + mappings = [mappings] + + ret = ' RETURN ' + \ + ', '.join( + f'{mapping[0]} AS {mapping[1]}' if mapping[1] else mapping[0].replace(".", "_") + for mapping in mappings) + + return ReturnAvailable(self.query + ret) + + +class Set(Query): + """A class for representing a "SET" clause.""" + + def set(self, properties: dict, escape_values: bool = True): + """Concatenate a SET clause, using the given properties map. + + :param properties: A dict to be used to set the variables with their corresponding values + :type properties: dict + :param escape_values: Determines whether the properties values should be escaped or not, defaults to True + :type escape_values: bool + + :return: A Query object with a query that contains the new clause. + :rtype: SetAvailable + """ + if isinstance(properties, dict): + _properties = Properties(properties).to_str("=", ", ", escape_values) + else: + _properties = str(properties) + + query = self.query + ' SET ' + _properties + + if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable): + return SetAfterMergeAvailable(query) + + return SetAvailable(query) + + +class SetAfterMerge(Query): + """A class for representing a "SET AFTER MERGE" clause.""" + + def set(self, properties: dict, escape_values: bool = True): + """Concatenate a SET clause, using the given properties map. + + :param properties: A dict to be used to set the variables with their corresponding values + :type properties: dict + :param escape_values: Determines whether the properties values should be escaped or not, defaults to True + :type escape_values: bool + + :return: A Query object with a query that contains the new clause. + :rtype: SetAfterMergeAvailable + """ + if isinstance(properties, dict): + _properties = Properties(properties).to_str("=", ", ", escape_values) + else: + _properties = str(properties) + + query = self.query + ' SET ' + _properties + + if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable): + return SetAfterMergeAvailable(query) + + return SetAvailable(query) + + +class Skip(Query): + """A class for representing a "SKIP" clause.""" + + def skip(self, skip_count: Union[int, str]): + """Concatenate a skip statement. + + :param skip_count: A non-negative integer or a string of cypher expression that evaluates to a non-negative + integer (as long as it is not referring to any external variables) + :type skip_count: Union[int, str] + + :return: A Query object with a query that contains the new clause. + :rtype: SkipAvailable + """ + ret = f" SKIP {skip_count}" + return SkipAvailable(self.query + ret) + + +class Union(Query): + """A class for representing a "UNION" clause.""" + + def union(self): + """Combines the results of two or more queries. Duplicates are removed. + + :return: A Query object with a query that contains the new clause. + :rtype: UnionAvailable + """ + return UnionAvailable(self.query + f' UNION') + + def union_all(self): + """Combines the results of two or more queries including duplicates. + + :return: A Query object with a query that contains the new clause. + :rtype: UnionAvailable + """ + return UnionAvailable(self.query + f' UNION ALL') + + +class Unwind(Query): + """A class for representing a "UNWIND" clause.""" + + def unwind(self, variables: str): + """Concatenate an UNWIND clause, keeping one or more variables given in 'variables' arg. + + :param variables: A string refering to previously obtained variables, comma seperated + :type variables: str + + :return: A Query object with a query that contains the new clause. + :rtype: UnwindAvailable + """ + return UnwindAvailable(self.query + f' UNWIND {variables}') + + +class Where(Query): + """A class for representing a "WHERE" clause.""" + + def where(self, name: str, comparison_operator: str, value: str, **kwargs): + """Concatenate a WHERE clause to the query, created as {name} {comparison_operator} {value}. E.g. x = 'abc'. + + :param name: The name of the object which is to be used in the comparison + :type name: str + :param comparison_operator: A string operator, according to which the comparison between compared object and + the {value} is done, e.g. for "=", we get: {name} = {value} + :type comparison_operator: str + :param value: The value which is compared against + :type value: str + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: WhereAvailable + """ + return self.where_multiple({name: value}, comparison_operator, **kwargs) + + def where_multiple(self, filters: dict, comparison_operator: str = "=", boolean_operator: str = ' AND ', **kwargs): + """Concatenate a WHERE clause to the query, created from a list of given property filters. + + :param filters: A dict representing the set of properties to be filtered + :type filters: dict + :param comparison_operator: A string operator, according to which the comparison between property values is + done, e.g. for "=", we get: property.name = property.value, defaults to "=" + :type comparison_operator: str + :param boolean_operator: The boolean operator to apply between predicates, defaults to ' AND ' + :type boolean_operator: str + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: WhereAvailable + """ + filt = ' WHERE ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs) + return WhereAvailable(self.query + filt) + + def where_literal(self, statement: str, **kwargs): + """Concatenate a literal WHERE clause to the query. + + :param statement: A literal string of the required filter + :type statement: str + :param **kwargs: kwargs + :type **kwargs + + :return: A Query object with a query that contains the new clause. + :rtype: WhereAvailable + """ + filt = ' WHERE ' + statement + return WhereAvailable(self.query + filt) + + +class With(Query): + """A class for representing a "WITH" clause.""" + + def with_(self, variables: str): + """Concatenate a WITH clause, keeping one or more variables given in 'variables' arg. + + :param variables: A string refering to previously obtained variables, comma seperated + :type variables: str + + :return: A Query object with a query that contains the new clause. + :rtype: WithAvailable + """ + return WithAvailable(self.query + f' WITH {variables}') + + +class Yield(Query): + """A class for representing a "YIELD" clause.""" + + def yield_(self, mappings: List[Mapping]): + """Concatenate a YIELD cluase, to yield a list of Mappings. + + :param mappings: The list of mappings of db properties names to code names, to be yielded + :type mappings: List[Mapping] + + :return: A Query object with a query that contains the new clause. + :rtype: YieldAvailable + """ + if not isinstance(mappings, list): + mappings = [mappings] + + query = ' YIELD ' + \ + ', '.join(f'{mapping[0]} AS ' + f'{mapping[1] if mapping[1] else mapping[0].replace(".", "_")}' + for mapping in mappings) + return YieldAvailable(self.query + query) + + +class QueryStartAvailable(Match, Merge, Call, Create, With): + """A class decorator declares a QueryStart is available in the current query.""" + + +class CallAvailable(Procedure): + """A class decorator declares a Call is available in the current query.""" + + +class CaseAvailable(QueryStartAvailable, Unwind, Where, Set, Remove, CaseWhen, Return, Limit, Skip, OrderBy, Union): + """A class decorator declares a Case is available in the current query.""" + + +class CaseWhenAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set): + """A class decorator declares a CaseWhen is available in the current query.""" + + +class CreateAvailable(Node, Union): + """A class decorator declares a Create is available in the current query.""" + + +class DeleteAvailable(Return, CaseWhen, Union): + """A class decorator declares a Delete is available in the current query.""" + + +class LimitAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set, Skip, Union): + """A class decorator declares a Limit is available in the current query.""" + + +class MatchAvailable(Node, Return, OperatorStart): + """A class decorator declares a Match is available in the current query.""" + + +class MergeAvailable(NodeAfterMerge, Return, OperatorStart, Union): + """A class decorator declares a Merge is available in the current query.""" + + +class NodeAvailable(Relation, Return, Delete, Where, OperatorStart, OperatorEnd, Set, QueryStartAvailable, Merge, Remove): + """A class decorator declares a Node is available in the current query.""" + + +class NodeAfterMergeAvailable(RelationAfterMerge, Return, Delete, OperatorStart, OperatorEnd, SetAfterMerge, OnCreate, OnMatch, QueryStartAvailable): + """A class decorator declares a NodeAfterMerge is available in the current query.""" + + +class OnCreateAvailable(SetAfterMerge, OperatorStart): + """A class decorator declares a OnCreate is available in the current query.""" + + +class OnMatchAvailable(SetAfterMerge, OperatorStart): + """A class decorator declares a OnMatch is available in the current query.""" + + +class OperatorEndAvailable(QueryStartAvailable, Yield, With, Return): + """A class decorator declares a OperatorEnd is available in the current query.""" + + +class OperatorStartAvailable(QueryStartAvailable, Node, OperatorEnd): + """A class decorator declares a OperatorStart is available in the current query.""" + + +class OrderByAvailable(Limit, Skip, Union): + """A class decorator declares a OrderBy is available in the current query.""" + + +class ProcedureAvailable(Yield, Return, QueryStartAvailable, Union): + """A class decorator declares a Procedure is available in the current query.""" + + +class RelationAvailable(Node): + """A class decorator declares a Relation is available in the current query.""" + + +class RelationAfterMergeAvailable(NodeAfterMerge): + """A class decorator declares a RelationAfterMerge is available in the current query.""" + + +class RemoveAvailable(Set, Return, Union): + """A class decorator declares a Remove is available in the current query.""" + + +class ReturnAvailable(QueryStartAvailable, Unwind, Return, Limit, Skip, OrderBy, Union, CaseWhen, Case): + """A class decorator declares a Return is available in the current query.""" + + +class SetAvailable(QueryStartAvailable, Set, Remove, Unwind, Return, Union): + """A class decorator declares a Set is available in the current query.""" + + +class SetAfterMergeAvailable(QueryStartAvailable, OnCreate, OnMatch, SetAfterMerge, Unwind, Return, Union): + """A class decorator declares a SetAfterMerge is available in the current query.""" + + +class SkipAvailable(QueryStartAvailable, Unwind, Where, CaseWhen, Return, Set, Remove, Limit, Union): + """A class decorator declares a Skip is available in the current query.""" + + +class UnionAvailable(Call, Create, Delete, Match, Merge, Remove, Return, Set, Unwind, With): + """A class decorator declares a Union is available in the current query.""" + + +class UnwindAvailable(QueryStartAvailable, Unwind, Return, Create, Remove): + """A class decorator declares a Unwind is available in the current query.""" + + +class WhereAvailable(Return, Delete, Where, Set, Remove, OperatorStart, QueryStartAvailable): + """A class decorator declares a Where is available in the current query.""" + + +class WithAvailable(QueryStartAvailable, Unwind, Where, Set, Remove, CaseWhen, Return, Limit, Skip, OrderBy, Case): + """A class decorator declares a With is available in the current query.""" + + +class YieldAvailable(QueryStartAvailable, Node, Where, Return): + """A class decorator declares a Yield is available in the current query.""" + + +class AnyAvailable(Call, Case, CaseWhen, Create, Delete, Limit, Match, Merge, Node, NodeAfterMerge, OnCreate, OnMatch, OperatorEnd, OperatorStart, OrderBy, Procedure, QueryStart, Relation, RelationAfterMerge, Remove, Return, Set, SetAfterMerge, Skip, Union, Unwind, Where, With, Yield): + """A class decorator declares anything is available in the current query.""" + + +class QueryBuilder(QueryStartAvailable): + """The Query Builder's initial interface.""" + + def __init__(self) -> None: + """Initialize a query builder.""" + super().__init__('') + + def reset(self): + """Reset the query to an empty string.""" + self.query = '' + return self diff --git a/src/cymple/internal/finale.py b/src/cymple/internal/finale.py new file mode 100644 index 0000000000000000000000000000000000000000..59e9b8412f8ea24a29f0f47cd04482cfa22765fa --- /dev/null +++ b/src/cymple/internal/finale.py @@ -0,0 +1,11 @@ +class QueryBuilder(QueryStartAvailable): + """The Query Builder's initial interface.""" + + def __init__(self) -> None: + """Initialize a query builder.""" + super().__init__('') + + def reset(self): + """Reset the query to an empty string.""" + self.query = '' + return self diff --git a/src/cymple/internal/internal_renderer.py b/src/cymple/internal/internal_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..86e44e2a0eeed31def96c2eafa87fd0ba493a302 --- /dev/null +++ b/src/cymple/internal/internal_renderer.py @@ -0,0 +1,181 @@ +"""Internal Rendering module, used for creating a new builder implementation.""" + +import inspect +import json +import os +import pathlib +import preface +import overloads + +query_class = getattr(preface, preface.Query.__name__) + +MAX_LINE_LEN = 120 + + +def _render_clause(declaration: dict): + main_output = '' + decorators_output = '' + + clause_name = declaration['clause_name'].upper() + clause_name_title = declaration['clause_name'].title().replace(' ', '') + + successors = declaration['successors'] + avilability_class_str = f'class {clause_name_title}Available({", ".join(successors)}):' + '\n ' + avilability_class_str += f'"""A class decorator declares a {clause_name_title} is available in the current query."""' + '\n\n' + decorators_output += avilability_class_str + + main_output += f'class {clause_name_title}({query_class.__name__}):' + '\n ' + main_output += f'"""A class for representing a "{clause_name}" clause."""' + '\n\n' + + methods = declaration.get('methods') + + if not methods and clause_name != 'QUERY START': + methods = [{'name': clause_name.replace(' ', '_')}] + + for method in methods: + docstring_summary = method.get('docstring_summary', f'Concatenate the "{clause_name}" clause.') + method_name = method['name'].lower() + args = method.get('args') + args_str = 'self' + + if not docstring_summary.endswith('.'): + docstring_summary = docstring_summary + '.' + docstring_summary += '\n ' + + docstring_params = '' + method_overload = None + + if args: + for arg_name, arg_meta in args.items(): + arg_description = arg_meta.get('description', '') + arg_type = arg_meta.get('type', '') + arg_default = arg_meta.get('default', '') + args_str += ', ' + \ + f'{arg_name}{": " + arg_type if arg_type else ""}{" = " + arg_default if arg_default else ""}' + + docstring_params += ':param ' + arg_name + (': ' + arg_description if arg_description else ': ' + arg_name) + ( + f', defaults to {arg_default}' if arg_default else '') + '\n ' + docstring_params += ':type ' + arg_name + \ + (f': {arg_type}' if arg_type else '' + ', optional' if arg_default else '') + '\n ' + + try: + method_overload = getattr(overloads, method_name) + except Exception as ex: + print(f'Note: No overload to method "{method_name}" ({ex}).') + + if method_overload: + try: + try: + method_overload.__doc__ = '' + except Exception as exc: + print(exc) + + # overload = inspect.getsource(method_overload) + def_lines = inspect.getsourcelines(method_overload)[0] + overload = '' + flag = False + for line in def_lines: + if flag: + overload += line + elif line.strip().startswith(f'def {method_name}'): + flag = True + + overload = overload.replace('\n', '\n ') + + except Exception as ex: + print(f'Couldn\'t overload method "{method_name}". Exception: {ex}') + overload = '' + else: + overload = '' + + main_output += f' def {method_name}({args_str}):' + '\n ' + main_output += f'"""{docstring_summary}' + '\n ' + main_output += f'{docstring_params}' + '\n ' if docstring_params else '' + main_output += f':return: A Query object with a query that contains the new clause.' + '\n ' + main_output += f':rtype: {clause_name_title}Available' + '\n ' + main_output += f'"""' + '\n ' + + if overload: + main_output += overload.strip() + else: + main_output += f'return {clause_name_title}Available(self.query + \' {clause_name}\')' + + main_output += '\n\n' + + lines = main_output.split('\n') + new_lines = [] + + for line in lines: + if len(line) >= MAX_LINE_LEN: + white_space_idx = 0 + start_idx = 0 + + if ':param' in line: + start_idx = line.index(':param') + + try: + while line.index(' ', white_space_idx + 1) < MAX_LINE_LEN: + white_space_idx = line.index(' ', white_space_idx + 1) + except: + pass + + if start_idx > 0 and white_space_idx > start_idx: + new_lines.append(line[0:white_space_idx]) + new_lines.append(' ' * start_idx + ' ' + line[white_space_idx+1:]) + else: + new_lines.append(line) + else: + new_lines.append(line) + + main_output = '\n'.join(new_lines) + + return main_output, decorators_output, clause_name_title + + +def render_builder_code(): + """Main function to invoke to render a new builder implementation.""" + clauses_output = '"""This is the Cymple query builder module."""\n\n' + clauses_output += '# pylint: disable=R0901\n' + clauses_output += '# pylint: disable=R0903\n' + clauses_output += '# pylint: disable=W0102\n' + clauses_output += 'from typing import List, Union, Dict, Any\n' + clauses_output += 'from .typedefs import Mapping, Properties\n\n' + clauses_output += inspect.getsource(query_class) + '\n\n' + + decorators_output = '\n' + + all_clauses_titles = set() + + declarations_fps = os.listdir(os.path.join(os.path.dirname(__file__), 'declarations')) + declarations_fps.sort() + + for file in declarations_fps: + if file.endswith('.json'): + path = os.path.join(os.path.dirname(__file__), 'declarations', file) + + with open(path) as file: + declaration = json.load(file) + add_clause_output, add_decorators_output, clause_name_title = _render_clause(declaration) + clauses_output += add_clause_output + decorators_output += add_decorators_output + all_clauses_titles.add(clause_name_title) + + any_clause_decorator_output = f'class AnyAvailable({", ".join(sorted(all_clauses_titles))}):' + '\n ' + any_clause_decorator_output += f'"""A class decorator declares anything is available in the current query."""' + '\n\n' + + with open(os.path.join(os.path.dirname(__file__), 'finale.py')) as file: + finale_output = file.read() + + with open(os.path.join(os.path.dirname(__file__), '../builder.py'), 'w+') as file: + file.write(clauses_output) + file.write(decorators_output) + file.write(any_clause_decorator_output) + file.write(finale_output) + + builder_path = os.path.join(pathlib.Path(__file__).parent.parent.resolve(), "builder.py") + os.system( + f'autopep8 {builder_path} --in-place --max-line-length {MAX_LINE_LEN}') + + +if __name__ == '__main__': + render_builder_code() diff --git a/src/cymple/internal/overloads/__init__.py b/src/cymple/internal/overloads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c28e87a347bf63726f3e046e737c8859322bca --- /dev/null +++ b/src/cymple/internal/overloads/__init__.py @@ -0,0 +1,15 @@ +import sys +import os +import importlib +import inspect + + +overloads_module = sys.modules[__name__] + +for module_name in os.listdir(os.path.dirname(__file__)): + if module_name == '__init__.py' or module_name[-3:] != '.py': + continue + module = importlib.import_module(f'.{module_name[:-3]}', __name__) + funcs = inspect.getmembers(module, inspect.isfunction) + for name, func in funcs: + setattr(overloads_module, name, func) diff --git a/src/cymple/internal/overloads/case.py b/src/cymple/internal/overloads/case.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c18ed35714b4c8ac88160d5968e99491bd5848 --- /dev/null +++ b/src/cymple/internal/overloads/case.py @@ -0,0 +1,15 @@ +from typing import Dict, List, Union + + +def case(when_then_mapping: Dict[str, Union[List[str], str]], default_result: str, results_ref: str, test_expression: str = None): + ret = " CASE" + if test_expression is not None: + ret += f" {test_expression}" + for then, when in when_then_mapping.items(): + if type(when) is not list: + when = [when] + ret += f" WHEN {', '.join(when)} THEN {then}" + ret += f" ELSE {default_result} END" + if results_ref is not None: + ret += f" AS {results_ref}" + return CaseAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/case_when.py b/src/cymple/internal/overloads/case_when.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f9fcba7b4dac4dede94a0ffa5093969438b181 --- /dev/null +++ b/src/cymple/internal/overloads/case_when.py @@ -0,0 +1,6 @@ + + +def case_when(self, filters: dict, on_true: str, on_false: str, ref_name: str, comparison_operator: str = '"', boolean_operator: str = 'AND', **kwargs): + filt = ' CASE WHEN ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs) + filt += f' THEN {on_true} ELSE {on_false} END AS {ref_name}' + return CaseWhenAvailable(self.query + filt) diff --git a/src/cymple/internal/overloads/delete.py b/src/cymple/internal/overloads/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..2bcee28af7a2409b5505615b1d99907b6e0009c4 --- /dev/null +++ b/src/cymple/internal/overloads/delete.py @@ -0,0 +1,8 @@ +def detach_delete(self, ref_name: str): + ret = f' DETACH DELETE {ref_name}' + return DeleteAvailable(self.query + ret) + + +def delete(self, ref_name: str): + ret = f' DELETE {ref_name}' + return DeleteAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/limit.py b/src/cymple/internal/overloads/limit.py new file mode 100644 index 0000000000000000000000000000000000000000..3a3b8aee6dd71335068990d79fefaa63ae9e8efa --- /dev/null +++ b/src/cymple/internal/overloads/limit.py @@ -0,0 +1,6 @@ +from typing import Union + + +def limit(self, limitation: Union[int, str]): + ret = f" LIMIT {limitation}" + return LimitAvailable(self.query + ret) \ No newline at end of file diff --git a/src/cymple/internal/overloads/match_optional.py b/src/cymple/internal/overloads/match_optional.py new file mode 100644 index 0000000000000000000000000000000000000000..a5de9c18e4b60c46c61fc04ca7dea668bf6fcaeb --- /dev/null +++ b/src/cymple/internal/overloads/match_optional.py @@ -0,0 +1,2 @@ +def match_optional(self): + return MatchAvailable(self.query + ' OPTIONAL MATCH ') diff --git a/src/cymple/internal/overloads/node.py b/src/cymple/internal/overloads/node.py new file mode 100644 index 0000000000000000000000000000000000000000..cfe1036b5153fff82781ae302ac94440e6fc7785 --- /dev/null +++ b/src/cymple/internal/overloads/node.py @@ -0,0 +1,28 @@ + + + +def node(self, labels=None, ref_name: str = None, properties: dict = None, **kwargs): + if not labels: + labels_string = '' + elif isinstance(labels, str): + labels_string = f': {labels}' + else: + labels_string = f': {": ".join(labels).strip()}' + + if not properties: + property_string = '' + else: + property_string = f' {{{Properties(properties).to_str(**kwargs)}}}' + + ref_name = ref_name or '' + + query = self.query + if not (query.endswith('-') or query.endswith('>') or query.endswith('<')): + query += ' ' + + query += f'({ref_name}{labels_string}{property_string})' + + if isinstance(self, MergeAvailable): + return NodeAfterMergeAvailable(query) + + return NodeAvailable(query) diff --git a/src/cymple/internal/overloads/operator_end.py b/src/cymple/internal/overloads/operator_end.py new file mode 100644 index 0000000000000000000000000000000000000000..a0a32427d1aee8fcba83e3da7e06917a1758392f --- /dev/null +++ b/src/cymple/internal/overloads/operator_end.py @@ -0,0 +1,2 @@ +def operator_end(self): + return OperatorEndAvailable(self.query + ' )') diff --git a/src/cymple/internal/overloads/operator_start.py b/src/cymple/internal/overloads/operator_start.py new file mode 100644 index 0000000000000000000000000000000000000000..14714c223a335500492500079242d32aa8551d1b --- /dev/null +++ b/src/cymple/internal/overloads/operator_start.py @@ -0,0 +1,5 @@ +def operator_start(self, operator: str, ref_name: str = None, args: str = None): + result_name = '' if ref_name is None else f'{ref_name} = ' + arguments = '' if args is None else f' {args}' + + return OperatorStartAvailable(self.query + f' {result_name}{operator}({arguments}') diff --git a/src/cymple/internal/overloads/order_by.py b/src/cymple/internal/overloads/order_by.py new file mode 100644 index 0000000000000000000000000000000000000000..28195bedbd3379b08fea6ba0a1f7ca165d8c9213 --- /dev/null +++ b/src/cymple/internal/overloads/order_by.py @@ -0,0 +1,10 @@ + + + +def order_by(sorting_properties, ascending=True): + if type(sorting_properties) != list: + sorting_properties = [sorting_properties] + + ret = f" ORDER BY {', '.join(sorting_properties)}" + ret += " ASC" if ascending else " DESC" + return OrderByAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/procedure.py b/src/cymple/internal/overloads/procedure.py new file mode 100644 index 0000000000000000000000000000000000000000..c479046917bf383bbfe1f9085ff1d9de4dc81650 --- /dev/null +++ b/src/cymple/internal/overloads/procedure.py @@ -0,0 +1,3 @@ +def procedure(self, literal_procedure): + ret = f" {literal_procedure}" + return ProcedureAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/relation.py b/src/cymple/internal/overloads/relation.py new file mode 100644 index 0000000000000000000000000000000000000000..f243c6ab3ed3e9435959f6ea19b92cc25f3e0914 --- /dev/null +++ b/src/cymple/internal/overloads/relation.py @@ -0,0 +1,45 @@ + + + +def related(self, label: str, ref_name: str = None, properties: dict = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + return RelationAvailable(self.query + self._directed_relation('none', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + +def related_to(self, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + return RelationAvailable(self.query + self._directed_relation('forward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + +def related_from(self, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + return RelationAvailable(self.query + self._directed_relation('backward', label, ref_name, properties, min_hops, max_hops, **kwargs)) + + +def _directed_relation(self, direction: str, label: str, ref_name: str = None, properties: str = {}, min_hops: int = 1, max_hops: int = 1, **kwargs): + min_hops_str = '' if min_hops == -1 else str(min_hops) + max_hops_str = '' if max_hops == -1 else str(max_hops) + + relation_type = '' if label is None else f': {label}' + relation_ref_name = '' if ref_name is None else f'{ref_name}' + relation_properties = f' {{{Properties(properties).to_str(**kwargs)}}}' if properties else '' + if min_hops == 1 and max_hops == 1: + relation_length = '' + elif min_hops == -1 and max_hops == -1: + relation_length = '*' + elif min_hops == max_hops: + relation_length = f'*{min_hops_str}' + else: + relation_length = f'*{min_hops_str}..{max_hops_str}' + + if relation_ref_name or relation_type or relation_length or relation_properties: + relation_str = f'[{relation_ref_name}{relation_type}{relation_length}{relation_properties}]' + else: + relation_str = '' + + if direction == 'forward': + return f'-{relation_str}->' + if direction == 'backward': + return f'<-{relation_str}-' + + return f'-{relation_str}-' + + +__all__ = ['related', 'related_to', 'related_from', '_directed_relation'] diff --git a/src/cymple/internal/overloads/remove.py b/src/cymple/internal/overloads/remove.py new file mode 100644 index 0000000000000000000000000000000000000000..43b6f590ab27fcdd6b736d942128466eca5a4203 --- /dev/null +++ b/src/cymple/internal/overloads/remove.py @@ -0,0 +1,6 @@ + +def remove(properties): + if type(properties) != list: + properties = [properties] + ret = f" REMOVE {', '.join(properties)}" + return RemoveAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/returns.py b/src/cymple/internal/overloads/returns.py new file mode 100644 index 0000000000000000000000000000000000000000..5ddb571327cfb5d5697b58db2138c99c7371fa67 --- /dev/null +++ b/src/cymple/internal/overloads/returns.py @@ -0,0 +1,19 @@ + +def return_literal(self, literal): + ret = f' RETURN' + if literal is not None: + ret += f' {literal}' + + return ReturnAvailable(self.query + ret) + + +def return_mapping(self, mappings): + if not isinstance(mappings, list): + mappings = [mappings] + + ret = ' RETURN ' + \ + ', '.join( + f'{mapping[0]} AS {mapping[1]}' if mapping[1] else mapping[0].replace(".", "_") + for mapping in mappings) + + return ReturnAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/set.py b/src/cymple/internal/overloads/set.py new file mode 100644 index 0000000000000000000000000000000000000000..6a874fdc525ef9b96afbf4e28361229eb5c8249a --- /dev/null +++ b/src/cymple/internal/overloads/set.py @@ -0,0 +1,15 @@ +from typing import Union + + +def set(self, properties: Union[str, dict], escape_values: bool = True): + if isinstance(properties, dict): + _properties = Properties(properties).to_str("=", ", ", escape_values) + else: + _properties = str(properties) + + query = self.query + ' SET ' + _properties + + if isinstance(self, NodeAfterMergeAvailable) or isinstance(self, OnCreateAvailable) or isinstance(self, OnMatchAvailable) or isinstance(self, SetAfterMergeAvailable): + return SetAfterMergeAvailable(query) + + return SetAvailable(query) diff --git a/src/cymple/internal/overloads/skip.py b/src/cymple/internal/overloads/skip.py new file mode 100644 index 0000000000000000000000000000000000000000..cce9962435de7809bad83ab5308bd0d69af43a89 --- /dev/null +++ b/src/cymple/internal/overloads/skip.py @@ -0,0 +1,6 @@ +from typing import Union + + +def skip(self, skip_count: Union[int, str]): + ret = f" SKIP {skip_count}" + return SkipAvailable(self.query + ret) diff --git a/src/cymple/internal/overloads/union.py b/src/cymple/internal/overloads/union.py new file mode 100644 index 0000000000000000000000000000000000000000..9fdbaaeb94f16d070da52273b8d660d978b2e62c --- /dev/null +++ b/src/cymple/internal/overloads/union.py @@ -0,0 +1,6 @@ +def union(self): + return UnionAvailable(self.query + f' UNION') + + +def union_all(self): + return UnionAvailable(self.query + f' UNION ALL') \ No newline at end of file diff --git a/src/cymple/internal/overloads/unwind.py b/src/cymple/internal/overloads/unwind.py new file mode 100644 index 0000000000000000000000000000000000000000..e9451b32cc738b0cb3766e8bf89523124f9d3ff1 --- /dev/null +++ b/src/cymple/internal/overloads/unwind.py @@ -0,0 +1,2 @@ +def unwind(self, variables: str): + return UnwindAvailable(self.query + f' UNWIND {variables}') diff --git a/src/cymple/internal/overloads/where.py b/src/cymple/internal/overloads/where.py new file mode 100644 index 0000000000000000000000000000000000000000..59a17d4fd036a8f9dbad5f4529779ee5d08a6dda --- /dev/null +++ b/src/cymple/internal/overloads/where.py @@ -0,0 +1,14 @@ +from typing import Any + + + +def where_literal(self, statement: str, **kwargs): + filt = ' WHERE ' + statement + return WhereAvailable(self.query + filt) + +def where_multiple(self, filters: dict, comparison_operator: str = '=', boolean_operator: str = ' AND ', **kwargs): + filt = ' WHERE ' + Properties(filters).to_str(comparison_operator, boolean_operator, **kwargs) + return WhereAvailable(self.query + filt) + +def where(self, name: str, comparison_operator: str, value: Any, **kwargs): + return self.where_multiple({name: value}, comparison_operator, **kwargs) diff --git a/src/cymple/internal/overloads/with_.py b/src/cymple/internal/overloads/with_.py new file mode 100644 index 0000000000000000000000000000000000000000..b9d542131a22286945a609f99061f185d78e5552 --- /dev/null +++ b/src/cymple/internal/overloads/with_.py @@ -0,0 +1,2 @@ +def with_(self, variables: str): + return WithAvailable(self.query + f' WITH {variables}') diff --git a/src/cymple/internal/overloads/yield_.py b/src/cymple/internal/overloads/yield_.py new file mode 100644 index 0000000000000000000000000000000000000000..3c7e9cd5f062ad003a59d85af04d365b512fe00b --- /dev/null +++ b/src/cymple/internal/overloads/yield_.py @@ -0,0 +1,9 @@ +def yield_(self, mappings): + if not isinstance(mappings, list): + mappings = [mappings] + + query = ' YIELD ' + \ + ', '.join(f'{mapping[0]} AS ' + f'{mapping[1] if mapping[1] else mapping[0].replace(".", "_")}' + for mapping in mappings) + return YieldAvailable(self.query + query) diff --git a/src/cymple/internal/preface.py b/src/cymple/internal/preface.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea35b0011a922bb1ff66daf675908252359e6aa --- /dev/null +++ b/src/cymple/internal/preface.py @@ -0,0 +1,27 @@ +class Query(): + """A general query-descripting class .""" + + def __init__(self, query): + """Initialize the query object.""" + self.query = query + + def __str__(self) -> str: + """Implement the str() operator for the query builder.""" + return self.query.strip() + + def __add__(self, other): + """Implement the + operator for the query builder.""" + return Query(self.query.strip() + ' ' + other.query.strip()) + + def __iadd__(self, other): + """Implement the += operator for the query builder.""" + self.query = self.query.strip() + ' ' + other.query.strip() + return self + + def get(self): + """Get the final query string .""" + return str(self) + + def cypher(self, cypher_query_str): + """Concatenate a cypher query string""" + return AnyAvailable(self.query.strip() + ' ' + cypher_query_str.strip()) diff --git a/src/cymple/typedefs.py b/src/cymple/typedefs.py new file mode 100644 index 0000000000000000000000000000000000000000..59de7882df3abf2f158672221abf324e72f79b7e --- /dev/null +++ b/src/cymple/typedefs.py @@ -0,0 +1,36 @@ +"""Cymple's API type definitions.""" +from collections import namedtuple +from typing import Any, List +from dataclasses import dataclass + +Mapping = namedtuple('Mapping', ['ref_name', 'returned_name'], defaults=(None, None)) + + +class Properties(dict): + """A dict class storing a set of properties.""" + + @staticmethod + def _escape(string: str) -> str: + res = string.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'").replace('\r', '\\r').replace('\n', '\\n') + return res + + @staticmethod + def _format_value(value: Any, escape: bool) -> Any: + # Assigning a dict to a property is not supported by a neo4j graph + # if isinstance(value, dict): + # return str({sub_key: self._format_value(sub_value) for sub_key, sub_value in value.items()}) + if escape and isinstance(value, str): + return f'"{Properties._escape(value)}"' + if value is None: + return 'null' + + return value + + def to_str(self, comparison_operator: str = ':', boolean_operator: str = ', ', escape: bool = True) -> str: + """Convert this Properties dicionarty to a serialied string suitable for a cypher query""" + pairs = [f'{key} {comparison_operator} {Properties._format_value(value, escape)}' for key, value in self.items()] + res = boolean_operator.join(pairs) + return res + + def __str__(self) -> str: + return self.to_str() diff --git a/src/cymple/version.py b/src/cymple/version.py new file mode 100644 index 0000000000000000000000000000000000000000..37d4ad1eab1228e9fb2ae00295b40601eb52751c --- /dev/null +++ b/src/cymple/version.py @@ -0,0 +1,3 @@ +"""Version information for Cymple""" + +__version__: str = "0.12.0" diff --git a/src/samples/basic.py b/src/samples/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d233d5ef32312339b4567fb895523c6fe670770d --- /dev/null +++ b/src/samples/basic.py @@ -0,0 +1,95 @@ + +from typing import Any, Dict, List, Union +from cymple.builder import QueryBuilder + + + +def get_all_nodes_by_label(labels: Union[List[str], str], node_name: str = 'n'): + return (QueryBuilder() + .match() + .node(labels=labels, ref_name=node_name) + .return_literal(literal=node_name) + ) + + +def get_all_nodes_by_label_and_properties(labels: Union[List[str], str], properties: Dict[str, Any], node_name: str = 'n'): + return (QueryBuilder() + .match() + .node(labels=labels, ref_name=node_name, properties=properties) + .return_literal(literal=node_name) + ) + + +def get_all_paths(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], relationship_type: str, path_name: str = 'p'): + return (QueryBuilder() + .match() + .operator_start(operator='', ref_name=path_name) + .node(labels=src_node_labels) + .related(label=relationship_type) + .node(labels=dst_node_labels) + .operator_end() + .return_literal(literal=path_name) + ) + + +def get_all_nodes_related_to_nodes(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], relationship_type: str, dst_node_name: str = 'd'): + return (QueryBuilder() + .match() + .node(labels=src_node_labels) + .related(label=relationship_type) + .node(labels=dst_node_labels, ref_name=dst_node_name) + .return_literal(literal=dst_node_name) + ) + + +def get_all_nodes_related_by_fixed_num_of_hops(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], num_hops: int, dst_node_name: str = 'd'): + return (QueryBuilder() + .match() + .node(labels=src_node_labels) + .related(min_hops=num_hops, max_hops=num_hops) + .node(labels=dst_node_labels, ref_name=dst_node_name) + .return_literal(literal=dst_node_name) + ) + + +def get_all_nodes_related_by_varying_num_of_hops(src_node_labels: Union[List[str], str], dst_node_labels: Union[List[str], str], min_hops: int, max_hops: int, dst_node_name: str = 'd'): + return (QueryBuilder() + .match() + .node(labels=src_node_labels) + .related(min_hops=min_hops, max_hops=max_hops) + .node(labels=dst_node_labels, ref_name=dst_node_name) + .return_literal(literal=dst_node_name) + ) + + +def get_nodes_with_pagination(node_labels: Union[List[str], str], node_name: str = 'n', offset: int = 0, limit: int = -1): + raise NotImplementedError() + + +def create_node(node_labels: Union[List[str], str]): + raise NotImplementedError() + + +def merge_node(node_labels: Union[List[str], str], properties: Dict[str, Any] = None): + return (QueryBuilder() + .merge() + .node(labels=node_labels, properties=properties) + ) + + +def create_relationship(relationship_type: str): + raise NotImplementedError() + + +def merge_relationship(relationship_type: str, properties: Dict[str, Any] = None, src_node_labels: Union[List[str], str] = None, + dst_node_labels: Union[List[str], str] = None, src_node_properties: Dict[str, Any] = None, dst_node_properties: Dict[str, Any] = None): + return (QueryBuilder() + .match() + .node(labels=src_node_labels, properties=src_node_properties, ref_name='src') + .match() + .node(labels=dst_node_labels, properties=dst_node_properties, ref_name='dst') + .merge() + .node(ref_name='src') + .related_to(label=relationship_type, properties=properties) + .node(ref_name='dst') + ) diff --git a/src/samples/neo4j_config.py b/src/samples/neo4j_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdffd3a32ebdf8d5feeed3687429d7bbbc78e3b --- /dev/null +++ b/src/samples/neo4j_config.py @@ -0,0 +1,2 @@ +uri = 'bolt://127.0.0.1:7687' +db_name = 'neo4j' \ No newline at end of file diff --git a/src/samples/neo4j_e2e.py b/src/samples/neo4j_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..16444a4f176c86c6d9b9f84525d8f5c3d1873ae8 --- /dev/null +++ b/src/samples/neo4j_e2e.py @@ -0,0 +1,45 @@ +from cymple import QueryBuilder +from samples.neo4j_helper import Neo4jDbSession, Neo4jQueryHelper +from samples.neo4j_config import uri as neo4j_uri, db_name as neo4j_db + +helper: Neo4jQueryHelper +builder: QueryBuilder + +label = 'Movie' +property = 'name' +reference = 'node' + + +def init(neo4j_user, neo4j_password): + """Init this module by creating a session to the (neo4j) DB, creating a helper for running queries and a query builder""" + from neo4j import GraphDatabase + + global helper + global builder + + driver = GraphDatabase.driver(neo4j_uri, auth=(neo4j_user, neo4j_password)) + session = Neo4jDbSession(driver=driver, db_name=neo4j_db) + helper = Neo4jQueryHelper(session) + builder = QueryBuilder() + + +def read_movie_node(movie_name: str): + """Create a query for reading a node labeled 'Movie', with name given in movie_name""" + builder.reset() + query = str(builder + .match() + .node(labels=label, ref_name=reference, properties={property: movie_name}) + .return_mapping((f'{reference}.{property}', property))) + results = helper.read(query) + return results[0].get(property) if results else None + + +def write_movie_node(movie_name: str): + """Create a query for creating a node labeled 'Movie', with name given in movie_name""" + builder.reset() + query = str(builder + .merge() + .node(labels=label, ref_name=reference, properties={property: movie_name}) + .return_mapping((f'{reference}.{property}', property))) + results = helper.write(query) + return results[0].get(property) if results else None diff --git a/src/samples/neo4j_helper.py b/src/samples/neo4j_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..967d4818a741404b915ec3fd4d77278423cba2f6 --- /dev/null +++ b/src/samples/neo4j_helper.py @@ -0,0 +1,93 @@ +from typing import Callable, Dict, List +import logging + +logging.basicConfig(level=logging.INFO) + + +class Neo4jDbSession: + """Context manager for a neo4j DB session.""" + + def __init__(self, driver, db_name: str): + self._db_name = db_name + self._driver = driver + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self) -> None: + """Close the driver .""" + self._driver.close() + + def read_transaction(self, transaction_function: Callable, query: str, parameters: Dict = None) -> List[Dict]: + """Perform a Read transaction on the database. + + Args: + transaction_function (Callable): a function to be executed as a transaction on the DB + query (str): The actual query to be run + parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None. + + Returns: + List[Dict]: A list of dictionary-represented objects as obtained by running the transaction + """ + with self._driver.session(database=self._db_name) as session: + return session.read_transaction(transaction_function, query=query, parameters=parameters) + + def write_transaction(self, transaction_function: Callable, query: str, parameters: Dict = None) -> List[Dict]: + """Perform a Write transaction on the database . + + Args: + transaction_function (Callable): a function to be executed as a transaction on the DB + query (str): The actual query to be run + parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None. + + Returns: + List[Dict]: A list of dictionary-represented objects as obtained by running the transaction + """ + with self._driver.session(database=self._db_name) as session: + return session.write_transaction(transaction_function, query=query, parameters=parameters) + + +class Neo4jQueryHelper(): + """A helper class for running (Cypher) queries on a neo4j DB.""" + + @staticmethod + def run_query(t_x, query, parameters=None) -> List[Dict]: + """Transaction function to run a query against the database. + + Returns: + List[Dict]: A list of dictionary-represented objects as obtained by running the query + """ + res = t_x.run(query, parameters=parameters) + return res.data() + + def __init__(self, session: Neo4jDbSession) -> None: + self.dbs = session + + def read(self, query: str, parameters: Dict = None) -> List[Dict]: + """Run the given query against the database and returns the result as a Read operation. + + Args: + query (str): a Cypher query to be run + parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None. + + Returns: + List[Dict]: A list of dictionary-represented objects as obtained by running the query + """ + logging.info('In %s, executing query: %s', self.read.__name__, query) + return self.dbs.read_transaction(self.run_query, query, parameters) + + def write(self, query: str, parameters: Dict = None) -> List[Dict]: + """Run the given query against the database and returns the result as a Write operation. + + Args: + query (str): a Cypher query to be run + parameters (Dict, optional): Additional parameters to be used to run the query. Defaults to None. + + Returns: + List[Dict]: A list of dictionary-represented objects as obtained by running the query + """ + logging.info('In %s, executing query: %s', self.write.__name__, query) + return self.dbs.write_transaction(self.run_query, query, parameters) diff --git a/src/samples/version.py b/src/samples/version.py new file mode 100644 index 0000000000000000000000000000000000000000..bf14c7cf1dc349fc7a36304714844812d6466d39 --- /dev/null +++ b/src/samples/version.py @@ -0,0 +1,3 @@ +"""Version information for Cymple""" + +__version__: str = "0.4.2" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c23018f5eacfda9fe079202d30b4b95072509d2f --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Test suite for the cymple package.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa525725e33cbda3fe20dac6bda84b8de8b2404 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,22 @@ +from pytest import fixture + + +def pytest_addoption(parser): + try: + parser.addoption('--e2e', action='store_true', default=False) + parser.addoption('--neo4j_user', action='store', default=None) + parser.addoption('--neo4j_password', action='store', default=None) + except Exception as ex: + print(ex) + +@fixture(scope='session') +def is_run_e2e(pytestconfig) -> bool: + return pytestconfig.getoption('e2e') + +@fixture(scope='session') +def neo4j_user(pytestconfig) -> bool: + return pytestconfig.getoption('neo4j_user') + +@fixture(scope='session') +def neo4j_password(pytestconfig) -> bool: + return pytestconfig.getoption('neo4j_password') diff --git a/tests/data/.gitkeep b/tests/data/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/data/onto_types/labels.py b/tests/data/onto_types/labels.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf4939d7dc94e53d9877a43a51dcb2e02c80140 --- /dev/null +++ b/tests/data/onto_types/labels.py @@ -0,0 +1,14 @@ +from dataclasses import dataclass + + +@dataclass +class Labels: + Application: str = "Application" + CVEType: str = "CVEType" + CloudObject: str = "CloudObject" + Finding: str = "Finding" + FindingScan: str = "FindingScan" + FindingSourceType: str = "FindingSourceType" + FindingType: str = "FindingType" + ReferenceType: str = "ReferenceType" + ServiceType: str = "ServiceType" diff --git a/tests/data/onto_types/properties.py b/tests/data/onto_types/properties.py new file mode 100644 index 0000000000000000000000000000000000000000..deb0284d4cfe55099324664dd15ace67dbdd9256 --- /dev/null +++ b/tests/data/onto_types/properties.py @@ -0,0 +1,11 @@ +from dataclasses import dataclass + + +@dataclass +class Properties: + has_id: str = "has_id" + has_name: str = "has_name" + has_probability: str = "has_probability" + has_severity: str = "has_severity" + has_description: str = "has_description" + has_attack_scenario: str = "has_attack_scenario" diff --git a/tests/data/onto_types/relations.py b/tests/data/onto_types/relations.py new file mode 100644 index 0000000000000000000000000000000000000000..7a1fad5e6e83ebac7a1c3827566b981198f9af21 --- /dev/null +++ b/tests/data/onto_types/relations.py @@ -0,0 +1,12 @@ +from dataclasses import dataclass + + +@dataclass +class Relations: + has_cloud_object: str = "has_cloud_object" + has_service: str = "has_service" + has_finding_type: str = "has_finding_type" + has_diagnosed_cloud_object: str = "has_diagnosed_cloud_object" + has_finding: str = "has_finding" + has_cve: str = "has_cve" + has_reference: str = "has_reference" diff --git a/tests/e2e/.gitkeep b/tests/e2e/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/e2e/test_e2e_samples.py b/tests/e2e/test_e2e_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..c1eec7469dbe8213f9b2074fca5de00325022771 --- /dev/null +++ b/tests/e2e/test_e2e_samples.py @@ -0,0 +1,13 @@ +import pytest +from samples import neo4j_e2e + + +def test_neo4j_sample(is_run_e2e, neo4j_user, neo4j_password): + if not is_run_e2e: + pytest.skip('Use "pytest --e2e --neo4j_user --neo4j_password " to run this!') + + movie_name = 'The Matrix' + + neo4j_e2e.init(neo4j_user=neo4j_user, neo4j_password=neo4j_password) + assert neo4j_e2e.write_movie_node(movie_name) == movie_name + assert neo4j_e2e.read_movie_node(movie_name) == movie_name diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/functional/test_functionality.py b/tests/functional/test_functionality.py new file mode 100644 index 0000000000000000000000000000000000000000..421b4cd526c84fd9b6c6c066979d604e535b8d61 --- /dev/null +++ b/tests/functional/test_functionality.py @@ -0,0 +1,25 @@ +import inspect +import pytest +from cymple import QueryBuilder, builder + +any_available_clauses = [ + ("cypher", {"cypher_query_str": ""}) +] + + +@pytest.mark.parametrize("clause, params", any_available_clauses) +def test_any_available(clause, params): + qb = QueryBuilder() + callables = [_callable for _callable in dir(getattr(qb.match(), clause)(*params)) + if not _callable.startswith("__")] + builder_classes = [_class for _class in inspect.getmembers( + builder, + lambda member: inspect.isclass(member) and member.__module__ == builder.__name__ + ) if not _class[0].lower().endswith("available") and _class[0].lower() != "querybuilder"] + + missing_callables = set() + for _class in builder_classes: + missing_callables.update([ + func for func in dir(_class[1]) if not func.startswith("__") and func not in callables + ]) + assert not missing_callables diff --git a/tests/integration/.gitkeep b/tests/integration/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/unit/test_clauses.py b/tests/unit/test_clauses.py new file mode 100644 index 0000000000000000000000000000000000000000..4dcca16b72ff9f8326614e657013d401a9ff7108 --- /dev/null +++ b/tests/unit/test_clauses.py @@ -0,0 +1,141 @@ +import pytest +from cymple import QueryBuilder + +qb = QueryBuilder() + +rendered = { + '_RESET_': qb.reset(), + 'CALL': qb.reset().call().procedure("db.labels()"), + 'CASE WHEN': qb.reset().match().node(ref_name='n').with_('n').case_when({'n.name': 'Bob'}, 'true', 'false', 'my_boolean'), + 'DELETE': qb.reset().match().node(ref_name='n').delete('n'), + 'DETACH DELETE': qb.reset().match().node(ref_name='n').detach_delete('n'), + 'WHERE (single)': qb.reset().match().node(ref_name='n').where('n.name', '=', 'value'), + 'WHERE (multiple)': qb.reset().match().node(ref_name='n').where_multiple({'n.name': 'value', 'n.age': 20}), + 'WHERE (literal)': qb.reset().match().node(ref_name='n').where_literal('NOT exists(n)'), + 'MATCH': qb.reset().match(), + 'MATCH OPTIONAL': qb.reset().match_optional(), + 'MERGE': qb.reset().merge(), + 'NODE': qb.reset().match().node(['label1', 'label2'], 'node', {'name': 'Bob'}), + 'NODE MERGE': qb.reset().merge().node(labels=['label1', 'label2'], ref_name='n', properties={'name': 'Bob'}).related_to().node(ref_name='m'), + 'NODE (not escaping)': qb.reset().match().node(['label1', 'label2'], 'node', {'name': 'Bob'}, escape=False), + 'OPERATOR': qb.reset().match().operator_start('SHORTESTPATH', 'p', '(:A)-[*]-(:B)').operator_end(), + 'RELATION (forward)': qb.reset().match().node().related_to().node(), + 'RELATION (backward)': qb.reset().match().node().related_from().node(), + 'RELATION (unidirectional)': qb.reset().match().node().related().node(), + 'RELATION (variable length)': qb.reset().match().node().related(min_hops=1, max_hops=2).node(), + 'RELATION (variable length, empty)': qb.reset().match().node().related(min_hops=-1, max_hops=-1).node(), + 'RELATION (variable length, with label)': qb.reset().match().node().related(label='Relation', ref_name='rel', min_hops=1, max_hops=2).node(), + 'RETURN (literal)': qb.reset().match().node(ref_name='n').return_literal('n'), + 'RETURN (mapping)': qb.reset().match().node(ref_name='n').return_mapping(('n.name', 'name')), + 'RETURN (mapping, list)': qb.reset().match().node(ref_name='n').return_mapping([('n.name', 'name'), ('n.age', 'age')]), + 'SET': qb.reset().merge().node(ref_name='n').set({'n.name': 'Alice'}), + 'SET (not escaping)': qb.reset().merge().node(ref_name='n').set({'n.name': 'n.name + "!"'}, escape_values=False), + 'SET (string)': qb.reset().merge().node(ref_name='n').set('n.name = n.name + "!"'), + 'ON CREATE': qb.reset().merge().node(ref_name='n').on_create().set({'n.name': 'Bob'}), + 'ON MATCH': qb.reset().merge().node(ref_name='n').on_match().set({'n.name': 'Bob'}), + 'ON CREATE ON MATCH': qb.reset().merge().node(ref_name='n').on_create().set({'n.name': 'Bob'}).on_match().set({'n.name': 'Alice'}), + 'ON MATCH ON CREATE': qb.reset().merge().node(ref_name='n').on_match().set({'n.name': 'Bob'}).on_create().set({'n.name': 'Alice'}), + 'UNWIND': qb.reset().match().node(ref_name='n').with_('n').unwind('n'), + 'WITH': qb.reset().match().node(ref_name='a').with_('a,b'), + 'WITH (start)': qb.reset().with_('a').match().node(ref_name='a').with_('a,b'), + 'YIELD': qb.reset().call().procedure("db.labels()").yield_(("label", "label")).where("label", "CONTAINS", "User").return_literal("count(label) AS numLabels"), + 'YIELD (list)': qb.reset().call().procedure("db.labels()").yield_([('length(labels)', 'len'), ('count(label)', 'cnt')]), + 'LIMIT': qb.reset().match().node(ref_name='n').return_literal('n').limit(1), + 'LIMIT (expression)': qb.reset().match().node(ref_name='n').return_literal('n').limit("1 + toInteger(3 * rand())"), + 'LIMIT (with)': qb.reset().match().node(ref_name='n').with_('n').limit(1), + 'LIMIT (with set)': qb.reset().match().node(ref_name='n').with_('n').limit(1).set({'n.name': 'Bob'}), + 'CYPHER': qb.reset().match().node(ref_name='n').cypher("my cypher").limit(1), + 'SKIP': qb.reset().match().node(ref_name='n').return_literal('n').skip(1), + 'SKIP (expression)': qb.reset().match().node(ref_name='n').return_literal('n').skip("1 + toInteger(3 * rand())"), + 'SKIP (with)': qb.reset().match().node(ref_name='n').with_('n').skip(1), + 'SKIP (with set)': qb.reset().match().node(ref_name='n').with_('n').skip(1).set({'n.name': 'Bob'}), + 'ORDER BY': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by("elementId(n)"), + 'ORDER BY (List)': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by( + ["n.name", "keys(n)"]), + 'ORDER BY (Desc)': qb.match().node(ref_name='n').return_literal('n.name, n.age').order_by("n.name", False), + 'CREATE': qb.reset().create().node(ref_name='n').return_literal('n'), + 'REMOVE': qb.reset().match().node(ref_name='n').remove('n.name').return_literal('n.age, n.name'), + 'REMOVE (list)': qb.reset().match().node(ref_name='n').remove(['n.age', 'n.name']).return_literal('n.age, n.name'), + 'UNION': qb.match().node(ref_name='n', labels="Actor").return_mapping([('n.name', 'name')]).union().match().node( + ref_name='n', labels="Movie").return_mapping([('n.title', 'name')]), + 'UNION (all)': qb.match().node(ref_name='n', labels="Actor").return_mapping( + [('n.name', 'name')]).union_all().match().node(ref_name='n', labels="Movie").return_mapping([('n.title', 'name')]), + 'CASE (simple)': qb.match().node(ref_name="n", labels="Person").return_literal().case(when_then_mapping={"1": "'blue'", "2": ["'brown'", "'hazel'"]}, default_result="3", results_ref="result, n.eyes", test_expression="n.eyes"), + 'CASE (simple extended)': qb.match().node(ref_name="n", labels="Person").return_literal("n.name,").case(when_then_mapping={"'Unknown'": ["IS NULL", "IS NOT TYPED INTEGER | FLOAT"], "'Baby'": ["= 0", "= 1", "= 2"], "'Child'": "<= 13", "'Teenager'": "< 20", "'Young Adult'": "< 30", "'Immortal'": "> 1000"}, default_result="'Adult'", test_expression="n.age", results_ref="result"), + 'CASE (generic)': qb.match().node(ref_name="n", labels="Person").return_literal().case(when_then_mapping={"1": "n.eyes = 'blue'", "2": "n.age < 40"}, default_result="3", results_ref="result, n.eyes, n.age"), + 'CASE (null values)': qb.match().node(ref_name="n", labels="Person").return_literal("n.name,").case(when_then_mapping={"-1": "n.age IS NULL"}, default_result="n.age - 10", results_ref="age_10_years_ago"), + 'CASE (with set)': qb.match().node(ref_name="n", labels="Person").with_("n,").case(when_then_mapping={"1": "'blue'", "2": "'brown'"}, default_result="3", results_ref="colorCode", test_expression="n.eyes").set({"n.colorCode": "colorCode"}, escape_values=False).return_literal("n.name, n.colorCode") +} + +expected = { + '_RESET_': '', + 'CALL': 'CALL db.labels()', + 'CASE WHEN': 'MATCH (n) WITH n CASE WHEN n.name = "Bob" THEN true ELSE false END AS my_boolean', + 'DELETE': 'MATCH (n) DELETE n', + 'DETACH DELETE': 'MATCH (n) DETACH DELETE n', + 'WHERE (single)': 'MATCH (n) WHERE n.name = "value"', + 'WHERE (multiple)': 'MATCH (n) WHERE n.name = "value" AND n.age = 20', + 'WHERE (literal)': 'MATCH (n) WHERE NOT exists(n)', + 'MATCH': 'MATCH', + 'MATCH OPTIONAL': 'OPTIONAL MATCH', + 'MERGE': 'MERGE', + 'NODE': 'MATCH (node: label1: label2 {name : "Bob"})', + 'NODE MERGE': 'MERGE (n: label1: label2 {name : "Bob"})-->(m)', + 'NODE (not escaping)': 'MATCH (node: label1: label2 {name : Bob})', + 'OPERATOR': 'MATCH p = SHORTESTPATH( (:A)-[*]-(:B) )', + 'RELATION (forward)': 'MATCH ()-->()', + 'RELATION (backward)': 'MATCH ()<--()', + 'RELATION (unidirectional)': 'MATCH ()--()', + 'RELATION (variable length)': 'MATCH ()-[*1..2]-()', + 'RELATION (variable length, empty)': 'MATCH ()-[*]-()', + 'RELATION (variable length, with label)': 'MATCH ()-[rel: Relation*1..2]-()', + 'RETURN (literal)': 'MATCH (n) RETURN n', + 'RETURN (mapping)': 'MATCH (n) RETURN n.name AS name', + 'RETURN (mapping, list)': 'MATCH (n) RETURN n.name AS name, n.age AS age', + 'SET': 'MERGE (n) SET n.name = "Alice"', + 'SET (not escaping)': 'MERGE (n) SET n.name = n.name + "!"', + 'SET (string)': 'MERGE (n) SET n.name = n.name + "!"', + 'ON CREATE': 'MERGE (n) ON CREATE SET n.name = "Bob"', + 'ON MATCH': 'MERGE (n) ON MATCH SET n.name = "Bob"', + 'ON CREATE ON MATCH': 'MERGE (n) ON CREATE SET n.name = "Bob" ON MATCH SET n.name = "Alice"', + 'ON MATCH ON CREATE': 'MERGE (n) ON MATCH SET n.name = "Bob" ON CREATE SET n.name = "Alice"', + 'UNWIND': 'MATCH (n) WITH n UNWIND n', + 'WITH': 'MATCH (a) WITH a,b', + 'WITH (start)': 'WITH a MATCH (a) WITH a,b', + 'YIELD': 'CALL db.labels() YIELD label AS label WHERE label CONTAINS "User" RETURN count(label) AS numLabels', + 'YIELD (list)': 'CALL db.labels() YIELD length(labels) AS len, count(label) AS cnt', + 'LIMIT': 'MATCH (n) RETURN n LIMIT 1', + 'LIMIT (expression)': 'MATCH (n) RETURN n LIMIT 1 + toInteger(3 * rand())', + 'LIMIT (with)': 'MATCH (n) WITH n LIMIT 1', + 'LIMIT (with set)': 'MATCH (n) WITH n LIMIT 1 SET n.name = "Bob"', + 'CYPHER': 'MATCH (n) my cypher LIMIT 1', + 'SKIP': 'MATCH (n) RETURN n SKIP 1', + 'SKIP (expression)': 'MATCH (n) RETURN n SKIP 1 + toInteger(3 * rand())', + 'SKIP (with)': 'MATCH (n) WITH n SKIP 1', + 'SKIP (with set)': 'MATCH (n) WITH n SKIP 1 SET n.name = "Bob"', + 'ORDER BY': 'MATCH (n) RETURN n.name, n.age ORDER BY elementId(n) ASC', + 'ORDER BY (List)': 'MATCH (n) RETURN n.name, n.age ORDER BY n.name, keys(n) ASC', + 'ORDER BY (Desc)': 'MATCH (n) RETURN n.name, n.age ORDER BY n.name DESC', + 'CREATE': 'CREATE (n) RETURN n', + 'REMOVE': 'MATCH (n) REMOVE n.name RETURN n.age, n.name', + 'REMOVE (list)': 'MATCH (n) REMOVE n.age, n.name RETURN n.age, n.name', + 'UNION': 'MATCH (n: Actor) RETURN n.name AS name UNION MATCH (n: Movie) RETURN n.title AS name', + 'UNION (all)': 'MATCH (n: Actor) RETURN n.name AS name UNION ALL MATCH (n: Movie) RETURN n.title AS name', + 'CASE (simple)': "MATCH (n: Person) RETURN CASE n.eyes WHEN 'blue' THEN 1 WHEN 'brown', 'hazel' THEN 2 ELSE 3 END" + " AS result, n.eyes", + 'CASE (simple extended)': "MATCH (n: Person) RETURN n.name, CASE n.age WHEN IS NULL, IS NOT TYPED INTEGER | FLOAT" + " THEN 'Unknown' WHEN = 0, = 1, = 2 THEN 'Baby' WHEN <= 13 THEN 'Child' WHEN < 20 THEN" + " 'Teenager' WHEN < 30 THEN 'Young Adult' WHEN > 1000 THEN 'Immortal' ELSE 'Adult' END" + " AS result", + 'CASE (generic)': "MATCH (n: Person) RETURN CASE WHEN n.eyes = 'blue' THEN 1 WHEN n.age < 40 THEN 2 ELSE 3 END" + " AS result, n.eyes, n.age", + 'CASE (null values)': "MATCH (n: Person) RETURN n.name, CASE WHEN n.age IS NULL THEN -1 ELSE n.age - 10 END" + " AS age_10_years_ago", + 'CASE (with set)': "MATCH (n: Person) WITH n, CASE n.eyes WHEN 'blue' THEN 1 WHEN 'brown' THEN 2 ELSE 3 END " + "AS colorCode SET n.colorCode = colorCode RETURN n.name, n.colorCode" +} + + +@pytest.mark.parametrize('clause', expected) +def test_case(clause: str): + assert str(rendered[clause]) == expected[clause] diff --git a/tests/unit/test_generated.py b/tests/unit/test_generated.py new file mode 100644 index 0000000000000000000000000000000000000000..32668045c03288c52df11468b4dcae513a44de50 --- /dev/null +++ b/tests/unit/test_generated.py @@ -0,0 +1,33 @@ +import pytest +from cymple import QueryBuilder + +qb = QueryBuilder() + +rendered = { + 'CASE_1': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE p.age WHEN 18 THEN "Young Adult" WHEN 65 THEN "Senior" ELSE "Adult" END', 'ageCategory')]), + 'CASE_2': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END', 'ageGroup')]), + 'CASE_3': qb.reset().match().node(ref_name='p', labels='Person').set({'p.category': 'CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END'}, escape_values=False).return_literal('p'), + 'CASE_4': qb.reset().match().node(ref_name='p', labels='Person').with_('p,').case(when_then_mapping={"\"America\"": "\"US\"", "\"North America\"": "\"Canada\""}, default_result="\"Other\"", results_ref='region', test_expression='p.country').return_literal('p.name, region'), + 'CASE_5': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('CASE WHEN p.age < 18 THEN CASE p.age WHEN 0 THEN "Newborn" ELSE "Child" END WHEN p.age < 65 THEN "Adult" ELSE "Senior" END', 'lifeStage')]), + 'CASE_6': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('COUNT(CASE WHEN p.age < 18 THEN 1 END)', 'minors'), ('COUNT(CASE WHEN p.age >= 18 AND p.age < 65 THEN 1 END)', 'adults'), ('COUNT(CASE WHEN p.age >= 65 THEN 1 END)', 'seniors')]), + 'CASE_7': qb.reset().match().node(ref_name='p', labels='Person').where_literal('CASE WHEN p.age < 18 THEN false ELSE true END').return_literal('p'), + 'CASE_8': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('p.age', 'age')]).order_by('CASE WHEN p.age < 18 THEN 1 WHEN p.age >= 18 AND p.age < 65 THEN 2 ELSE 3 END'), + 'CASE_9': qb.reset().match().node(ref_name='p', labels='Person').return_mapping([('p.name', 'name'), ('p.age', 'age'), ('CASE WHEN p.age < 18 THEN "Young " + p.name WHEN p.age >= 65 THEN "Senior " + p.name ELSE "Adult " + p.name END', 'titledName')]) +} + +expected = { + 'CASE_1': 'MATCH (p: Person) RETURN p.name AS name, CASE p.age WHEN 18 THEN "Young Adult" WHEN 65 THEN "Senior" ELSE "Adult" END AS ageCategory', + 'CASE_2': 'MATCH (p: Person) RETURN p.name AS name, CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END AS ageGroup', + 'CASE_3': 'MATCH (p: Person) SET p.category = CASE WHEN p.age < 18 THEN "Minor" WHEN p.age >= 18 AND p.age < 65 THEN "Adult" ELSE "Senior" END RETURN p', + 'CASE_4': 'MATCH (p: Person) WITH p, CASE p.country WHEN "US" THEN "America" WHEN "Canada" THEN "North America" ELSE "Other" END AS region RETURN p.name, region', + 'CASE_5': 'MATCH (p: Person) RETURN p.name AS name, CASE WHEN p.age < 18 THEN CASE p.age WHEN 0 THEN "Newborn" ELSE "Child" END WHEN p.age < 65 THEN "Adult" ELSE "Senior" END AS lifeStage', + 'CASE_6': 'MATCH (p: Person) RETURN COUNT(CASE WHEN p.age < 18 THEN 1 END) AS minors, COUNT(CASE WHEN p.age >= 18 AND p.age < 65 THEN 1 END) AS adults, COUNT(CASE WHEN p.age >= 65 THEN 1 END) AS seniors', + 'CASE_7': 'MATCH (p: Person) WHERE CASE WHEN p.age < 18 THEN false ELSE true END RETURN p', + 'CASE_8': 'MATCH (p: Person) RETURN p.name AS name, p.age AS age ORDER BY CASE WHEN p.age < 18 THEN 1 WHEN p.age >= 18 AND p.age < 65 THEN 2 ELSE 3 END ASC', + 'CASE_9': 'MATCH (p: Person) RETURN p.name AS name, p.age AS age, CASE WHEN p.age < 18 THEN "Young " + p.name WHEN p.age >= 65 THEN "Senior " + p.name ELSE "Adult " + p.name END AS titledName' +} + + +@pytest.mark.parametrize('clause', expected) +def test_samples(clause: str): + assert str(rendered[clause]) == expected[clause] diff --git a/tests/unit/test_real_use_cases.py b/tests/unit/test_real_use_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..3b51db4f0f273b7bb23d8b8c81eaa4f1be17ade8 --- /dev/null +++ b/tests/unit/test_real_use_cases.py @@ -0,0 +1,396 @@ +from cymple import QueryBuilder + +from ..data.onto_types.labels import Labels +from ..data.onto_types.properties import Properties +from ..data.onto_types.relations import Relations + + +def cypher_get_all_findings(): + output_mapping = [('n', 'n')] + query = QueryBuilder().match().node(Labels.Finding, 'n').return_mapping(output_mapping).get() + return query + + +def cypher_get_findings(): + output_mapping = [(f'f.{Properties.has_id}', 'id'), + (f't.{Properties.has_probability}', 'probability'), + (f't.{Properties.has_severity}', 'severity'), + (f'ct.{Properties.has_id}', 'cve')] + + query = (QueryBuilder().match() + .node(Labels.Finding, 'f') + .related_to(Relations.has_finding_type) + .node(Labels.FindingType, 't') + .related_to(Relations.has_cve) + .node(Labels.CVEType, 'ct') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_services(): + output_mapping = [(f's.{Properties.has_id}', 'id'), + (f's.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.ServiceType, 's') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_identities(): + output_mapping = [(f'i.{Properties.has_id}', 'id'), + (f'i.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.Identity, 'i') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_business_applications(): + output_mapping = [(f'a.{Properties.has_id}', 'id'), + (f'a.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.Application, 'a') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_finding_detailed(finding_id): + output_mapping = [(f'f.{Properties.has_id}', 'id'), + (f't.{Properties.has_probability}', 'probability'), + (f't.{Properties.has_severity}', 'severity'), + (f'ct.{Properties.has_id}', 'cve'), + (f't.{Properties.has_description}', 'description'), + (f't.{Properties.has_attack_scenario}', 'attack_scenario'), + (f't.recommendation', 'recommendations')] + + query = (QueryBuilder().match() + .node(Labels.Finding, 'f', {Properties.has_id: finding_id}) + .related_to(Relations.has_finding_type) + .node(Labels.FindingType, 't') + .related_to(Relations.has_cve) + .node(Labels.CVEType, 'ct') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_business_application(application_id): + output_mapping = [(f'a.{Properties.has_id}', 'id'), + (f'a.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.Application, 'a', {Properties.has_id: application_id}) + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_references_for_finding(finding_id): + output_mapping = [(f'r.{Properties.has_description}', 'reference')] + + query = (QueryBuilder().match() + .node(Labels.Finding, None, {Properties.has_id: finding_id}) + .related_to(Relations.has_reference) + .node(Labels.ReferenceType, 'r') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_applications_for_finding(finding_id): + output_mapping = [(f'a.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.Finding, None, {Properties.has_id: finding_id}) + .related_to(Relations.has_cloud_object) + .node(Labels.Application, 'a') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_finding_type_details_per_id(id): + output_mapping = [(f'collect(t.{Properties.has_severity})', 'severities'), + (f'collect(t.{Properties.has_probability})', 'probabilities')] + + query = (QueryBuilder().match() + .node(Labels.FindingType, 't') + .related_from(Relations.has_finding_type) + .node(Labels.Finding) + .related_to(Relations.has_cloud_object) + .node(Labels.CloudObject) + .related_to(Relations.has_service) + .node(None, None, {Properties.has_id: id}) + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_finding_details_for_application(application_id): + output_mapping = [(f'f.{Properties.has_id}', 'id'), + (f't.{Properties.has_probability}', 'probability'), + (f't.{Properties.has_severity}', 'severity'), + (f'ct.{Properties.has_id}', 'cve')] + + query = (QueryBuilder().match() + .node(Labels.Application, None, {Properties.has_id: application_id}) + .related_to(Relations.has_cloud_object) + .node(Labels.CloudObject) + .related_from(Relations.has_cloud_object) + .node(Labels.Finding, 'f') + .related_to(Relations.has_finding_type) + .node(Labels.FindingType, 't') + .related_to(Relations.has_cve) + .node(Labels.CVEType, 'ct') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_get_service_details_for_application(application_id): + output_mapping = [(f's.{Properties.has_id}', 'id'), + (f's.{Properties.has_name}', 'name')] + + query = (QueryBuilder().match() + .node(Labels.Application, None, {Properties.has_id: application_id}) + .related_to(Relations.has_cloud_object) + .node(Labels.CloudObject) + .related_to(Relations.has_service) + .node(Labels.ServiceType, 's') + .return_mapping(output_mapping) + .get()) + + return query + + +def cypher_match_set_id(service_id): + query = (QueryBuilder().match() + .node(Labels.ServiceType, 's') + .set({Properties.has_id: service_id}) + .return_literal('s') + .get()) + + return query + + +def cypher_merge_on_match(service_id): + query = (QueryBuilder().merge() + .node(Labels.ServiceType, 's') + .on_match() + .set({Properties.has_id: service_id}) + .return_literal('s') + .get()) + + return query + + +def cypher_relationship_properties(service_id): + query = (QueryBuilder().match() + .node(Labels.Application) + .related_to(Relations.has_cloud_object) + .node(Labels.CloudObject) + .related_to(Relations.has_service, properties={Properties.has_id: service_id}) + .node(Labels.ServiceType, 's', {Properties.has_id: service_id}) + .return_literal('s') + .get()) + + return query + + +def test_cypher_get_all_findings(): + expected_query = f'MATCH (n: {Labels.Finding}) RETURN n AS n' + actual_query = cypher_get_all_findings() + assert actual_query == expected_query + + +def test_cypher_get_findings(): + expected_query = ( + f'MATCH (f: {Labels.Finding})-[: {Relations.has_finding_type}]->' + f'(t: {Labels.FindingType})-[: {Relations.has_cve}]->(ct: {Labels.CVEType}) ' + f'RETURN f.{Properties.has_id} AS id, t.{Properties.has_probability} AS probability, ' + f't.{Properties.has_severity} AS severity, ct.{Properties.has_id} AS cve') + actual_query = cypher_get_findings() + assert actual_query == expected_query + + +def test_cypher_get_services(): + expected_query = (f'MATCH (s: {Labels.ServiceType}) ' + f'RETURN s.{Properties.has_id} AS id, s.{Properties.has_name} AS name') + actual_query = cypher_get_services() + assert actual_query == expected_query + + +def test_cypher_get_business_applications(): + expected_query = (f'MATCH (a: {Labels.Application}) ' + f'RETURN a.{Properties.has_id} AS id, a.{Properties.has_name} AS name') + actual_query = cypher_get_business_applications() + assert actual_query == expected_query + + +def test_cypher_get_finding_detailed(): + finding_id = 'THAT_is_MOCK_id' + + expected_query = ( + f'MATCH (f: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})-' + f'[: {Relations.has_finding_type}]->(t: {Labels.FindingType})' + f'-[: {Relations.has_cve}]->(ct: {Labels.CVEType}) ' + f'RETURN f.{Properties.has_id} AS id, ' + f't.{Properties.has_probability} AS probability, ' + f't.{Properties.has_severity} AS severity, ct.{Properties.has_id} AS cve, ' + f't.{Properties.has_description} AS description, ' + f't.{Properties.has_attack_scenario} AS attack_scenario, t.recommendation AS recommendations') + + actual_query = cypher_get_finding_detailed(finding_id) + assert actual_query == expected_query + + +def test_cypher_get_business_application(): + application_id = 'THAT_is_MOCK_id' + expected_query = (f'MATCH (a: {Labels.Application} {{{Properties.has_id} : "{application_id}"}}) ' + f'RETURN a.{Properties.has_id} AS id, a.{Properties.has_name} AS name') + actual_query = cypher_get_business_application(application_id) + assert actual_query == expected_query + + +def test_cypher_get_references_for_finding(): + finding_id = 'THAT_is_MOCK_id' + + expected_query = (f'MATCH (: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})' + f'-[: {Relations.has_reference}]->(r: {Labels.ReferenceType}) ' + f'RETURN r.{Properties.has_description} AS reference') + + actual_query = cypher_get_references_for_finding(finding_id) + assert actual_query == expected_query + + +def test_cypher_get_applications_for_finding(): + finding_id = 'THAT_is_MOCK_id' + + expected_query = ( + f'MATCH (: {Labels.Finding} {{{Properties.has_id} : "{finding_id}"}})' + f'-[: {Relations.has_cloud_object}]->(a: {Labels.Application}) ' + f'RETURN a.{Properties.has_name} AS name') + + actual_query = cypher_get_applications_for_finding(finding_id) + assert actual_query == expected_query + + +def test_cypher_get_finding_type_details_for_service(): + service_id = 'THAT_is_MOCK_id' + + expected_query = ( + f'MATCH (t: {Labels.FindingType})<-[: {Relations.has_finding_type}]-' + f'(: {Labels.Finding})-[: {Relations.has_cloud_object}]->' + f'(: {Labels.CloudObject})-[: {Relations.has_service}]->( {{{Properties.has_id} : "{service_id}"}}) ' + f'RETURN collect(t.{Properties.has_severity}) AS severities, ' + f'collect(t.{Properties.has_probability}) AS probabilities') + + actual_query = cypher_get_finding_type_details_per_id(service_id) + assert actual_query == expected_query + + +def test_cypher_match_set_id(): + service_id = 'THAT_is_MOCK_id' + + expected_query = f'MATCH (s: {Labels.ServiceType}) SET {Properties.has_id} = "{service_id}" RETURN s' + + actual_query = cypher_match_set_id(service_id) + assert actual_query == expected_query + + +def test_cypher_merge_on_match(): + service_id = 'THAT_is_MOCK_id' + + expected_query = f'MERGE (s: {Labels.ServiceType}) ON MATCH SET {Properties.has_id} = "{service_id}" RETURN s' + + actual_query = cypher_merge_on_match(service_id) + assert actual_query == expected_query + + +def test_cypher_relationship_properties(): + service_id = 'THAT_is_MOCK_id' + + expected_query = ( + f'MATCH (: {Labels.Application})-[: {Relations.has_cloud_object}]->' + f'(: {Labels.CloudObject})-[: {Relations.has_service} {{{Properties.has_id} : "{service_id}"}}]->' + f'(s: {Labels.ServiceType} {{{Properties.has_id} : "{service_id}"}}) RETURN s') + + actual_query = cypher_relationship_properties(service_id) + assert actual_query == expected_query + +def test_cypher_query_add(): + service_id = 'THAT_is_MOCK_id' + + expected_query = ( + f'MATCH (: {Labels.Application})-[: {Relations.has_cloud_object}]->' + f'(: {Labels.CloudObject})-[: {Relations.has_service} {{{Properties.has_id} : "{service_id}"}}]->' + f'(s: {Labels.ServiceType} {{{Properties.has_id} : "{service_id}"}}) WITH s MATCH (s) RETURN s') + + actual_query1 = (QueryBuilder().match() + .node(Labels.Application) + .related_to(Relations.has_cloud_object) + .node(Labels.CloudObject) + .related_to(Relations.has_service, properties={Properties.has_id: service_id}) + .node(Labels.ServiceType, 's', {Properties.has_id: service_id}) + .with_('s')) + actual_query2 = (QueryBuilder().match() + .node(ref_name='s') + .return_literal('s')) + + actual_query = str(actual_query1 + actual_query2) + assert actual_query == expected_query + + actual_query1 += actual_query2 + actual_query = str(actual_query1) + assert actual_query == expected_query + +def test_cypher_set_unescaped_after_merge(): + node_id = '1' + + expected_query = ( + f'MERGE (n: Node {{name : "test"}}) ' + f'ON CREATE SET n.id = "{node_id}" ' + f'ON MATCH SET n.id = n.id + "1" ' + f'RETURN n') + + actual_query = (QueryBuilder() + .merge() + .node('Node', 'n', {'name': 'test'}) + .on_create().set({f'n.id': node_id}) + .on_match().set({f'n.id': f'n.id + "1"'}, escape_values=False) + .return_literal('n') + .get()) + + assert actual_query == expected_query + +def test_multiple_where_1(): + expected_query = 'MATCH (p) WHERE p.lock IS NULL OR p.value IS NULL' + actual_query = str(QueryBuilder().match().node(ref_name='p').where_multiple({'p.lock': 'NULL', 'p.value': 'NULL'}, 'IS', ' OR ', escape=False)) + assert actual_query == expected_query + +def test_multiple_where_2(): + expected_query = 'MATCH (n: Person) WHERE n.age=32 AND NOT n:Teacher' + actual_query = str(QueryBuilder().match().node('Person', ref_name='n').where_literal('n.age=32 AND NOT n:Teacher')) + assert actual_query == expected_query + +def test_with_list(): + expected_query = 'MATCH (n) WITH n AS n_test WITH [n_test] AS n_list RETURN n_list AS n_test' + actual_query = str(QueryBuilder().match().node(ref_name='n').with_('n AS n_test').with_('[n_test] AS n_list').return_mapping(('n_list', 'n_test'))) + assert actual_query == expected_query \ No newline at end of file diff --git a/tests/unit/test_samples.py b/tests/unit/test_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..81744f82623ad6459da9ef1e6f094f3c66d58e4d --- /dev/null +++ b/tests/unit/test_samples.py @@ -0,0 +1,53 @@ +import pytest +from src.samples import basic + + +rendered = { + # Read Operations # + basic.get_all_nodes_by_label.__name__: + basic.get_all_nodes_by_label(labels='Movie', node_name='n'), + basic.get_all_nodes_by_label_and_properties.__name__: + basic.get_all_nodes_by_label_and_properties(labels='Movie', properties={'name': 'The Matrix'}, node_name='n'), + basic.get_all_paths.__name__: + basic.get_all_paths(src_node_labels='Movie', dst_node_labels='Director', + relationship_type='has_directed', path_name='path'), + basic.get_all_nodes_related_to_nodes.__name__: + basic.get_all_nodes_related_to_nodes( + src_node_labels='Movie', dst_node_labels='Director', relationship_type='has_directed', dst_node_name='director'), + basic.get_all_nodes_related_by_fixed_num_of_hops.__name__: + basic.get_all_nodes_related_by_fixed_num_of_hops( + src_node_labels='Movie', dst_node_labels='Director', num_hops=2, dst_node_name='director'), + basic.get_all_nodes_related_by_varying_num_of_hops.__name__: + basic.get_all_nodes_related_by_varying_num_of_hops( + src_node_labels='Movie', dst_node_labels='Director', min_hops=1, max_hops=3, dst_node_name='director'), + # Write Operations # + basic.merge_node.__name__: + basic.merge_node(node_labels='Movie', properties={'name': 'The Matrix Revolutions'}), + basic.merge_relationship.__name__: + basic.merge_relationship(relationship_type='has_sequel', src_node_labels='Movie', src_node_properties={'name': 'The Matrix'}, + dst_node_labels='Movie', dst_node_properties={'name': 'The Matrix Revolutions'}), +} + +expected = { + basic.get_all_nodes_by_label.__name__: + 'MATCH (n: Movie) RETURN n', + basic.get_all_nodes_by_label_and_properties.__name__: + 'MATCH (n: Movie {name : "The Matrix"}) RETURN n', + basic.get_all_paths.__name__: + 'MATCH path = ( (: Movie)-[: has_directed]-(: Director) ) RETURN path', + basic.get_all_nodes_related_to_nodes.__name__: + 'MATCH (: Movie)-[: has_directed]-(director: Director) RETURN director', + basic.get_all_nodes_related_by_fixed_num_of_hops.__name__: + 'MATCH (: Movie)-[*2]-(director: Director) RETURN director', + basic.get_all_nodes_related_by_varying_num_of_hops.__name__: + 'MATCH (: Movie)-[*1..3]-(director: Director) RETURN director', + basic.merge_node.__name__: + 'MERGE (: Movie {name : "The Matrix Revolutions"})', + basic.merge_relationship.__name__: + 'MATCH (src: Movie {name : "The Matrix"}) MATCH (dst: Movie {name : "The Matrix Revolutions"}) MERGE (src)-[: has_sequel]->(dst)', +} + + +@pytest.mark.parametrize('clause', expected) +def test_samples(clause: str): + assert str(rendered[clause]) == expected[clause]