flowquery 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/flowquery.min.js +1 -1
  2. package/dist/graph/database.d.ts +1 -0
  3. package/dist/graph/database.d.ts.map +1 -1
  4. package/dist/graph/database.js +43 -6
  5. package/dist/graph/database.js.map +1 -1
  6. package/dist/graph/relationship.d.ts +3 -1
  7. package/dist/graph/relationship.d.ts.map +1 -1
  8. package/dist/graph/relationship.js +12 -4
  9. package/dist/graph/relationship.js.map +1 -1
  10. package/dist/graph/relationship_data.js +1 -1
  11. package/dist/graph/relationship_data.js.map +1 -1
  12. package/dist/graph/relationship_match_collector.d.ts.map +1 -1
  13. package/dist/graph/relationship_match_collector.js +6 -3
  14. package/dist/graph/relationship_match_collector.js.map +1 -1
  15. package/dist/graph/relationship_reference.js +1 -1
  16. package/dist/graph/relationship_reference.js.map +1 -1
  17. package/dist/parsing/functions/function_factory.d.ts +3 -0
  18. package/dist/parsing/functions/function_factory.d.ts.map +1 -1
  19. package/dist/parsing/functions/function_factory.js +3 -0
  20. package/dist/parsing/functions/function_factory.js.map +1 -1
  21. package/dist/parsing/functions/predicate_sum.d.ts.map +1 -1
  22. package/dist/parsing/functions/predicate_sum.js +13 -10
  23. package/dist/parsing/functions/predicate_sum.js.map +1 -1
  24. package/dist/parsing/functions/schema.d.ts +5 -2
  25. package/dist/parsing/functions/schema.d.ts.map +1 -1
  26. package/dist/parsing/functions/schema.js +7 -4
  27. package/dist/parsing/functions/schema.js.map +1 -1
  28. package/dist/parsing/functions/to_lower.d.ts +7 -0
  29. package/dist/parsing/functions/to_lower.d.ts.map +1 -0
  30. package/dist/parsing/functions/to_lower.js +37 -0
  31. package/dist/parsing/functions/to_lower.js.map +1 -0
  32. package/dist/parsing/functions/to_string.d.ts +7 -0
  33. package/dist/parsing/functions/to_string.d.ts.map +1 -0
  34. package/dist/parsing/functions/to_string.js +44 -0
  35. package/dist/parsing/functions/to_string.js.map +1 -0
  36. package/dist/parsing/functions/trim.d.ts +7 -0
  37. package/dist/parsing/functions/trim.d.ts.map +1 -0
  38. package/dist/parsing/functions/trim.js +37 -0
  39. package/dist/parsing/functions/trim.js.map +1 -0
  40. package/dist/parsing/operations/group_by.d.ts.map +1 -1
  41. package/dist/parsing/operations/group_by.js +4 -2
  42. package/dist/parsing/operations/group_by.js.map +1 -1
  43. package/dist/parsing/parser.d.ts.map +1 -1
  44. package/dist/parsing/parser.js +15 -2
  45. package/dist/parsing/parser.js.map +1 -1
  46. package/docs/flowquery.min.js +1 -1
  47. package/flowquery-py/pyproject.toml +1 -1
  48. package/flowquery-py/src/graph/database.py +44 -11
  49. package/flowquery-py/src/graph/relationship.py +11 -3
  50. package/flowquery-py/src/graph/relationship_data.py +2 -1
  51. package/flowquery-py/src/graph/relationship_match_collector.py +7 -1
  52. package/flowquery-py/src/graph/relationship_reference.py +2 -2
  53. package/flowquery-py/src/parsing/functions/__init__.py +6 -0
  54. package/flowquery-py/src/parsing/functions/predicate_sum.py +3 -6
  55. package/flowquery-py/src/parsing/functions/schema.py +9 -5
  56. package/flowquery-py/src/parsing/functions/to_lower.py +35 -0
  57. package/flowquery-py/src/parsing/functions/to_string.py +41 -0
  58. package/flowquery-py/src/parsing/functions/trim.py +35 -0
  59. package/flowquery-py/src/parsing/operations/group_by.py +2 -0
  60. package/flowquery-py/src/parsing/parser.py +12 -2
  61. package/flowquery-py/tests/compute/test_runner.py +294 -4
  62. package/flowquery-vscode/flowQueryEngine/flowquery.min.js +1 -1
  63. package/package.json +1 -1
  64. package/src/graph/database.ts +42 -4
  65. package/src/graph/relationship.ts +12 -4
  66. package/src/graph/relationship_data.ts +1 -1
  67. package/src/graph/relationship_match_collector.ts +6 -2
  68. package/src/graph/relationship_reference.ts +1 -1
  69. package/src/parsing/functions/function_factory.ts +3 -0
  70. package/src/parsing/functions/predicate_sum.ts +17 -12
  71. package/src/parsing/functions/schema.ts +7 -4
  72. package/src/parsing/functions/to_lower.ts +25 -0
  73. package/src/parsing/functions/to_string.ts +32 -0
  74. package/src/parsing/functions/trim.ts +25 -0
  75. package/src/parsing/operations/group_by.ts +4 -1
  76. package/src/parsing/parser.ts +15 -2
  77. package/tests/compute/runner.test.ts +319 -3
  78. package/tests/parsing/parser.test.ts +37 -0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "flowquery"
3
- version = "1.0.23"
3
+ version = "1.0.25"
4
4
  description = "A declarative query language for data processing pipelines"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any, Dict, Optional, Union
5
+ from typing import Any, AsyncIterator, Dict, List, Optional, Union
6
6
 
7
7
  from ..parsing.ast_node import ASTNode
8
8
  from .node import Node
@@ -48,35 +48,57 @@ class Database:
48
48
  physical = PhysicalRelationship()
49
49
  physical.type = relationship.type
50
50
  physical.statement = statement
51
+ if relationship.source is not None:
52
+ physical.source = relationship.source
53
+ if relationship.target is not None:
54
+ physical.target = relationship.target
51
55
  Database._relationships[relationship.type] = physical
52
56
 
53
57
  def get_relationship(self, relationship: 'Relationship') -> Optional['PhysicalRelationship']:
54
58
  """Gets a relationship from the database."""
55
59
  return Database._relationships.get(relationship.type) if relationship.type else None
56
60
 
57
- async def schema(self) -> list[dict[str, Any]]:
61
+ def get_relationships(self, relationship: 'Relationship') -> list['PhysicalRelationship']:
62
+ """Gets multiple physical relationships for ORed types."""
63
+ result = []
64
+ for rel_type in relationship.types:
65
+ physical = Database._relationships.get(rel_type)
66
+ if physical:
67
+ result.append(physical)
68
+ return result
69
+
70
+ async def schema(self) -> List[Dict[str, Any]]:
58
71
  """Returns the graph schema with node/relationship labels and sample data."""
59
- result: list[dict[str, Any]] = []
72
+ return [item async for item in self._schema()]
60
73
 
74
+ async def _schema(self) -> AsyncIterator[Dict[str, Any]]:
75
+ """Async generator for graph schema with node/relationship labels and sample data."""
61
76
  for label, physical_node in Database._nodes.items():
62
77
  records = await physical_node.data()
63
- entry: dict[str, Any] = {"kind": "node", "label": label}
78
+ entry: Dict[str, Any] = {"kind": "Node", "label": label}
64
79
  if records:
65
80
  sample = {k: v for k, v in records[0].items() if k != "id"}
66
- if sample:
81
+ properties = list(sample.keys())
82
+ if properties:
83
+ entry["properties"] = properties
67
84
  entry["sample"] = sample
68
- result.append(entry)
85
+ yield entry
69
86
 
70
87
  for rel_type, physical_rel in Database._relationships.items():
71
88
  records = await physical_rel.data()
72
- entry_rel: dict[str, Any] = {"kind": "relationship", "type": rel_type}
89
+ entry_rel: Dict[str, Any] = {
90
+ "kind": "Relationship",
91
+ "type": rel_type,
92
+ "from_label": physical_rel.source.label if physical_rel.source else None,
93
+ "to_label": physical_rel.target.label if physical_rel.target else None,
94
+ }
73
95
  if records:
74
96
  sample = {k: v for k, v in records[0].items() if k not in ("left_id", "right_id")}
75
- if sample:
97
+ properties = list(sample.keys())
98
+ if properties:
99
+ entry_rel["properties"] = properties
76
100
  entry_rel["sample"] = sample
77
- result.append(entry_rel)
78
-
79
- return result
101
+ yield entry_rel
80
102
 
81
103
  async def get_data(self, element: Union['Node', 'Relationship']) -> Union['NodeData', 'RelationshipData']:
82
104
  """Gets data for a node or relationship."""
@@ -87,6 +109,17 @@ class Database:
87
109
  data = await node.data()
88
110
  return NodeData(data)
89
111
  elif isinstance(element, Relationship):
112
+ if len(element.types) > 1:
113
+ physicals = self.get_relationships(element)
114
+ if not physicals:
115
+ raise ValueError(f"No physical relationships found for types {', '.join(element.types)}")
116
+ all_records = []
117
+ for i, physical in enumerate(physicals):
118
+ records = await physical.data()
119
+ type_name = element.types[i]
120
+ for record in records:
121
+ all_records.append({**record, "_type": type_name})
122
+ return RelationshipData(all_records)
90
123
  relationship = self.get_relationship(element)
91
124
  if relationship is None:
92
125
  raise ValueError(f"Physical relationship not found for type {element.type}")
@@ -19,7 +19,7 @@ class Relationship(ASTNode):
19
19
  def __init__(self) -> None:
20
20
  super().__init__()
21
21
  self._identifier: Optional[str] = None
22
- self._type: Optional[str] = None
22
+ self._types: List[str] = []
23
23
  self._hops: Hops = Hops()
24
24
  self._source: Optional['Node'] = None
25
25
  self._target: Optional['Node'] = None
@@ -39,11 +39,19 @@ class Relationship(ASTNode):
39
39
 
40
40
  @property
41
41
  def type(self) -> Optional[str]:
42
- return self._type
42
+ return self._types[0] if self._types else None
43
43
 
44
44
  @type.setter
45
45
  def type(self, value: str) -> None:
46
- self._type = value
46
+ self._types = [value]
47
+
48
+ @property
49
+ def types(self) -> List[str]:
50
+ return self._types
51
+
52
+ @types.setter
53
+ def types(self, value: List[str]) -> None:
54
+ self._types = value
47
55
 
48
56
  @property
49
57
  def hops(self) -> Hops:
@@ -25,11 +25,12 @@ class RelationshipData(Data):
25
25
  return self._find(id, hop, key)
26
26
 
27
27
  def properties(self) -> Optional[Dict[str, Any]]:
28
- """Get properties of current relationship, excluding left_id and right_id."""
28
+ """Get properties of current relationship, excluding left_id, right_id, and _type."""
29
29
  current = self.current()
30
30
  if current:
31
31
  props = dict(current)
32
32
  props.pop("left_id", None)
33
33
  props.pop("right_id", None)
34
+ props.pop("_type", None)
34
35
  return props
35
36
  return None
@@ -28,9 +28,15 @@ class RelationshipMatchCollector:
28
28
  """Push a new match onto the collector."""
29
29
  start_node_value = relationship.source.value() if relationship.source else None
30
30
  rel_data = relationship.get_data()
31
+ current_record = rel_data.current() if rel_data else None
32
+ default_type = relationship.type or ""
33
+ if current_record and isinstance(current_record, dict):
34
+ actual_type = current_record.get('_type', default_type)
35
+ else:
36
+ actual_type = default_type
31
37
  rel_props: Dict[str, Any] = (rel_data.properties() or {}) if rel_data else {}
32
38
  match: RelationshipMatchRecord = {
33
- "type": relationship.type or "",
39
+ "type": actual_type,
34
40
  "startNode": start_node_value or {},
35
41
  "endNode": None,
36
42
  "properties": rel_props,
@@ -10,8 +10,8 @@ class RelationshipReference(Relationship):
10
10
  def __init__(self, relationship: Relationship, referred: ASTNode) -> None:
11
11
  super().__init__()
12
12
  self._referred = referred
13
- if relationship.type:
14
- self.type = relationship.type
13
+ if relationship.types:
14
+ self.types = relationship.types
15
15
 
16
16
  @property
17
17
  def referred(self) -> ASTNode:
@@ -37,6 +37,9 @@ from .stringify import Stringify
37
37
  # Built-in functions
38
38
  from .sum import Sum
39
39
  from .to_json import ToJson
40
+ from .to_lower import ToLower
41
+ from .to_string import ToString
42
+ from .trim import Trim
40
43
  from .type_ import Type
41
44
  from .value_holder import ValueHolder
42
45
 
@@ -74,6 +77,9 @@ __all__ = [
74
77
  "StringDistance",
75
78
  "Stringify",
76
79
  "ToJson",
80
+ "ToLower",
81
+ "ToString",
82
+ "Trim",
77
83
  "Type",
78
84
  "Functions",
79
85
  "Schema",
@@ -1,6 +1,6 @@
1
1
  """PredicateSum function."""
2
2
 
3
- from typing import Any, Optional
3
+ from typing import Any
4
4
 
5
5
  from .function_metadata import FunctionDef
6
6
  from .predicate_function import PredicateFunction
@@ -41,12 +41,9 @@ class PredicateSum(PredicateFunction):
41
41
  if array is None or not isinstance(array, list):
42
42
  raise ValueError("Invalid array for sum function")
43
43
 
44
- _sum: Optional[Any] = None
44
+ _sum: int = 0
45
45
  for item in array:
46
46
  self._value_holder.holder = item
47
47
  if self.where is None or self.where.value():
48
- if _sum is None:
49
- _sum = self._return.value()
50
- else:
51
- _sum += self._return.value()
48
+ _sum += self._return.value()
52
49
  return _sum
@@ -9,23 +9,27 @@ from .function_metadata import FunctionDef
9
9
  @FunctionDef({
10
10
  "description": (
11
11
  "Returns the graph schema listing all nodes and relationships "
12
- "with a sample of their data."
12
+ "with their properties and a sample of their data."
13
13
  ),
14
14
  "category": "async",
15
15
  "parameters": [],
16
16
  "output": {
17
- "description": "Schema entry with kind, label/type, and optional sample data",
17
+ "description": "Schema entry with label/type, properties, and optional sample data",
18
18
  "type": "object",
19
19
  },
20
20
  "examples": [
21
- "CALL schema() YIELD kind, label, type, sample RETURN kind, label, type, sample",
21
+ "CALL schema() YIELD label, type, from_label, to_label, properties, sample "
22
+ "RETURN label, type, from_label, to_label, properties, sample",
22
23
  ],
23
24
  })
24
25
  class Schema(AsyncFunction):
25
26
  """Returns the graph schema of the database.
26
27
 
27
- Lists all nodes and relationships with their labels/types and a sample
28
- of their data (excluding id from nodes, left_id and right_id from relationships).
28
+ Lists all nodes and relationships with their labels/types, properties,
29
+ and a sample of their data (excluding id from nodes, left_id and right_id from relationships).
30
+
31
+ Nodes: {label, properties, sample}
32
+ Relationships: {type, from_label, to_label, properties, sample}
29
33
  """
30
34
 
31
35
  async def generate(self) -> AsyncGenerator[Any, None]:
@@ -0,0 +1,35 @@
1
+ """ToLower function."""
2
+
3
+ from typing import Any
4
+
5
+ from .function import Function
6
+ from .function_metadata import FunctionDef
7
+
8
+
9
+ @FunctionDef({
10
+ "description": "Converts a string to lowercase",
11
+ "category": "scalar",
12
+ "parameters": [
13
+ {"name": "text", "description": "String to convert to lowercase", "type": "string"}
14
+ ],
15
+ "output": {"description": "Lowercase string", "type": "string", "example": "hello world"},
16
+ "examples": [
17
+ "WITH 'Hello World' AS s RETURN toLower(s)",
18
+ "WITH 'FOO' AS s RETURN toLower(s)"
19
+ ]
20
+ })
21
+ class ToLower(Function):
22
+ """ToLower function.
23
+
24
+ Converts a string to lowercase.
25
+ """
26
+
27
+ def __init__(self) -> None:
28
+ super().__init__("tolower")
29
+ self._expected_parameter_count = 1
30
+
31
+ def value(self) -> Any:
32
+ val = self.get_children()[0].value()
33
+ if not isinstance(val, str):
34
+ raise ValueError("Invalid argument for toLower function: expected a string")
35
+ return val.lower()
@@ -0,0 +1,41 @@
1
+ """ToString function."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from .function import Function
7
+ from .function_metadata import FunctionDef
8
+
9
+
10
+ @FunctionDef({
11
+ "description": "Converts a value to its string representation",
12
+ "category": "scalar",
13
+ "parameters": [
14
+ {"name": "value", "description": "Value to convert to a string", "type": "any"}
15
+ ],
16
+ "output": {"description": "String representation of the value", "type": "string", "example": "42"},
17
+ "examples": [
18
+ "WITH 42 AS n RETURN toString(n)",
19
+ "WITH true AS b RETURN toString(b)",
20
+ "WITH [1, 2, 3] AS arr RETURN toString(arr)"
21
+ ]
22
+ })
23
+ class ToString(Function):
24
+ """ToString function.
25
+
26
+ Converts a value to its string representation.
27
+ """
28
+
29
+ def __init__(self) -> None:
30
+ super().__init__("tostring")
31
+ self._expected_parameter_count = 1
32
+
33
+ def value(self) -> Any:
34
+ val = self.get_children()[0].value()
35
+ if val is None:
36
+ return "null"
37
+ if isinstance(val, bool):
38
+ return str(val).lower()
39
+ if isinstance(val, (dict, list)):
40
+ return json.dumps(val)
41
+ return str(val)
@@ -0,0 +1,35 @@
1
+ """Trim function."""
2
+
3
+ from typing import Any
4
+
5
+ from .function import Function
6
+ from .function_metadata import FunctionDef
7
+
8
+
9
+ @FunctionDef({
10
+ "description": "Removes leading and trailing whitespace from a string",
11
+ "category": "scalar",
12
+ "parameters": [
13
+ {"name": "text", "description": "String to trim", "type": "string"}
14
+ ],
15
+ "output": {"description": "Trimmed string", "type": "string", "example": "hello"},
16
+ "examples": [
17
+ "WITH ' hello ' AS s RETURN trim(s)",
18
+ "WITH '\\tfoo\\n' AS s RETURN trim(s)"
19
+ ]
20
+ })
21
+ class Trim(Function):
22
+ """Trim function.
23
+
24
+ Removes leading and trailing whitespace from a string.
25
+ """
26
+
27
+ def __init__(self) -> None:
28
+ super().__init__("trim")
29
+ self._expected_parameter_count = 1
30
+
31
+ def value(self) -> Any:
32
+ val = self.get_children()[0].value()
33
+ if not isinstance(val, str):
34
+ raise ValueError("Invalid argument for trim function: expected a string")
35
+ return val.strip()
@@ -122,6 +122,8 @@ class GroupBy(Projection):
122
122
  self.mappers[mapper_index].overridden = child.value
123
123
  yield from self.generate_results(mapper_index + 1, child)
124
124
  else:
125
+ if node.elements is None:
126
+ node.elements = [reducer.element() for reducer in self.reducers]
125
127
  if node.elements:
126
128
  for i, element in enumerate(node.elements):
127
129
  self.reducers[i].overridden = element.value
@@ -398,6 +398,8 @@ class Parser(BaseParser):
398
398
  raise ValueError("Expected target node definition")
399
399
  relationship = Relationship()
400
400
  relationship.type = rel_type
401
+ relationship.source = node
402
+ relationship.target = target
401
403
 
402
404
  self._expect_and_skip_whitespace_and_comments()
403
405
  if not self.token.is_as():
@@ -576,8 +578,16 @@ class Parser(BaseParser):
576
578
  self.set_next_token()
577
579
  if not self.token.is_identifier_or_keyword():
578
580
  raise ValueError("Expected relationship type identifier")
579
- rel_type: str = self.token.value or ""
581
+ rel_types: List[str] = [self.token.value or ""]
580
582
  self.set_next_token()
583
+ while self.token.is_pipe():
584
+ self.set_next_token()
585
+ if self.token.is_colon():
586
+ self.set_next_token()
587
+ if not self.token.is_identifier_or_keyword():
588
+ raise ValueError("Expected relationship type identifier after '|'")
589
+ rel_types.append(self.token.value or "")
590
+ self.set_next_token()
581
591
  hops = self._parse_relationship_hops()
582
592
  properties: Dict[str, Expression] = dict(self._parse_properties())
583
593
  if not self.token.is_closing_bracket():
@@ -607,7 +617,7 @@ class Parser(BaseParser):
607
617
  self._state.variables[variable] = relationship
608
618
  if hops is not None:
609
619
  relationship.hops = hops
610
- relationship.type = rel_type
620
+ relationship.types = rel_types
611
621
  return relationship
612
622
 
613
623
  def _parse_properties(self) -> Iterator[Tuple[str, Expression]]: