if not chunk:
                    raise errors.InterfaceError(errno=2013)
                packet += chunk
                rest = packet_totlen - len(packet)

            return packet
        except socket.timeout, err:
            raise errors.InterfaceError(errno=2013)
        except socket.error, err:
            try:
                msg = err.errno
                if msg is None:
                    msg = str(err)
            except AttributeError:
                msg = str(err)
            raise errors.InterfaceError(errno=2055,
                                        values=(self.get_address(), msg))

    recv = recv_plain

    def _split_zipped_payload(self, packet_bunch):
        """Split compressed payload"""
        while packet_bunch:
            payload_length = struct.unpack("<I", packet_bunch[0:3] + '\x00')[0]
            self._packet_queue.append(packet_bunch[0:payload_length + 4])
            packet_bunch = packet_bunch[payload_length + 4:]

    def recv_compressed(self):
        """Receive compressed packets from the MySQL server"""
        try:
            return self._packet_queue.popleft()
        except IndexError:
Ejemplo n.º 2
0
 def _handle_eof(self, buf):
     try:
         return self._pkt_parse_eof(buf)
     except:
         raise errors.InterfaceError("Failed parsing EOF packet.")
Ejemplo n.º 3
0
 def fetchall(self):
     if self._rows is None:
         raise errors.InterfaceError("No result set to fetch from.")
     return [r for r in self._rows]
Ejemplo n.º 4
0
 def _set_connection(self, connection):
     try:
         self._connection = weakref.proxy(connection)
         self._connection._protocol
     except (AttributeError, TypeError):
         raise errors.InterfaceError(errno=2048)
Ejemplo n.º 5
0
                raise errors.ProgrammingError(
                    "Wrong number of arguments during string formatting")
        else:
            stmt = operation

        if multi:
            self._executed = stmt
            self._executed_list = []
            return self._execute_iter(self._connection.cmd_query_iter(stmt))
        else:
            self._executed = stmt
            try:
                self._handle_result(self._connection.cmd_query(stmt))
            except errors.InterfaceError, err:
                if self._connection._have_next_result:
                    raise errors.InterfaceError(
                        "Use multi=True when executing multiple statements")
                raise
            return None

    def executemany(self, operation, seq_params):
        """Execute the given operation multiple times
        
        The executemany() method will execute the operation iterating
        over the list of parameters in seq_params.
        
        Example: Inserting 3 new employees and their phone number
        
        data = [
            ('Jane','555-001'),
            ('Joe', '555-001'),
            ('John', '555-003')
Ejemplo n.º 6
0
    def callproc(self, procname, args=()):
        """Calls a stored procedue with the given arguments

        The arguments will be set during this session, meaning
        they will be called like  _<procname>__arg<nr> where
        <nr> is an enumeration (+1) of the arguments.

        Coding Example:
          1) Definining the Stored Routine in MySQL:
          CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
          BEGIN
            SET pProd := pFac1 * pFac2;
          END

          2) Executing in Python:
          args = (5,5,0) # 0 is to hold pprod
          cursor.callproc('multiply', args)
          print cursor.fetchone()

        Does not return a value, but a result set will be
        available when the CALL-statement execute successfully.
        Raises exceptions when something is wrong.
        """
        if not procname or not isinstance(procname, str):
            raise ValueError("procname must be a string")

        if not isinstance(args, (tuple, list)):
            raise ValueError("args must be a sequence")

        argfmt = "@_%s_arg%d"
        self._stored_results = []

        results = []
        try:
            argnames = []

            if args:
                for idx, arg in enumerate(args):
                    argname = argfmt % (procname, idx + 1)
                    argnames.append(argname)
                    self.execute("SET %s=%%s" % (argname), (arg, ))

            call = "CALL %s(%s)" % (procname, ','.join(argnames))

            for result in self._connection.cmd_query_iter(call):
                if 'columns' in result:
                    tmp = MySQLCursorBuffered(self._connection._get_self())
                    tmp._handle_result(result)
                    results.append(tmp)

            if argnames:
                select = "SELECT %s" % ','.join(argnames)
                self.execute(select)
                self._stored_results = results
                return self.fetchone()
            else:
                self._stored_results = results
                return ()

        except errors.Error:
            raise
        except StandardError, e:
            raise errors.InterfaceError("Failed calling stored routine; %s" %
                                        e)
Ejemplo n.º 7
0
    def config(self, **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

        # 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]

        # 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 '%s'" % 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): %s" %
                                     (', '.join(missing_attrs)))
            self.set_client_flags([ClientFlag.SSL])