Beispiel #1
0
    def quote_bool(self, value: bool) -> str:
        """Quote a boolean value for being passed as a literal in a query."""
        # MC_REWRITE_TO_PYTHON: remove after starting to use Python's boolean type everywhere

        if isinstance(value, bool):
            pass
        elif isinstance(value, int):
            if value == 0:
                value = False
            elif value == 1:
                value = True
            else:
                raise McQuoteException("Value '%s' is neither 0 nor 1" % str(value))
        elif isinstance(value, str) or isinstance(value, bytes):
            value = decode_object_from_bytes_if_needed(value)
            if value.lower() in ['t', 'true', 'y', 'yes', 'on', '1']:
                value = True
            elif value.lower() in ['f', 'false', 'n', 'no', 'off', '0']:
                value = False
            else:
                raise McQuoteException("Value '%s' is string but neither of supported values" % str(value))
        else:
            raise McQuoteException("Value '%s' is unsupported" % str(value))

        return self.quote(value=value)
Beispiel #2
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