Пример #1
0
    def set_charset_collation(self, charset=None, collation=None):
        """Sets the character set and collation for the current connection

        This method sets the character set and collation to be used for
        the current connection. The charset argument can be either the
        name of a character set as a string, or the numerical equivalent
        as defined in constants.CharacterSet.

        When the collation is not given, the default will be looked up and
        used.

        For example, the following will set the collation for the latin1
        character set to latin1_general_ci:

           set_charset('latin1','latin1_general_ci')

        """
        if charset:
            if isinstance(charset, int):
                self._charset_id = charset
                (charset_name, collation_name) = CharacterSet.get_info(self._charset_id)
            elif isinstance(charset, str):
                (self._charset_id, charset_name, collation_name) = CharacterSet.get_charset_info(charset, collation)
            else:
                raise ValueError("charset should be either integer, string or None")
        elif collation:
            (self._charset_id, charset_name, collation_name) = CharacterSet.get_charset_info(collation=collation)

        self._execute_query("SET NAMES '{}' COLLATE '{}'".format(charset_name, collation_name))
        self.converter.set_charset(charset_name)
Пример #2
0
 def set_charset(self, charset):
     """Set character set"""
     if charset is not None:
         self.charset = charset
     else:
         # default to utf8
         self.charset = 'utf8'
     self.charset_id = CharacterSet.get_charset_info(self.charset)[0]
Пример #3
0
 def set_charset(self, charset):
     """Set character set"""
     if charset is not None:
         self.charset = charset
     else:
         # default to utf8
         self.charset = 'utf8'
     self.charset_id = CharacterSet.get_charset_info(self.charset)[0]
Пример #4
0
    def collation(self):
        """Returns the collation for current connection

        This property returns the collation name of the current connection.
        The server is queried when the connection is active. If not connected,
        the configured collation name is returned.

        Returns a string.
        """
        return CharacterSet.get_charset_info(self._charset_id)[2]
Пример #5
0
 def set_converter_class(self, convclass):
     """
     Set the converter class to be used. This should be a class overloading
     methods and members of conversion.MySQLConverter.
     """
     if issubclass(convclass, MySQLConverterBase):
         charset_name = CharacterSet.get_info(self._charset_id)[0]
         self._converter_class = convclass
         self.converter = convclass(charset_name, self._use_unicode)
     else:
         raise TypeError("Converter class should be a subclass " "of conversion.MySQLConverterBase.")
Пример #6
0
    def _InitDBCursor(self, started=False):

        charset = CharacterSet.get_charset_info("utf8mb4",
                                                "utf8mb4_0900_ai_ci")

        if self._c:
            self._CloseDBCursor()

        if not started:
            self._db = mysql.connector.connect(host=HC.MYSQL_HOST,
                                               user=HC.MYSQL_USER,
                                               password=HC.MYSQL_PASSWORD,
                                               buffered=True,
                                               pool_name="hydrus",
                                               pool_size=10,
                                               charset=charset[0],
                                               use_pure=False)
        elif not self._db:
            self._db = mysql.connector.connect(host=HC.MYSQL_HOST,
                                               user=HC.MYSQL_USER,
                                               password=HC.MYSQL_PASSWORD,
                                               database=HC.MYSQL_DB,
                                               buffered=True,
                                               pool_name="hydrus",
                                               pool_size=10,
                                               charset=charset[0],
                                               use_pure=False)

        self._db.autocommit = True
        self._connection_timestamp = HydrusData.GetNow()

        self._c = self._db.cursor()
        try:

            self._BeginImmediate()

        except Exception as e:

            raise HydrusExceptions.DBAccessException(str(e))
Пример #7
0
    def config(self, *args, **kwargs):
        """Configure the MySQL Connection

        This method allows you to configure the MySQLConnection instance.

        Raises on errors.
        """
        config = kwargs.copy()
        if "dsn" in config:
            raise errors.NotSupportedError("Data source name is not supported")

        # Configure how we handle MySQL warnings
        try:
            self.get_warnings = config["get_warnings"]
            del config["get_warnings"]
        except KeyError:
            pass  # Leave what was set or default
        try:
            self.raise_on_warnings = config["raise_on_warnings"]
            del config["raise_on_warnings"]
        except KeyError:
            pass  # Leave what was set or default

        # Configure client flags
        try:
            default = ClientFlag.get_default()
            self.set_client_flags(config["client_flags"] or default)
            del config["client_flags"]
        except KeyError:
            pass  # Missing client_flags-argument is OK

        try:
            if config["compress"]:
                self.set_client_flags([ClientFlag.COMPRESS])
        except KeyError:
            pass  # Missing compress argument is OK

        # Configure character set and collation
        if "charset" in config or "collation" in config:
            try:
                charset = config["charset"]
                del config["charset"]
            except KeyError:
                charset = None
            try:
                collation = config["collation"]
                del config["collation"]
            except KeyError:
                collation = None
            self._charset_id = CharacterSet.get_charset_info(charset, collation)[0]

        # Set converter class
        try:
            self.set_converter_class(config["converter_class"])
        except KeyError:
            pass  # Using default converter class
        except TypeError:
            raise AttributeError("Converter class should be a subclass " "of conversion.MySQLConverterBase.")

        # Compatible configuration with other drivers
        compat_map = [
            # (<other driver argument>,<translates to>)
            ("db", "database"),
            ("passwd", "password"),
            ("connect_timeout", "connection_timeout"),
        ]
        for compat, translate in compat_map:
            try:
                if translate not in config:
                    config[translate] = config[compat]
                del config[compat]
            except KeyError:
                pass  # Missing compat argument is OK

        # Configure login information
        if "user" in config or "password" in config:
            try:
                user = config["user"]
                del config["user"]
            except KeyError:
                user = self._user
            try:
                password = config["password"]
                del config["password"]
            except KeyError:
                password = self._password
            self.set_login(user, password)

        # Check network locations
        try:
            self._port = int(config["port"])
            del config["port"]
        except KeyError:
            pass  # Missing port argument is OK
        except ValueError:
            raise errors.InterfaceError("TCP/IP port number should be an integer")

        # Other configuration
        set_ssl_flag = False
        for key, value in config.items():
            try:
                DEFAULT_CONFIGURATION[key]
            except KeyError:
                raise AttributeError("Unsupported argument '{}'".format(key))
            # SSL Configuration
            if key == "ssl_verify_cert":
                set_ssl_flag = True
                self._ssl.update({"verify_cert": value})
            elif key.startswith("ssl_") and value:
                set_ssl_flag = True
                self._ssl.update({key.replace("ssl_", ""): value})
            else:
                attribute = "_" + key
                try:
                    setattr(self, attribute, value.strip())
                except AttributeError:
                    setattr(self, attribute, value)

        if set_ssl_flag:
            if "verify_cert" not in self._ssl:
                self._ssl["verify_cert"] = DEFAULT_CONFIGURATION["ssl_verify_cert"]
            required_keys = set(["ca", "cert", "key"])
            diff = list(required_keys - set(self._ssl.keys()))
            if diff:
                missing_attrs = ["ssl_" + val for val in diff]
                raise AttributeError("Missing SSL argument(s): {0}".format(", ".join(missing_attrs)))
            self.set_client_flags([ClientFlag.SSL])