예제 #1
0
    def escape_bytea(self, data: "abc.Buffer") -> memoryview:
        len_out = c_size_t()
        # TODO: might be able to do without a copy but it's a mess.
        # the C library does it better anyway, so maybe not worth optimising
        # https://mail.python.org/pipermail/python-dev/2012-September/121780.html
        if not isinstance(data, bytes):
            data = bytes(data)
        if self.conn:
            self.conn._ensure_pgconn()
            out = impl.PQescapeByteaConn(
                self.conn._pgconn_ptr,
                data,
                len(data),
                pointer(t_cast(c_ulong, len_out)),
            )
        else:
            out = impl.PQescapeBytea(
                data, len(data), pointer(t_cast(c_ulong, len_out))
            )
        if not out:
            raise MemoryError(
                f"couldn't allocate for escape_bytea of {len(data)} bytes"
            )

        rv = string_at(out, len_out.value - 1)  # out includes final 0
        impl.PQfreemem(out)
        return memoryview(rv)
예제 #2
0
    def escape_bytea(self, data: bytes) -> bytes:
        len_out = c_size_t()
        if self.conn:
            self.conn._ensure_pgconn()
            out = impl.PQescapeByteaConn(
                self.conn.pgconn_ptr,
                data,
                len(data),
                pointer(t_cast(c_ulong, len_out)),
            )
        else:
            out = impl.PQescapeBytea(data, len(data),
                                     pointer(t_cast(c_ulong, len_out)))
        if not out:
            raise MemoryError(
                f"couldn't allocate for escape_bytea of {len(data)} bytes")

        rv = string_at(out, len_out.value - 1)  # out includes final 0
        impl.PQfreemem(out)
        return rv
예제 #3
0
    def unescape_bytea(self, data: bytes) -> memoryview:
        # not needed, but let's keep it symmetric with the escaping:
        # if a connection is passed in, it must be valid.
        if self.conn:
            self.conn._ensure_pgconn()

        len_out = c_size_t()
        out = impl.PQunescapeBytea(data, pointer(t_cast(c_ulong, len_out)))
        if not out:
            raise MemoryError(
                f"couldn't allocate for unescape_bytea of {len(data)} bytes")

        rv = string_at(out, len_out.value)
        impl.PQfreemem(out)
        return memoryview(rv)