예제 #1
0
    def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)", _re.UNICODE)):
        """Parse an hstore representation in a Python string.

        The hstore is represented as something like::

            "a"=>"1", "b"=>"2"

        with backslash-escaped strings.
        """
        if s is None:
            return None

        rv = {}
        start = 0
        if six.PY3 and isinstance(s, six.binary_type):
            s = s.decode(_ext.encodings[cur.connection.encoding]) \
                    if cur else bytes_to_unicode(s)
        for m in self._re_hstore.finditer(s):
            if m is None or m.start() != start:
                raise psycopg2.InterfaceError(
                    "error parsing hstore pair at char %d" % start)
            k = _bsdec.sub(r'\1', m.group(1), _re.UNICODE)
            v = m.group(2)
            if v is not None:
                v = _bsdec.sub(r'\1', v, _re.UNICODE)

            rv[k] = v
            start = m.end()

        if start < len(s):
            raise psycopg2.InterfaceError(
                "error parsing hstore: unparsed data after char %d" % start)

        return rv
예제 #2
0
 def _get_field(self, field):
     from psycopg2cffi._impl.adapters import bytes_to_unicode
     if self._exc and self._exc._pgres:
         b = libpq.PQresultErrorField(self._exc._pgres, field)
         if b:
             b = ffi.string(b)
             if six.PY3: # py2 tests insist on str here
                 b = bytes_to_unicode(b)
             return b
예제 #3
0
def parse_date(value, length, cursor):
    if value is None:
        return None
    if isinstance(value, six.text_type):
        value = unicode_to_bytes(value)
    if value == b'infinity':
        return datetime.date.max
    elif value == b'-infinity':
        return datetime.date.min

    try:
        return datetime.date(*[int(x) for x in value.split(b'-')])
    except (TypeError, ValueError):
        if value.endswith(b'BC'):
            raise ValueError('BC dates not supported')
        raise DataError("bad datetime: '%s'" % bytes_to_unicode(value))
예제 #4
0
def parse_datetime(value, length, cursor):
    if value is None:
        return None
    if isinstance(value, six.text_type):
        value = unicode_to_bytes(value)
    if value == b'infinity':
        return datetime.datetime.max
    elif value == b'-infinity':
        return datetime.datetime.min

    try:
        date, time = value.split(b' ')
        date_args = date.split(b'-')
        return datetime.datetime(
                int(date_args[0]),
                int(date_args[1]),
                int(date_args[2]),
                *_parse_time_to_args(time, cursor))
    except (TypeError, ValueError):
        if value.endswith(b'BC'):
            raise ValueError('BC dates not supported')
        raise DataError("bad datetime: '%s'" % bytes_to_unicode(value))
예제 #5
0
def parse_decimal(value, length, cursor):
    if value is None:
        return None
    if isinstance(value, six.binary_type):
        value = bytes_to_unicode(value)
    return decimal.Decimal(value)
예제 #6
0
 def _to_unicode(self, s, cur):
     if s is None:
         return None
     else:
         return s.decode(_ext.encodings[cur.connection.encoding]) \
                 if cur else bytes_to_unicode(s)
예제 #7
0
def get_exception_for_sqlstate(code):
    """Translate the sqlstate to a relevant exception.

    See for a list of possible errors:
    http://www.postgresql.org/docs/current/static/errcodes-appendix.html

    """
    if isinstance(code, six.binary_type):
        code = bytes_to_unicode(code)
    if code[0] == '0':
        # Class 0A - Feature Not Supported
        if code[1] == 'A':
            return exceptions.NotSupportedError

    elif code[0] == '2':
        # Class 20 - Case Not Found
        # Class 21 - Cardinality Violation
        if code[1] in '01':
            return exceptions.ProgrammingError

        # Class 22 - Data Exception
        if code[1] == '2':
            return exceptions.DataError

        # Class 23 - Integrity Constraint Violation
        if code[1] == '3':
            return exceptions.IntegrityError

        # Class 24 - Invalid Cursor State
        # Class 25 - Invalid Transaction State
        if code[1] in '45':
            return exceptions.InternalError

        # Class 26 - Invalid SQL Statement Name
        # Class 27 - Triggered Data Change Violation
        # Class 28 - Invalid Authorization Specification
        if code[1] in '678':
            return exceptions.OperationalError

        # Class 2B - Dependent Privilege Descriptors Still Exist
        # Class 2D - Invalid Transaction Termination
        # Class 2F - SQL Routine Exception
        if code[1] in 'BDF':
            return exceptions.InternalError

    elif code[0] == '3':
        # Class 34 - Invalid Cursor Name
        if code[1] == '4':
            return exceptions.OperationalError

        # Class 38 - External Routine Exception
        # Class 39 - External Routine Invocation Exception
        # Class 3B - Savepoint Exception
        if code[1] in '89B':
            return exceptions.InternalError

        # Class 3D - Invalid Catalog Name
        # Class 3F - Invalid Schema Name
        if code[1] in 'DF':
            return exceptions.ProgrammingError

    elif code[0] == '4':
        # Class 40 - Transaction Rollback
        if code[1] == '0':
            return exceptions.TransactionRollbackError

        # Class 42 - Syntax Error or Access Rule Violation
        # Class 44 - WITH CHECK OPTION Violation
        if code[1] in '24':
            return exceptions.ProgrammingError

    elif code[0] == '5':
        if code == '57014':
            return exceptions.QueryCanceledError

        # Class 53 - Insufficient Resources
        # Class 54 - Program Limit Exceeded
        # Class 55 - Object Not In Prerequisite State
        # Class 57 - Operator Intervention
        # Class 58 - System Error (errors external to PostgreSQL itself)
        return exceptions.OperationalError

    elif code[0] == 'F':
        # Class F0 - Configuration File Error
        return exceptions.InternalError

    elif code[0] == 'H':
        # Class HV - Foreign Data Wrapper Error (SQL/MED)
        return exceptions.OperationalError

    elif code[0] == 'P':
        # Class P0 - PL/pgSQL Error
        return exceptions.InternalError

    elif code[0] == 'X':
        # Class XX - Internal Error
        return exceptions.InternalError

    # Fallback exception
    return exceptions.DatabaseError