Skip to content

Commit

Permalink
Fix serialisation of dict (#422)
Browse files Browse the repository at this point in the history
* Serialisation was not working for queries which embedded dictionaries

* Add document serialisation

* Satisfy the linting gods

* Remove print statement

* Fix negation of isinstance
  • Loading branch information
GavinMendelGleason authored Nov 9, 2023
1 parent 0251f80 commit 97ec3b1
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 11 deletions.
4 changes: 2 additions & 2 deletions terminusdb_client/schema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def transform_enum_dict(d):
if not key.startswith("__") and not value:
value = str(key)
# remove this value from the undocumented member names list
if type(d._member_names) == list:
if isinstance(d._member_names, list):
d._member_names.remove(key)
else:
d._member_names.pop(key)
Expand Down Expand Up @@ -410,7 +410,7 @@ def __new__(
# definitions here, we'll have to reach into internals
# like this to keep things working well.
# There is probably a better way to do this.
if type(classdict._member_names) == list:
if isinstance(classdict._member_names, list):
classdict._member_names.remove("_schema")
else:
classdict._member_names.pop("_schema")
Expand Down
4 changes: 2 additions & 2 deletions terminusdb_client/scripts/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def __init__(self, name, parent, script=None):
else:
self.parent = parent
if script is None:
if type(parent) == str or len(parent) == 1:
if isinstance(parent, str) or len(parent) == 1:
self.script = f"class {name}({parent}):\n"
elif len(parent) > 1:
self.script = f"class {name}({', '.join(parent)}):\n"
Expand Down Expand Up @@ -266,7 +266,7 @@ def add_docstring(self, obj_dict):
if obj.parent is None:
print_script += obj.script
printed.append(obj.name)
elif type(obj.parent) == str and obj.parent in printed:
elif isinstance(obj.parent, str) and obj.parent in printed:
print_script += obj.script
printed.append(obj.name)
else:
Expand Down
27 changes: 26 additions & 1 deletion terminusdb_client/tests/test_woqlQuery.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pprint
import datetime as dt

from terminusdb_client.woqlquery.woql_query import WOQLQuery
from terminusdb_client.woqlquery.woql_query import WOQLQuery, Doc, Var

from .ans_cardinality import * # noqa
from .ans_doctype import * # noqa
Expand Down Expand Up @@ -707,3 +707,28 @@ def test_dot(self):
},
"value": {"@type": "Value", "node": "value"},
}

def test_doc(self):
result = WOQLQuery().insert_document(
Doc({"@type": "Car", "wheels": 4})
)
assert result.to_dict() == {'@type': 'InsertDocument', 'document': {'@type': 'Value', 'dictionary': {'@type': 'DictionaryTemplate', 'data': [{'@type': 'FieldValuePair', 'field': '@type', 'value': {'@type': 'Value', 'data': {'@type': 'xsd:string', '@value': 'Car'}}}, {'@type': 'FieldValuePair', 'field': 'wheels', 'value': {'@type': 'Value', 'data': {'@type': 'xsd:integer', '@value': 4}}}]}}}

def test_var(self):
result = WOQLQuery().insert_document(
Doc({"@type": "Car", "wheels": Var("v")})
)

assert result.to_dict() == {
'@type': 'InsertDocument',
'document': {'@type': 'Value',
'dictionary': {'@type': 'DictionaryTemplate',
'data': [{'@type': 'FieldValuePair',
'field': '@type',
'value': {'@type': 'Value',
'data': {'@type': 'xsd:string',
'@value': 'Car'}}},
{'@type': 'FieldValuePair',
'field': 'wheels',
'value': {'@type': 'Value',
'variable': 'v'}}]}}}
2 changes: 2 additions & 0 deletions terminusdb_client/woqlquery/woql_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ def _copy_dict(orig, rollup=None):
query = _copy_dict(part, rollup)
if query:
nuj[key] = query
elif hasattr(part, 'to_dict'):
nuj[key] = part.to_dict()
else:
nuj[key] = part
return nuj
19 changes: 13 additions & 6 deletions terminusdb_client/woqlquery/woql_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ def __init__(self, name):
def __str__(self):
return self.name

def to_dict(self):
return {"@type": "Value",
"variable": self.name}


class Doc:
def __init__(self, dictionary):
Expand All @@ -58,6 +62,9 @@ def __init__(self, dictionary):
def __str__(self):
return str(self.dictionary)

def to_dict(self):
return self.encoded

def _convert(self, obj):
if type(obj) is str:
return {"@type": "Value", "data": {"@type": "xsd:string", "@value": obj}}
Expand Down Expand Up @@ -363,9 +370,9 @@ def _clean_subject(self, obj):
def _clean_predicate(self, predicate):
"""Transforms whatever is passed in as the predicate (id or variable) into the appropriate json-ld form"""
pred = False
if type(predicate) is dict:
if isinstance(predicate, dict):
return predicate
if type(predicate) != str:
if not isinstance(predicate, str):
raise ValueError("Predicate must be a URI string")
return str(predicate)
if ":" in predicate:
Expand Down Expand Up @@ -716,7 +723,7 @@ def using(self, collection, subq=None):
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Using"
if not collection or type(collection) != str:
if not collection or not isinstance(collection, str):
raise ValueError(
"The first parameter to using must be a Collection ID (string)"
)
Expand Down Expand Up @@ -888,7 +895,7 @@ def woql_from(self, graph, query=None):
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "From"
if not graph or type(graph) != str:
if not graph or not isinstance(graph, str):
raise ValueError(
"The first parameter to from must be a Graph Filter Expression (string)"
)
Expand All @@ -914,7 +921,7 @@ def into(self, graph_descriptor, query):
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Into"
if not graph_descriptor or type(graph_descriptor) != str:
if not graph_descriptor or not isinstance(graph_descriptor, str):
raise ValueError(
"The first parameter to from must be a Graph Filter Expression (string)"
)
Expand Down Expand Up @@ -1257,7 +1264,7 @@ def substr(self, string, length, substring, before=0, after=0):
if not substring:
substring = length
length = len(substring) + before
if not string or not substring or type(substring) != str:
if not string or not substring or not isinstance(substring, str):
raise ValueError(
"Substr - the first and last parameters must be strings representing the full and substring variables / literals"
)
Expand Down

0 comments on commit 97ec3b1

Please sign in to comment.