Esempio n. 1
0
    def quote(self, value: Union[bool, int, float, str, None]) -> str:
        """Quote a string for being passed as a literal in a query.

        Also, replace all cases of a percentage sign ('%') with a random string shared within database handler's
        instance which will be later replaced back into double percentage sign ('%%') when executing the query."""

        value = decode_object_from_bytes_if_needed(value)

        quoted_obj = None
        try:
            # Docs say that: "While the original adapt() takes 3 arguments, psycopg2's one only takes 1: the bound
            # variable to be adapted", so:
            #
            # noinspection PyArgumentList
            quoted_obj = psycopg2_adapt(value)

            if hasattr(
                    quoted_obj, 'encoding'
            ):  # integer adaptors don't support encoding for example
                # Otherwise string gets treated as Latin-1:
                quoted_obj.encoding = psycopg2.extensions.encodings['UTF8']

        except Exception as ex:
            raise McQuoteException(
                "psycopg2_adapt() failed while quoting '%s': %s" %
                (quoted_obj, str(ex)))
        if quoted_obj is None:
            raise McQuoteException(
                "psycopg2_adapt() returned None while quoting '%s'" %
                quoted_obj)

        try:
            quoted_value = quoted_obj.getquoted()
        except Exception as ex:
            raise McQuoteException(
                "getquoted() failed while quoting '%s': %s" %
                (quoted_obj, str(ex)))
        if quoted_value is None:
            raise McQuoteException(
                "getquoted() returned None while quoting '%s'" % quoted_obj)

        if isinstance(quoted_value, bytes):
            quoted_value = quoted_value.decode(encoding='utf-8',
                                               errors='replace')

        if not isinstance(quoted_value, str):
            # Maybe overly paranoid, but better than returning random stuff for a string that will go into the database
            raise McQuoteException(
                "Quoted value is not 'str' after quoting '%s'" % quoted_obj)

        # Replace percentage signs with a randomly generated marker that will be replaced back into '%%' when executing
        # the query.
        quoted_value = quoted_value.replace(
            '%', self.__double_percentage_sign_marker)

        return quoted_value
Esempio n. 2
0
    def adapt(self, value):
        if isinstance(value, Variable):
            value = value.get(to_db=True)

        if self.type == "postgres":
            output = psycopg2_adapt(value)
            if hasattr(output, "prepare"):
                output.prepare(self._conn._raw_connection)
            return output.getquoted()

        return self._default_adapt(value)
Esempio n. 3
0
    def adapt(self, value):
        if isinstance(value, Variable):
            value = value.get(to_db=True)

        if self.type == "postgres":
            output = psycopg2_adapt(value)
            if hasattr(output, "prepare"):
                raw_connection = self._conn._raw_connection
                if isinstance(raw_connection, ConnectionWrapper):
                    raw_connection = raw_connection._connection
                output.prepare(raw_connection)
            quoted = output.getquoted()
            if not isinstance(quoted, str):
                # getquoted returns bytes on Python 3, but we need str.
                quoted = quoted.decode("UTF-8")
            return quoted

        return self._default_adapt(value)
Esempio n. 4
0
    def quote(self, value: Union[bool, int, float, str, None]) -> str:
        """Quote a string for being passed as a literal in a query.

        Also, replace all cases of a percentage sign ('%') with a random string shared within database handler's
        instance which will be later replaced back into double percentage sign ('%%') when executing the query."""

        value = decode_object_from_bytes_if_needed(value)

        quoted_obj = None
        try:
            # Docs say that: "While the original adapt() takes 3 arguments, psycopg2's one only takes 1: the bound
            # variable to be adapted", so:
            #
            # noinspection PyArgumentList
            quoted_obj = psycopg2_adapt(value)

            if hasattr(quoted_obj, 'encoding'):  # integer adaptors don't support encoding for example
                # Otherwise string gets treated as Latin-1:
                quoted_obj.encoding = psycopg2.extensions.encodings['UTF8']

        except Exception as ex:
            raise McQuoteException("psycopg2_adapt() failed while quoting '%s': %s" % (quoted_obj, str(ex)))
        if quoted_obj is None:
            raise McQuoteException("psycopg2_adapt() returned None while quoting '%s'" % quoted_obj)

        try:
            quoted_value = quoted_obj.getquoted()
        except Exception as ex:
            raise McQuoteException("getquoted() failed while quoting '%s': %s" % (quoted_obj, str(ex)))
        if quoted_value is None:
            raise McQuoteException("getquoted() returned None while quoting '%s'" % quoted_obj)

        if isinstance(quoted_value, bytes):
            quoted_value = quoted_value.decode(encoding='utf-8', errors='replace')

        if not isinstance(quoted_value, str):
            # Maybe overly paranoid, but better than returning random stuff for a string that will go into the database
            raise McQuoteException("Quoted value is not 'str' after quoting '%s'" % quoted_obj)

        # Replace percentage signs with a randomly generated marker that will be replaced back into '%%' when executing
        # the query.
        quoted_value = quoted_value.replace('%', DatabaseHandler.__DOUBLE_PERCENTAGE_SIGN_MARKER)

        return quoted_value