Example #1
0
 def _encode_relationship_detail(self, relationship, template):
     return u"[" + template.format(
         id=u"" if relationship.identity is None else (u"_" + ustr(relationship.identity)),
         type=u":" + ustr(type(relationship).__name__),
         properties=PropertyDictView(relationship, encoding=self.encoding, quote=self.quote),
         property=PropertySelector(relationship, u""),
         name=relationship.__name__,
     ).strip() + u"]"
Example #2
0
 def hydrate(cls, data, batch):
     graph = getattr(batch, "graph", None)
     job_id = data["id"]
     uri = data["from"]
     status_code = data.get("status")
     location = data.get("location")
     if graph is None or batch[job_id].raw_result:
         body = data.get("body")
     else:
         body = None
         try:
             body = graph._hydrate(data.get("body"))
         except GraphError as error:
             message = "Batch job %s failed with %s\n%s" % (
                 job_id, error.__class__.__name__, ustr(error))
             raise_from(BatchError(message, batch, job_id, status_code, uri, location), error)
         else:
             # If Cypher results, reduce to single row or single value if possible
             if isinstance(body, Cursor):
                 if body.forward():
                     record = body.current()
                     width = len(record)
                     if width == 1:
                         body = record[0]
                     else:
                         body = record
                 else:
                     body = None
     return cls(batch, job_id, uri, status_code, location, body)
Example #3
0
    def encode_string(self, value):
        value = ustr(value)

        quote = self.quote
        if quote is None:
            num_single = value.count(u"'")
            num_double = value.count(u'"')
            quote = SINGLE_QUOTE if num_single <= num_double else DOUBLE_QUOTE

        if quote == SINGLE_QUOTE:
            escaped_quote = ESCAPED_SINGLE_QUOTE
            safe = SINGLE_QUOTED_SAFE
        elif quote == DOUBLE_QUOTE:
            escaped_quote = ESCAPED_DOUBLE_QUOTE
            safe = DOUBLE_QUOTED_SAFE
        else:
            raise ValueError("Unsupported quote character %r" % quote)

        if not value:
            return quote + quote

        parts = safe.split(value)
        for i in range(0, len(parts), 2):
            parts[i] = (X_ESCAPE.sub(
                u"\\\\u00\\2",
                parts[i].encode("unicode-escape").decode("utf-8")).replace(
                    quote,
                    escaped_quote).replace(u"\\u0008",
                                           u"\\b").replace(u"\\u000c", u"\\f"))
        return quote + u"".join(parts) + quote
Example #4
0
 def encode_key(cls, key):
     key = ustr(key)
     if not key:
         raise ValueError("Keys cannot be empty")
     if cls.is_safe_key(key):
         return key
     else:
         return u"`" + key.replace(u"`", u"``") + u"`"
Example #5
0
 def _encode_node(self, node, template):
     return u"(" + template.format(
         id=u"" if node.identity is None else (u"_" + ustr(node.identity)),
         labels=LabelSetView(node.labels, encoding=self.encoding, quote=self.quote),
         properties=PropertyDictView(node, encoding=self.encoding, quote=self.quote),
         property=PropertySelector(node, u""),
         name=node.__name__,
     ).strip() + u")"
Example #6
0
 def __name__(self):
     name = None
     if name is None and "__name__" in self:
         name = self["__name__"]
     if name is None and "name" in self:
         name = self["name"]
     if name is None and self.identity is not None:
         name = u"_" + ustr(self.identity)
     return name or u""
Example #7
0
 def apply(x):
     if isinstance(x, dict):
         inst.update(x)
     elif is_collection(x):
         for item in x:
             apply(item)
     elif isinstance(x, string_types):
         inst.add_label(ustr(x))
     else:
         raise TypeError("Cannot cast %s to Node" % obj.__class__.__name__)
Example #8
0
 def apply(x):
     if isinstance(x, dict):
         inst.update(x)
     elif is_collection(x):
         for item in x:
             apply(item)
     elif isinstance(x, string):
         inst.add_label(ustr(x))
     else:
         raise TypeError("Cannot cast %s to Node" % obj.__class__.__name__)
Example #9
0
 def data_row(values):
     for value in values:
         if value is None:
             yield ""
             continue
         if isinstance(value, string_types):
             value = ustr(value)
             if any(ch in value for ch in quotable):
                 value = quote + value.replace(quote, escaped_quote) + quote
         else:
             value = cypher_repr(value)
         yield value
Example #10
0
    def write_identifier(self, identifier):
        """ Write an identifier.

        :arg identifier:
        """
        if not identifier:
            raise ValueError("Invalid identifier")
        identifier = ustr(identifier)
        safe = (identifier[0] in self.safe_first_chars and
                all(ch in self.safe_chars for ch in identifier[1:]))
        if not safe:
            self.file.write(u"`")
            self.file.write(identifier.replace(u"`", u"``"))
            self.file.write(u"`")
        else:
            self.file.write(identifier)
Example #11
0
    def get(self, key, default=None):
        """ Obtain a single value from the record by index or key. If the
        specified item does not exist, the default value is returned.

        :param key: index or key
        :param default: default value to be returned if `key` does not exist
        :return: selected value
        """
        try:
            index = self.__keys.index(ustr(key))
        except ValueError:
            return default
        if 0 <= index < len(self):
            return super(Record, self).__getitem__(index)
        else:
            return default
Example #12
0
def coerce_atomic_property(x):
    if isinstance(x, unicode):
        return x
    elif isinstance(x, string):
        return ustr(x)
    elif isinstance(x, bool):
        return x
    elif isinstance(x, integer):
        if JAVA_INTEGER_MIN_VALUE <= x <= JAVA_INTEGER_MAX_VALUE:
            return x
        else:
            raise ValueError("Integer value out of range: %s" % x)
    elif isinstance(x, float):
        return x
    else:
        raise TypeError("Properties of type %s are not supported" % x.__class__.__name__)
Example #13
0
def coerce_atomic_property(x):
    if isinstance(x, unicode):
        return x
    elif isinstance(x, string):
        return ustr(x)
    elif isinstance(x, bool):
        return x
    elif isinstance(x, integer):
        if JAVA_INTEGER_MIN_VALUE <= x <= JAVA_INTEGER_MAX_VALUE:
            return x
        else:
            raise ValueError("Integer value out of range: %s" % x)
    elif isinstance(x, float):
        return x
    else:
        raise TypeError("Properties of type %s are not supported" %
                        x.__class__.__name__)
Example #14
0
    def uri_string(self):
        """ The fully resolved URI string for this target.

        :rtype: string

        """
        if isinstance(self.entity, int):
            uri_string = "{%d}" % self.entity
        elif isinstance(self.entity, NodePointer):
            uri_string = "{%d}" % self.entity.address
        else:
            remote_entity = remote(self.entity)
            if remote_entity:
                uri_string = remote_entity.ref
            else:
                uri_string = ustr(self.entity)
        if self.segments:
            if not uri_string.endswith("/"):
                uri_string += "/"
            uri_string += "/".join(map(percent_encode, self.segments))
        return uri_string
Example #15
0
 def encode_value(self, value):
     from py2neo.cypher import Literal
     from py2neo.data import Node, Relationship, Path
     from neotime import Date, Time, DateTime, Duration
     if value is None:
         return u"null"
     if value is True:
         return u"true"
     if value is False:
         return u"false"
     if isinstance(value, Literal):
         return value.value
     if isinstance(value, numeric_types):
         return ustr(value)
     if isinstance(value, string_types):
         return self.encode_string(value)
     if isinstance(value, Node):
         return self.encode_node(value)
     if isinstance(value, Relationship):
         return self.encode_relationship(value)
     if isinstance(value, Path):
         return self.encode_path(value)
     if isinstance(value, list):
         return self.encode_list(value)
     if isinstance(value, dict):
         return self.encode_map(value)
     if isinstance(value, Date):
         return u"date({})".format(self.encode_string(value.iso_format()))
     if isinstance(value, Time):
         return u"time({})".format(self.encode_string(value.iso_format()))
     if isinstance(value, DateTime):
         return u"datetime({})".format(
             self.encode_string(value.iso_format()))
     if isinstance(value, Duration):
         return u"duration({})".format(
             self.encode_string(value.iso_format()))
     raise TypeError(
         "Cypher literal values of type %s.%s are not supported" %
         (type(value).__module__, type(value).__name__))
Example #16
0
 def is_safe_key(cls, key):
     key = ustr(key)
     return key[0] in ID_START and all(key[i] in ID_CONTINUE
                                       for i in range(1, len(key)))
Example #17
0
 def __repr__(self):
     parts = ["{" + ustr(self.job_id) + "}", ustr(self.status_code)]
     if self.content is not None:
         parts.append(repr(self.content))
     return " ".join(parts)
Example #18
0
 def default_type(cls):
     from py2neo.cypher.lang import relationship_case
     if cls is Relationship:
         return "TO"
     assert issubclass(cls, Relationship)
     return ustr(relationship_case(cls.__name__))
Example #19
0
    def write_value(self, value):
        """ Write a value.

        :arg value:
        """
        self.file.write(ustr(json_dumps(value, ensure_ascii=False)))
Example #20
0
 def default_type(cls):
     if cls is Relationship:
         return "TO"
     assert issubclass(cls, Relationship)
     return ustr(relationship_case(cls.__name__))
Example #21
0
 def default_type(cls):
     if cls is Relationship:
         return "TO"
     assert issubclass(cls, Relationship)
     return ustr(relationship_case(cls.__name__))
Example #22
0
    def write_literal(self, text):
        """ Write literal text.

        :arg text:
        """
        self.file.write(ustr(text))