コード例 #1
0
def test():
    ctype = 'text/plain'
    html = ''
    html += 'Python: %s\n' % sys.version
    html += 'mysql: %s\n' % mysql.get_client_info()
    html += 'OPENSHIFT_MYSQL_DB: %s:%d\n' % (os.environ['OPENSHIFT_MYSQL_DB_HOST'], int(os.environ['OPENSHIFT_MYSQL_DB_PORT']))
    return (ctype, html)
コード例 #2
0
    def _parse_connection_string(cls, connection, use_unicode=False,
                                 charset=None, timeout=None):
        """ Done as a class method to both allow access to class attribute
            conv (conversion) settings while allowing for wrapping pool class
            use of this method. The former is important to allow for subclasses
            to override the conv settings while the latter is important so
            the connection string doesn't have to be parsed for each instance
            in the pool.
        """
        kw_args = {'conv': cls.conv}
        flags = {'kw_args': kw_args, 'connection': connection}
        kw_args['use_unicode'] = use_unicode
        if use_unicode:
            kw_args['charset'] = cls.unicode_charset
        if charset:
            kw_args['charset'] = charset
        items = connection.split()
        flags['use_TM'] = None
        if _mysql.get_client_info()[0] >= '5':
            kw_args['client_flag'] = CLIENT.MULTI_STATEMENTS
        if items:
            lockreq, items = items[0], items[1:]
            if lockreq[0] == '*':
                flags['mysql_lock'] = lockreq[1:]
                db_host, items = items[0], items[1:]
                flags['use_TM'] = True  # redundant. eliminate?
            else:
                flags['mysql_lock'] = None
                db_host = lockreq
            if '@' in db_host:
                db, host = db_host.split('@', 1)
                kw_args['db'] = db
                if ':' in host:
                    host, port = host.split(':', 1)
                    kw_args['port'] = int(port)
                kw_args['host'] = host
            else:
                kw_args['db'] = db_host
            if kw_args['db'] and kw_args['db'][0] in ('+', '-'):
                flags['try_transactions'] = kw_args['db'][0]
                kw_args['db'] = kw_args['db'][1:]
            else:
                flags['try_transactions'] = None
            if not kw_args['db']:
                del kw_args['db']
            if items:
                kw_args['user'], items = items[0], items[1:]
            if items:
                kw_args['passwd'], items = items[0], items[1:]
            if items:
                kw_args['unix_socket'], items = items[0], items[1:]
        if timeout:
            kw_args['connect_timeout'] = timeout

        return flags
コード例 #3
0
def check_libmysqlclient_version(app_configs, **kwargs):
    """
    Check mysqlclient has been compiled against a version of libmysqlclient
    that isn't vulnerable to TLS stripping. See vendor-libmysqclient.sh.
    """
    # get_client_info() returns the libmysqlclient version as a string of form `5.7.0`.
    libmysqlclient_version = get_client_info()
    if version_to_tuple(libmysqlclient_version) < (5, 7, 11):
        msg = ("mysqlclient has been compiled against an insecure version "
               "of libmysqlclient (%s)." % libmysqlclient_version)
        hint = "If using Vagrant, run `vagrant provision` and re-login."
        return [Error(msg, hint=hint, id="treeherder.E001")]
    return []
コード例 #4
0
ファイル: python.monitor.mysql.py プロジェクト: weady/shell
	def printmysqlinfo(self):
		print "=============MySQL info============="
		print "Connection id        : "+str(self.conn.thread_id())
		print "Current database     : "+dbname
		print "Current user         : "******"SSL                  : "+self.mysqlvariables.strFormat('have_openssl')
		#print "Current pager        : "
		#print "Using outfile        : "
		#print "Using delimiter      : "
		self.version=Decimal(self.mysqlvariables.strFormat('version')[0:3])
		print "MySQL VERSION        : "+self.mysqlvariables.strFormat('version')+" "+self.mysqlvariables.strFormat('version_comment')
		print "MySQL client info    : "+_mysql.get_client_info()
		print "Protocol version     : "+str(self.conn.get_proto_info())
		print "Connection           : "+self.conn.get_host_info()
		print "Server characterset  : "+self.mysqlvariables.strFormat('character_set_server')
		print "Db     characterset  : "+self.mysqlvariables.strFormat('character_set_database')
		print "Client characterset  : "+self.mysqlvariables.strFormat('character_set_client')
		print "Conn.  characterset  : "+self.mysqlvariables.strFormat('character_set_connection')
		print "collation_connection : "+self.mysqlvariables.strFormat('collation_connection')
		print "collation_database   : "+self.mysqlvariables.strFormat('collation_database')
		print "collation_server     : "+self.mysqlvariables.strFormat('collation_server')
		print "Uptime               : "+self.mysqlstatus['Uptime']+"s"
コード例 #5
0
ファイル: db.py プロジェクト: lds56/LDSLIB
 def _parse_connection_string(self, connection):
     kwargs = {'conv': self.conv}
     items = split(connection)
     self._use_TM = None
     if _mysql.get_client_info()[0] >= '5':
         kwargs['client_flag'] = CLIENT.MULTI_STATEMENTS
     if not items: return kwargs
     lockreq, items = items[0], items[1:]
     if lockreq[0] == "*":
         self._mysql_lock = lockreq[1:]
         db_host, items = items[0], items[1:]
         self._use_TM = 1
     else:
         self._mysql_lock = None
         db_host = lockreq
     if '@' in db_host:
         db, host = split(db_host,'@',1)
         kwargs['db'] = db
         if ':' in host:
             host, port = split(host,':',1)
             kwargs['port'] = int(port)
         kwargs['host'] = host
     else:
         kwargs['db'] = db_host
     if kwargs['db'] and kwargs['db'][0] in ('+', '-'):
         self._try_transactions = kwargs['db'][0]
         kwargs['db'] = kwargs['db'][1:]
     else:
         self._try_transactions = None
     if not kwargs['db']:
         del kwargs['db']
     if not items: return kwargs
     kwargs['user'], items = items[0], items[1:]
     if not items: return kwargs
     kwargs['passwd'], items = items[0], items[1:]
     if not items: return kwargs
     kwargs['unix_socket'], items = items[0], items[1:]
     return kwargs
コード例 #6
0
    def __init__(self, *args, **kwargs):
        """

        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect

        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer).

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.

        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables

        autocommit
          If False (default), autocommit is disabled.
          If True, autocommit is enabled.
          If None, autocommit isn't set and server default is used.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import conversions
        from weakref import proxy, WeakValueDictionary

        kwargs2 = kwargs.copy()

        if 'conv' in kwargs:
            conv = kwargs['conv']
        else:
            conv = conversions

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:
                conv2[k] = v
        kwargs2['conv'] = conv2

        cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', 'utf8')

        sql_mode = kwargs2.pop('sql_mode', '')

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS

        kwargs2['client_flag'] = client_flag

        # PEP-249 requires autocommit to be initially off
        autocommit = kwargs2.pop('autocommit', False)

        super(Connection, self).__init__(*args, **kwargs2)
        self.cursorclass = cursorclass
        self.encoders = dict([ (k, v) for k, v in conv.items()
                               if type(k) is not int ])

        self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])

        db = proxy(self)
        def _get_string_literal():
            def string_literal(obj, dummy=None):
                return db.string_literal(obj)
            return string_literal

        def _get_bytes_literal():
            def bytes_literal(u, dummy=None):
                return db.literal(u.decode(bytes_literal.charset))
            return bytes_literal

        string_literal = _get_string_literal()
        self.bytes_literal = bytes_literal = _get_bytes_literal()
        if not charset:
            charset = self.character_set_name()
        self.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        self.encoders[str] = string_literal
        self.encoders[bytes] = bytes_literal

        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        if self._transactional:
            if autocommit is not None:
                self.autocommit(autocommit)
        self.messages = []
コード例 #7
0
 def test_client_info(self):
     self.assertTrue(isinstance(_mysql.get_client_info(), str))
コード例 #8
0
ファイル: connections.py プロジェクト: sscir020/inventory2
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        :param str host:        host to connect
        :param str user:        user to connect as
        :param str password:    password to use
        :param str passwd:      alias of password, for backward compatibility
        :param str database:    database to use
        :param str db:          alias of database, for backward compatibility
        :param int port:        TCP/IP port to connect to
        :param str unix_socket: location of unix_socket to use
        :param dict conv:       conversion dictionary, see MySQLdb.converters
        :param int connect_timeout:
            number of seconds to wait before the connection attempt fails.

        :param bool compress:   if set, compression is enabled
        :param str named_pipe:  if set, a named pipe is used to connect (Windows only)
        :param str init_command:
            command which is run once the connection is created

        :param str read_default_file:
            file from which default client values are read

        :param str read_default_group:
            configuration group to use from the default file

        :param type cursorclass:
            class object, used to create cursors (keyword only)

        :param bool use_unicode:
            If True, text-like columns are returned as unicode objects
            using the connection's character set.  Otherwise, text-like
            columns are returned as strings.  columns are returned as
            normal strings. Unicode objects will always be encoded to
            the connection's character set regardless of this setting.
            Default to False on Python 2 and True on Python 3.

        :param str charset:
            If supplied, the connection character set will be changed
            to this character set (MySQL-4.1 and newer). This implies
            use_unicode=True.

        :param str sql_mode:
            If supplied, the session SQL mode will be changed to this
            setting (MySQL-4.1 and newer). For more details and legal
            values, see the MySQL documentation.

        :param int client_flag:
            flags to use or 0 (see MySQL docs or constants/CLIENTS.py)

        :param dict ssl:
            dictionary or mapping contains SSL connection parameters;
            see the MySQL documentation for more details
            (mysql_ssl_set()).  If this is set, and the client does not
            support SSL, NotSupportedError will be raised.

        :param bool local_infile:
            enables LOAD LOCAL INFILE; zero disables

        :param bool autocommit:
            If False (default), autocommit is disabled.
            If True, autocommit is enabled.
            If None, autocommit isn't set and server default is used.

        :param bool binary_prefix:
            If set, the '_binary' prefix will be used for raw byte query
            arguments (e.g. Binary). This is disabled by default.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.
        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import conversions
        from weakref import proxy

        kwargs2 = kwargs.copy()

        if 'database' in kwargs2:
            kwargs2['db'] = kwargs2.pop('database')
        if 'password' in kwargs2:
            kwargs2['passwd'] = kwargs2.pop('password')

        if 'conv' in kwargs:
            conv = kwargs['conv']
        else:
            conv = conversions

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:
                conv2[k] = v
        kwargs2['conv'] = conv2

        cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

        if charset or not PY2:
            use_unicode = True
        else:
            use_unicode = False

        use_unicode = kwargs2.pop('use_unicode', use_unicode)
        sql_mode = kwargs2.pop('sql_mode', '')
        self._binary_prefix = kwargs2.pop('binary_prefix', False)

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS

        kwargs2['client_flag'] = client_flag

        # PEP-249 requires autocommit to be initially off
        autocommit = kwargs2.pop('autocommit', False)
        self.waiter = kwargs2.pop('waiter', None)

        super(Connection, self).__init__(*args, **kwargs2)
        self.cursorclass = cursorclass
        self.encoders = dict([ (k, v) for k, v in conv.items()
                               if type(k) is not int ])

        self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])

        self.encoding = 'ascii'  # overriden in set_character_set()
        db = proxy(self)

        # Note: string_literal() is called for bytes object on Python 3 (via bytes_literal)
        def string_literal(obj, dummy=None):
            return db.string_literal(obj)

        if PY2:
            # unicode_literal is called for only unicode object.
            def unicode_literal(u, dummy=None):
                return db.string_literal(u.encode(db.encoding))
        else:
            # unicode_literal() is called for arbitrary object.
            def unicode_literal(u, dummy=None):
                return db.string_literal(str(u).encode(db.encoding))

        def bytes_literal(obj, dummy=None):
            return b'_binary' + db.string_literal(obj)

        def string_decoder(s):
            return s.decode(db.encoding)

        if not charset:
            charset = self.character_set_name()
        self.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        if use_unicode:
            for t in (FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING, FIELD_TYPE.VARCHAR, FIELD_TYPE.TINY_BLOB,
                      FIELD_TYPE.MEDIUM_BLOB, FIELD_TYPE.LONG_BLOB, FIELD_TYPE.BLOB):
                self.converter[t].append((None, string_decoder))

        self.encoders[bytes] = string_literal
        self.encoders[unicode] = unicode_literal
        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        if self._transactional:
            if autocommit is not None:
                self.autocommit(autocommit)
        self.messages = []
コード例 #9
0
ファイル: connections.py プロジェクト: baladewa88/new-idci
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect

        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.
          Default to False on Python 2 and True on Python 3.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.

        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables

        autocommit
          If False (default), autocommit is disabled.
          If True, autocommit is enabled.
          If None, autocommit isn't set and server default is used.

        waiter
          Callable accepts fd as an argument. It is called after sending
          query and before reading response.
          This is useful when using with greenlet and async io.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.
        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import conversions
        from weakref import proxy

        kwargs2 = kwargs.copy()

        if 'conv' in kwargs:
            conv = kwargs['conv']
        else:
            conv = conversions

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:
                conv2[k] = v
        kwargs2['conv'] = conv2

        cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

        if charset or not PY2:
            use_unicode = True
        else:
            use_unicode = False

        use_unicode = kwargs2.pop('use_unicode', use_unicode)
        sql_mode = kwargs2.pop('sql_mode', '')

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple(
            [numeric_part(n) for n in _mysql.get_client_info().split('.')[:2]])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS

        kwargs2['client_flag'] = client_flag

        # PEP-249 requires autocommit to be initially off
        autocommit = kwargs2.pop('autocommit', False)
        self.waiter = kwargs2.pop('waiter', None)

        super(Connection, self).__init__(*args, **kwargs2)
        self.cursorclass = cursorclass
        self.encoders = dict([(k, v) for k, v in conv.items()
                              if type(k) is not int])

        self._server_version = tuple(
            [numeric_part(n) for n in self.get_server_info().split('.')[:2]])

        db = proxy(self)

        def _get_string_literal():
            # Note: string_literal() is called for bytes object on Python 3.
            def string_literal(obj, dummy=None):
                return db.string_literal(obj)

            return string_literal

        def _get_unicode_literal():
            if PY2:
                # unicode_literal is called for only unicode object.
                def unicode_literal(u, dummy=None):
                    return db.literal(u.encode(unicode_literal.charset))
            else:
                # unicode_literal() is called for arbitrary object.
                def unicode_literal(u, dummy=None):
                    return db.literal(str(u).encode(unicode_literal.charset))

            return unicode_literal

        def _get_string_decoder():
            def string_decoder(s):
                return s.decode(string_decoder.charset)

            return string_decoder

        string_literal = _get_string_literal()
        self.unicode_literal = unicode_literal = _get_unicode_literal()
        self.string_decoder = string_decoder = _get_string_decoder()
        if not charset:
            charset = self.character_set_name()
        self.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        if use_unicode:
            self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VAR_STRING].append(
                (None, string_decoder))
            self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
            self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))

        self.encoders[bytes] = string_literal
        self.encoders[unicode] = unicode_literal
        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        if self._transactional:
            if autocommit is not None:
                self.autocommit(autocommit)
        self.messages = []
コード例 #10
0
 def test_client_info(self):
     self.assertTrue(isinstance(_mysql.get_client_info(), str))
コード例 #11
0
ファイル: connections.py プロジェクト: lds56/LDSLIB
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended that
        you only use keyword parameters. Consult the MySQL C API documentation
        for more information.

        host
          string, host to connect
          
        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        decoders
          list, SQL decoder stack
          
        encoders
          list, SQL encoder stack
          
        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.
          
        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables
    
        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import default_decoders, default_encoders, default_row_formatter
        from MySQLdb.cursors import Cursor
        import _mysql

        kwargs2 = kwargs.copy()

        self.cursorclass = Cursor
        charset = kwargs2.pop('charset', '')

        self.encoders = kwargs2.pop('encoders', default_encoders)
        self.decoders = kwargs2.pop('decoders', default_decoders)
        self.row_formatter = kwargs2.pop('row_formatter', default_row_formatter)
        
        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple(
            [ int(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS
        
        kwargs2['client_flag'] = client_flag
        
        sql_mode = kwargs2.pop('sql_mode', None)
        
        self._db = _mysql.connection(*args, **kwargs2)

        self._server_version = tuple(
            [ int(n) for n in self._db.get_server_info().split('.')[:2] ])

        if charset:
            self._db.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        self._transactional = bool(self._db.server_capabilities & CLIENT.TRANSACTIONS)
        if self._transactional:
            # PEP-249 requires autocommit to be initially off
            self.autocommit(False)
        self.messages = []
        self._active_cursor = None
コード例 #12
0
ファイル: connections.py プロジェクト: andrii29/django-test1
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        :param str host:        host to connect
        :param str user:        user to connect as
        :param str password:    password to use
        :param str passwd:      alias of password, for backward compatibility
        :param str database:    database to use
        :param str db:          alias of database, for backward compatibility
        :param int port:        TCP/IP port to connect to
        :param str unix_socket: location of unix_socket to use
        :param dict conv:       conversion dictionary, see MySQLdb.converters
        :param int connect_timeout:
            number of seconds to wait before the connection attempt fails.

        :param bool compress:   if set, compression is enabled
        :param str named_pipe:  if set, a named pipe is used to connect (Windows only)
        :param str init_command:
            command which is run once the connection is created

        :param str read_default_file:
            file from which default client values are read

        :param str read_default_group:
            configuration group to use from the default file

        :param type cursorclass:
            class object, used to create cursors (keyword only)

        :param bool use_unicode:
            If True, text-like columns are returned as unicode objects
            using the connection's character set.  Otherwise, text-like
            columns are returned as strings.  columns are returned as
            normal strings. Unicode objects will always be encoded to
            the connection's character set regardless of this setting.
            Default to False on Python 2 and True on Python 3.

        :param str charset:
            If supplied, the connection character set will be changed
            to this character set (MySQL-4.1 and newer). This implies
            use_unicode=True.

        :param str sql_mode:
            If supplied, the session SQL mode will be changed to this
            setting (MySQL-4.1 and newer). For more details and legal
            values, see the MySQL documentation.

        :param int client_flag:
            flags to use or 0 (see MySQL docs or constants/CLIENTS.py)

        :param dict ssl:
            dictionary or mapping contains SSL connection parameters;
            see the MySQL documentation for more details
            (mysql_ssl_set()).  If this is set, and the client does not
            support SSL, NotSupportedError will be raised.

        :param bool local_infile:
            enables LOAD LOCAL INFILE; zero disables

        :param bool autocommit:
            If False (default), autocommit is disabled.
            If True, autocommit is enabled.
            If None, autocommit isn't set and server default is used.

        :param bool binary_prefix:
            If set, the '_binary' prefix will be used for raw byte query
            arguments (e.g. Binary). This is disabled by default.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.
        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import conversions
        from weakref import proxy

        kwargs2 = kwargs.copy()

        if 'database' in kwargs2:
            kwargs2['db'] = kwargs2.pop('database')
        if 'password' in kwargs2:
            kwargs2['passwd'] = kwargs2.pop('password')

        if 'conv' in kwargs:
            conv = kwargs['conv']
        else:
            conv = conversions

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:
                conv2[k] = v
        kwargs2['conv'] = conv2

        cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

        if charset or not PY2:
            use_unicode = True
        else:
            use_unicode = False

        use_unicode = kwargs2.pop('use_unicode', use_unicode)
        sql_mode = kwargs2.pop('sql_mode', '')
        self._binary_prefix = kwargs2.pop('binary_prefix', False)

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS

        kwargs2['client_flag'] = client_flag

        # PEP-249 requires autocommit to be initially off
        autocommit = kwargs2.pop('autocommit', False)
        self.waiter = kwargs2.pop('waiter', None)

        super(Connection, self).__init__(*args, **kwargs2)
        self.cursorclass = cursorclass
        self.encoders = dict([ (k, v) for k, v in conv.items()
                               if type(k) is not int ])

        self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])

        self.encoding = 'ascii'  # overriden in set_character_set()
        db = proxy(self)

        # Note: string_literal() is called for bytes object on Python 3 (via bytes_literal)
        def string_literal(obj, dummy=None):
            return db.string_literal(obj)

        if PY2:
            # unicode_literal is called for only unicode object.
            def unicode_literal(u, dummy=None):
                return db.string_literal(u.encode(db.encoding))
        else:
            # unicode_literal() is called for arbitrary object.
            def unicode_literal(u, dummy=None):
                return db.string_literal(str(u).encode(db.encoding))

        def bytes_literal(obj, dummy=None):
            return b'_binary' + db.string_literal(obj)

        def string_decoder(s):
            return s.decode(db.encoding)

        if not charset:
            charset = self.character_set_name()
        self.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        if use_unicode:
            self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
            self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))

        self.encoders[bytes] = string_literal
        self.encoders[unicode] = unicode_literal
        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        if self._transactional:
            if autocommit is not None:
                self.autocommit(autocommit)
        self.messages = []
コード例 #13
0
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended that
        you only use keyword parameters. Consult the MySQL C API documentation
        for more information.

        host
          string, host to connect

        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        decoders
          list, SQL decoder stack

        encoders
          list, SQL encoder stack

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.

        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import default_decoders, default_encoders, default_row_formatter
        from MySQLdb.cursors import Cursor
        import _mysql

        kwargs2 = kwargs.copy()

        self.cursorclass = Cursor
        charset = kwargs2.pop('charset', '')

        self.encoders = kwargs2.pop('encoders', default_encoders)
        self.decoders = kwargs2.pop('decoders', default_decoders)
        self.row_formatter = kwargs2.pop('row_formatter', default_row_formatter)

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple(
            [ int(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS

        kwargs2['client_flag'] = client_flag

        sql_mode = kwargs2.pop('sql_mode', None)

        self._db = _mysql.connection(*args, **kwargs2)

        self._server_version = tuple(
            [ int(n) for n in self._db.get_server_info().split('.')[:2] ])

        if charset:
            self._db.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        self._transactional = bool(self._db.server_capabilities & CLIENT.TRANSACTIONS)
        if self._transactional:
            # PEP-249 requires autocommit to be initially off
            self.autocommit(False)
        self.messages = []
        self._active_cursor = None
コード例 #14
0
ファイル: connection.py プロジェクト: edelooff/newWeb
  def __init__(self, user, passwd, *args, **kwargs):
    """Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.

    Arguments:
      user:               string, user to connect as.
      passwd:             string, password to use.
      db:                 string, database to use. Default same as user.
      host:               string, host to connect to. Default 'localhost'.
      port:               integer, TCP/IP port to connect to.
      unix_socket:        string, location of unix_socket to use.
      conv:               conversion dictionary, see converters module.
      connect_timeout:    number of seconds to wait before the connection
                          attempt fails.
      compress:           bool, enable compression. Default False
      named_pipe:         if set, a named pipe is used to connect (Windows only)
      init_command:       command which is run once the connection is created
      read_default_file:  file from which default client values are read
      read_default_group: configuration group to use from the default file
      use_unicode:        If True, text-like columns are returned as unicode
                          objects using the connection's character set.
                          Otherwise, text-like columns are returned as strings.
                          Columns are returned as normal strings. Unicode
                          objects will always be encoded to the connection's
                          character set regardless of this setting.
      charset:            If supplied, the connection character set will be
                          changed to this character set (MySQL-4.1 and newer).
                          This enforces use_unicode=True.
      sql_mode:           If supplied, the session SQL mode will be changed to
                          this setting (MySQL-4.1 and newer). For more details
                          and legal values, see the MySQL documentation.
      client_flag:        integer, flags to use or 0.
                          (see MySQL docs or constants/CLIENTS.py)
      ssl:                dictionary or mapping, contains SSL connection
                          parameters; see the MySQL documentation for more
                          details (mysql_ssl_set()).  If this is set, and the
                          client does not support SSL, NotSupportedError will
                          be raised.
      local_infile:       bool, True enables LOAD LOCAL INFILE, False disables.
                          Default False

    There are a number of undocumented, non-standard arguments. See the
    documentation for the MySQL C API for some hints on what they do.
    """
    # Counters, transaction lock & timer
    self.counter_transactions = 0
    self.counter_queries = 0
    self.queries = []
    self.transaction_timer = None
    self.lock = threading.Lock()

    # _mysql connect args mapping
    kwargs['user'] = user
    kwargs['passwd'] = passwd
    kwargs['host'] = kwargs.get('host', 'localhost')
    kwargs['db'] = kwargs.get('db', user)
    self.logger = logging.getLogger('mysql_%s' % kwargs['db'])
    if kwargs.pop('debug', False):
      self.debug = True
      self.logger.setLevel(logging.DEBUG)
    else:
      self.debug = False
      self.logger.setLevel(logging.WARNING)
    if kwargs.pop('disable_log', False):
      self.logger.disable_logger = True

    self.encoders = {}
    converts = {}
    for key, value in converters.CONVERSIONS.iteritems():
      if not isinstance(key, int):
        self.encoders[key] = value
      else:
        if isinstance(value, list):
          converts[key] = value[:]
        else:
          converts[key] = value
    kwargs.setdefault('conv', {}).update(converts)

    autocommit = kwargs.pop('autocommit', None)
    charset = kwargs.pop('charset', 'utf8')
    sql_mode = kwargs.pop('sql_mode', None)
    use_unicode = kwargs.pop('use_unicode', False) or bool(charset)

    client_version = tuple(map(int, _mysql.get_client_info().split('.')[:2]))
    kwargs.setdefault('client_flag', 0)
    if client_version >= (4, 1):
      kwargs['client_flag'] |= constants.CLIENT.MULTI_STATEMENTS
    if client_version >= (5, 0):
      kwargs['client_flag'] |= constants.CLIENT.MULTI_RESULTS

    # Done redefining variables for initialization. Engage _mysql!
    super(Connection, self).__init__(*args, **kwargs)

    self.server_version = tuple(map(int, self.get_server_info().split('.')[:2]))
    if sql_mode:
      self.SetSqlMode(sql_mode)

    # The following voodoo is necssary to avoid double references that would
    # prevent a connection object from being finalized and collected properly.
    db = weakref.proxy(self)
    def _GetStringLiteral():
      def StringLiteral(string, _dummy=None):
        """Returns the SQL literal (safe) for the given string."""
        return db.string_literal(string)
      return StringLiteral

    def _GetUnicodeLiteral():
      def UnicodeLiteral(u_string, _dummy=None):
        """Returns the SQL (safe) literal for the given unicode object."""
        return db.EscapeValues(u_string.encode(db.charset))
      return UnicodeLiteral

    def _GetStringDecoder():
      def StringDecoder(string):
        """Returns the unicode codepoints for an encoded bytestream."""
        return string.decode(db.charset)
      return StringDecoder

    self.string_decoder = _GetStringDecoder()
    self.encoders[str] = _GetStringLiteral()
    self.encoders[unicode] = self.unicode_literal = _GetUnicodeLiteral()

    if use_unicode:
      decoder = None, self.string_decoder
      self.converter[constants.FIELD_TYPE.STRING].append(decoder)
      self.converter[constants.FIELD_TYPE.VAR_STRING].append(decoder)
      self.converter[constants.FIELD_TYPE.VARCHAR].append(decoder)
      self.converter[constants.FIELD_TYPE.BLOB].append(decoder)
    self._charset = None
    self.charset = charset or self.character_set_name()

    self.transactional = bool(self.server_capabilities &
                              constants.CLIENT.TRANSACTIONS)
    self._autocommit = None
    if autocommit is not None:
      self.autocommit = autocommit
    else:
      self.autocommit = not self.transactional
コード例 #15
0
ファイル: connections.py プロジェクト: shivekkhurana/bowdin
    def __init__(self, *args, **kwargs):
        """

        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect
          
        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.
          
        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables
    
        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """
        from MySQLdb.constants import CLIENT, FIELD_TYPE
        from MySQLdb.converters import conversions
        from weakref import proxy, WeakValueDictionary
        
        import types

        kwargs2 = kwargs.copy()
        
        if 'conv' in kwargs:
            conv = kwargs['conv']
        else:
            conv = conversions

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:
                conv2[k] = v
        kwargs2['conv'] = conv2

        cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

        if charset:
            use_unicode = True
        else:
            use_unicode = False
            
        use_unicode = kwargs2.pop('use_unicode', use_unicode)
        sql_mode = kwargs2.pop('sql_mode', '')

        client_flag = kwargs.get('client_flag', 0)
        client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
        if client_version >= (4, 1):
            client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            client_flag |= CLIENT.MULTI_RESULTS
            
        kwargs2['client_flag'] = client_flag

        super(Connection, self).__init__(*args, **kwargs2)
        self.cursorclass = cursorclass
        self.encoders = dict([ (k, v) for k, v in conv.items()
                               if type(k) is not int ])
        
        self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])

        db = proxy(self)
        def _get_string_literal():
            def string_literal(obj, dummy=None):
                return db.string_literal(obj)
            return string_literal

        def _get_unicode_literal():
            def unicode_literal(u, dummy=None):
                return db.literal(u.encode(unicode_literal.charset))
            return unicode_literal

        def _get_string_decoder():
            def string_decoder(s):
                return s.decode(string_decoder.charset)
            return string_decoder
        
        string_literal = _get_string_literal()
        self.unicode_literal = unicode_literal = _get_unicode_literal()
        self.string_decoder = string_decoder = _get_string_decoder()
        if not charset:
            charset = self.character_set_name()
        self.set_character_set(charset)

        if sql_mode:
            self.set_sql_mode(sql_mode)

        if use_unicode:
            self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
            self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))

        self.encoders[types.StringType] = string_literal
        self.encoders[types.UnicodeType] = unicode_literal
        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        if self._transactional:
            # PEP-249 requires autocommit to be initially off
            self.autocommit(False)
        self.messages = []
コード例 #16
0
    def __init__(self, *args, **kwargs):
        """
        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.
        #--------------------------------------------------------------------------------------
        host:               string, host to connect
        user:               string, user to connect as
        passwd:             string, password to use
        db:                 string, database to use
        port:               integer, TCP/IP port to connect to
        unix_socket:        string, location of unix_socket to use
        conv:               conversion dictionary, see MySQLdb.converters
        connect_timeout:    number of seconds to wait before the connection attempt fails.
        compress:           if set, compression is enabled
        named_pipe:         if set, a named pipe is used to connect (Windows only)
        init_command:       command which is run once the connection is created
        read_default_file:  file from which default client values are read
        read_default_group: configuration group to use from the default file
        cursorclass:        class object, used to create cursors (keyword only)
        use_unicode:        If True, text-like columns are returned as unicode objects
                            using the connection's character set.  Otherwise, text-like
                            columns are returned as strings.  columns are returned as
                            normal strings. Unicode objects will always be encoded to
                            the connection's character set regardless of this setting.
        
        charset:            If supplied, the connection character set will be changed
                            to this character set (MySQL-4.1 and newer). This implies
                            use_unicode=True.

        sql_mode:           If supplied, the session SQL mode will be changed to this
                            setting (MySQL-4.1 and newer). For more details and legal
                            values, see the MySQL documentation.
          
        client_flag:        integer, flags to use or 0 (see MySQL docs or constants/CLIENTS.py)

        ssl:                dictionary or mapping, contains SSL connection parameters;
                            see the MySQL documentation for more details
                            (mysql_ssl_set()).  If this is set, and the client does not
                            support SSL, NotSupportedError will be raised.

        local_infile:       integer, non-zero enables LOAD LOCAL INFILE; zero disables
        #--------------------------------------------------------------------------------------
        
        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.
        """
        self._myfd          = self.fd
        
        from constants import CLIENT, FIELD_TYPE
        from converters import conversions

        conv,kwargs2 = conversions,kwargs.copy()
        
        if kwargs.has_key('conv'):  conv = kwargs['conv']

        conv2 = {}
        for k, v in conv.items():
            if isinstance(k, int) and isinstance(v, list):
                conv2[k] = v[:]
            else:   conv2[k] = v
        kwargs2['conv'] = conv2

        self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor)
        charset = kwargs2.pop('charset', '')

        if charset:     use_unicode = True
        else:           use_unicode = False
        
        use_unicode     = kwargs2.pop('use_unicode', use_unicode)
        sql_mode        = kwargs2.pop('sql_mode', '')
        client_version  = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ])
        #
        client_flag     = kwargs.get('client_flag', 0)
        if client_version >= (4, 1):    client_flag |= CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):    client_flag |= CLIENT.MULTI_RESULTS
        kwargs2['client_flag'] = client_flag


        #
        #
        super(Connection, self).__init__(*args, **kwargs2)
        self.encoders = dict([ (k, v) for k, v in conv.items()  if type(k) is not int ])
        
        self._server_version = tuple([ numeric_part(n) for n in self.get_server_info().split('.')[:2] ])

        db = proxy(self)
        def _get_string_literal():
            def string_literal(obj, dummy=None):
                return db.string_literal(obj)
            return string_literal

        def _get_unicode_literal():
            def unicode_literal(u, dummy=None):
                return db.literal(u.encode(unicode_literal.charset))
            return unicode_literal

        def _get_string_decoder():
            def string_decoder(s):
                return s.decode(string_decoder.charset)
            return string_decoder
        
        string_literal       = _get_string_literal()
        self.unicode_literal = unicode_literal = _get_unicode_literal()
        self.string_decoder  = string_decoder  = _get_string_decoder()
        #--------charset
        if not charset:     charset = self.character_set_name()
        self.set_character_set(charset)
        #--------sql-mode
        if sql_mode:    self.set_sql_mode(sql_mode)

        if use_unicode:
            self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
            self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
            self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))

        self.encoders[types.StringType] = string_literal
        self.encoders[types.UnicodeType] = unicode_literal
        self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
        
        # PEP-249 requires autocommit to be initially off
        if self._transactional:     self.autocommit(False)
        self.messages = []
        
        #------------------------------------------------Royce
        #
        self._orig_query    = super(Connection,self).query
        self.query          = self._async_query
        #
        self._orig_ping     = super(Connection,self).ping
        self.ping           = self._async_ping
        #
        self._wait_channel  = stackless.channel()
        self._wait_channel.preference = 1
        self._query_channel = stackless.channel()
        self._release_wait(0,bInitial = True)
        self._waitings      = {}
コード例 #17
0
ファイル: connection.py プロジェクト: edelooff/newWeb
    def __init__(self, user, passwd, *args, **kwargs):
        """Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.

    Arguments:
      user:               string, user to connect as.
      passwd:             string, password to use.
      db:                 string, database to use. Default same as user.
      host:               string, host to connect to. Default 'localhost'.
      port:               integer, TCP/IP port to connect to.
      unix_socket:        string, location of unix_socket to use.
      conv:               conversion dictionary, see converters module.
      connect_timeout:    number of seconds to wait before the connection
                          attempt fails.
      compress:           bool, enable compression. Default False
      named_pipe:         if set, a named pipe is used to connect (Windows only)
      init_command:       command which is run once the connection is created
      read_default_file:  file from which default client values are read
      read_default_group: configuration group to use from the default file
      use_unicode:        If True, text-like columns are returned as unicode
                          objects using the connection's character set.
                          Otherwise, text-like columns are returned as strings.
                          Columns are returned as normal strings. Unicode
                          objects will always be encoded to the connection's
                          character set regardless of this setting.
      charset:            If supplied, the connection character set will be
                          changed to this character set (MySQL-4.1 and newer).
                          This enforces use_unicode=True.
      sql_mode:           If supplied, the session SQL mode will be changed to
                          this setting (MySQL-4.1 and newer). For more details
                          and legal values, see the MySQL documentation.
      client_flag:        integer, flags to use or 0.
                          (see MySQL docs or constants/CLIENTS.py)
      ssl:                dictionary or mapping, contains SSL connection
                          parameters; see the MySQL documentation for more
                          details (mysql_ssl_set()).  If this is set, and the
                          client does not support SSL, NotSupportedError will
                          be raised.
      local_infile:       bool, True enables LOAD LOCAL INFILE, False disables.
                          Default False

    There are a number of undocumented, non-standard arguments. See the
    documentation for the MySQL C API for some hints on what they do.
    """
        # Counters, transaction lock & timer
        self.counter_transactions = 0
        self.counter_queries = 0
        self.queries = []
        self.transaction_timer = None
        self.lock = threading.Lock()

        # _mysql connect args mapping
        kwargs['user'] = user
        kwargs['passwd'] = passwd
        kwargs['host'] = kwargs.get('host', 'localhost')
        kwargs['db'] = kwargs.get('db', user)
        self.logger = logging.getLogger('mysql_%s' % kwargs['db'])
        if kwargs.pop('debug', False):
            self.debug = True
            self.logger.setLevel(logging.DEBUG)
        else:
            self.debug = False
            self.logger.setLevel(logging.WARNING)
        if kwargs.pop('disable_log', False):
            self.logger.disable_logger = True

        self.encoders = {}
        converts = {}
        for key, value in converters.CONVERSIONS.iteritems():
            if not isinstance(key, int):
                self.encoders[key] = value
            else:
                if isinstance(value, list):
                    converts[key] = value[:]
                else:
                    converts[key] = value
        kwargs.setdefault('conv', {}).update(converts)

        autocommit = kwargs.pop('autocommit', None)
        charset = kwargs.pop('charset', 'utf8')
        sql_mode = kwargs.pop('sql_mode', None)
        use_unicode = kwargs.pop('use_unicode', False) or bool(charset)

        client_version = tuple(
            map(int,
                _mysql.get_client_info().split('.')[:2]))
        kwargs.setdefault('client_flag', 0)
        if client_version >= (4, 1):
            kwargs['client_flag'] |= constants.CLIENT.MULTI_STATEMENTS
        if client_version >= (5, 0):
            kwargs['client_flag'] |= constants.CLIENT.MULTI_RESULTS

        # Done redefining variables for initialization. Engage _mysql!
        super(Connection, self).__init__(*args, **kwargs)

        self.server_version = tuple(
            map(int,
                self.get_server_info().split('.')[:2]))
        if sql_mode:
            self.SetSqlMode(sql_mode)

        # The following voodoo is necssary to avoid double references that would
        # prevent a connection object from being finalized and collected properly.
        db = weakref.proxy(self)

        def _GetStringLiteral():
            def StringLiteral(string, _dummy=None):
                """Returns the SQL literal (safe) for the given string."""
                return db.string_literal(string)

            return StringLiteral

        def _GetUnicodeLiteral():
            def UnicodeLiteral(u_string, _dummy=None):
                """Returns the SQL (safe) literal for the given unicode object."""
                return db.EscapeValues(u_string.encode(db.charset))

            return UnicodeLiteral

        def _GetStringDecoder():
            def StringDecoder(string):
                """Returns the unicode codepoints for an encoded bytestream."""
                return string.decode(db.charset)

            return StringDecoder

        self.string_decoder = _GetStringDecoder()
        self.encoders[str] = _GetStringLiteral()
        self.encoders[unicode] = self.unicode_literal = _GetUnicodeLiteral()

        if use_unicode:
            decoder = None, self.string_decoder
            self.converter[constants.FIELD_TYPE.STRING].append(decoder)
            self.converter[constants.FIELD_TYPE.VAR_STRING].append(decoder)
            self.converter[constants.FIELD_TYPE.VARCHAR].append(decoder)
            self.converter[constants.FIELD_TYPE.BLOB].append(decoder)
        self._charset = None
        self.charset = charset or self.character_set_name()

        self.transactional = bool(self.server_capabilities
                                  & constants.CLIENT.TRANSACTIONS)
        self._autocommit = None
        if autocommit is not None:
            self.autocommit = autocommit
        else:
            self.autocommit = not self.transactional