Commits

Sarah Mount  committed b07596c

Moved mysql package, in preparation for major MVC refactoring

  • Participants
  • Parent commits 515cc49

Comments (0)

Files changed (61)

File open-ihm/data/GenericDBOP.py

 from data.config import Config
-import data.mysql.connector 
+import includes.mysql.connector as connector
 
 class GenericDBOP:
 	def __init__(self,query):
 		# connect to mysql database
 		self.config = Config.dbinfo().copy()        	
-		self.db = data.mysql.connector.Connect(**self.config)
+		self.db = connector.Connect(**self.config)
         	self.cursor = self.db.cursor()		
 		self.sqlquery = query
 	
 
         def runSelectQuery(self):	
         	#connect to mysql database
-        	db = data.mysql.connector.Connect(**self.config)
+        	db = connector.Connect(**self.config)
         	cursor = db.cursor()
 		
 		cursor.execute(self.sqlquery)
 	
 	def runUpdateQuery(self):	
         	#connect to mysql database
-        	db = data.mysql.connector.Connect(**self.config)
+        	db = connector.Connect(**self.config)
         	cursor = db.cursor()
         	
 		# execute query and commit changes

File open-ihm/data/config.py

 class Config(object):
     """ Configures the mysql database connector which is then called as below:
     
-        mysql.connector.Connect(**Config.dbinfo())
+        includes.mysql.connector.Connect(**Config.dbinfo())
     """
     
     HOST = 'localhost'

File open-ihm/data/database.py

 #-------------------------------------------------------------------
 
 from config import Config
-import mysql.connector 
+import includes.mysql.connector as connector
 
 class Database:
     def __init__(self):
         
     def open(self):
         ''' Open a connection to the database'''
-        self.db = mysql.connector.Connect(**self.config)             
+        self.db = connector.Connect(**self.config)             
         self.cursor = self.db.cursor()
         
     def close(self):

File open-ihm/data/databaseinitialiser.py

-from mysql.connector import Connect
-from mysql.connector import errors
+from includes.mysql.connector import Connect
+from includes.mysql.connector import errors
 
 class DbConfig(object):
      """ Configures the mysql database connector which is then called as below:

File open-ihm/data/mysql/__init__.py

Empty file removed.

File open-ihm/data/mysql/connector/__init__.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""
-MySQL Connector/Python - MySQL drive written in Python
-"""
-
-# Python Db API v2
-apilevel = '2.0'
-threadsafety = 1
-paramstyle = 'pyformat'
-
-# Read the version from an generated file
-import _version
-__version__ = _version.version
-
-from mysql import MySQL
-from errors import *
-from constants import FieldFlag, FieldType, CharacterSet,\
-    RefreshOption, ClientFlag
-from dbapi import *
-
-def Connect(*args, **kwargs):
-    """Shortcut for creating a mysql.MySQL object."""
-    return MySQL(*args, **kwargs)
-connect = Connect
-
-__all__ = [
-    'MySQL', 'Connect',
-    
-    # Some useful constants
-    'FieldType','FieldFlag','ClientFlag','CharacterSet','RefreshOption',
-
-    # Error handling
-    'Error','Warning',
-    'InterfaceError','DatabaseError',
-    'NotSupportedError','DataError','IntegrityError','ProgrammingError',
-    'OperationalError','InternalError',
-    
-    # DBAPI PEP 249 required exports
-    'connect','apilevel','threadsafety','paramstyle',
-    'Date', 'Time', 'Timestamp', 'Binary',
-    'DateFromTicks', 'DateFromTicks', 'TimestampFromTicks',
-    'STRING', 'BINARY', 'NUMBER',
-    'DATETIME', 'ROWID',
-    ]

File open-ihm/data/mysql/connector/_version.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""Holds version of MySQL Connector/Python
-"""
-
-# Next line is generated
-version = (0, 1, 3, 'devel', '')

File open-ihm/data/mysql/connector/connection.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""Implementing communication to MySQL servers
-"""
-
-import socket
-import os
-
-import protocol
-import errors
-from constants import CharacterSet
-
-class MySQLBaseConnection(object):
-    """Base class for MySQL Connections subclasses.
-    
-    Should not be used directly but overloaded, changing the
-    open_connection part. Examples over subclasses are
-      MySQLTCPConnection
-      MySQLUNIXConnection
-    """
-    def __init__(self, prtcls=None):
-        self.sock = None # holds the socket connection
-        self.connection_timeout = None
-        self.protocol = None
-        self.socket_flags = 0
-        try:
-            self.protocol = prtcls(self)
-        except:
-            self.protocol = protocol.MySQLProtocol(self)
-        self._set_socket_flags()
-        
-    def open_connection(self):
-        pass
-    
-    def close_connection(self):
-        try:
-            self.sock.close()
-        except:
-            pass
-    
-    def get_address(self):
-        pass
-    
-    def do_handshake(self):
-        buf = self.recv()[0]
-        try:
-            self.protocol.handle_handshake(buf)
-        except:
-            raise errors.InterfaceError(errno=2012)
-
-    def send(self, buf):
-        """
-        Send packets using the socket to the server.
-        """
-        pktlen = len(buf)
-        try:
-            while pktlen:
-                pktlen -= self.sock.send(buf)
-        except Exception, e:
-            raise errors.OperationalError('%s' % e)
-
-    def recv(self):
-        """
-        Receive packets using the socket from the server.
-        """
-        try:
-            header = self.sock.recv(4, self.socket_flags)
-            (pktsize, pktnr) = self.protocol.handle_header(header)
-            buf = header + self.sock.recv(pktsize, self.socket_flags)
-            self.protocol.is_error(buf)
-        except socket.error, e:
-            raise errors.InterfaceError(errno=2055,
-                values=(self.get_address(),e.errno))
-        except:
-            raise
-
-        return (buf, pktsize, pktnr)
-
-    def set_protocol(self, prtcls):
-        try:
-            self.protocol = prtcls(self, self.protocol.handshake)
-        except:
-            self.protocol = protocol.MySQLProtocol(self)
-    
-    def set_connection_timeout(self, timeout):
-        self.connection_timeout = timeout
-
-    def _set_socket_flags(self, flags=None):
-        self.socket_flags = 0
-        if flags is None:
-            if os.name == 'nt':
-                flags = 0
-            else:
-                flags = socket.MSG_WAITALL
-                
-        if flags is not None:
-            self.socket_flags = flags
-    
-
-class MySQLUnixConnection(MySQLBaseConnection):
-    """Opens a connection through the UNIX socket of the MySQL Server."""
-    
-    def __init__(self, prtcls=None,unix_socket='/tmp/mysql.sock'):
-        MySQLBaseConnection.__init__(self, prtcls=prtcls)
-        self.unix_socket = unix_socket
-        self.socket_flags = socket.MSG_WAITALL
-    
-    def get_address(self):
-        return self.unix_socket
-        
-    def open_connection(self):
-        """Opens a UNIX socket and checks the MySQL handshake."""
-        try:
-            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-            self.sock.settimeout(self.connection_timeout)
-            self.sock.connect(self.unix_socket)
-        except socket.error, e:
-            raise errors.InterfaceError(errno=2002,
-                values=(self.get_address(),e.errno or e))
-        except StandardError, e:
-            raise errors.InterfaceError('%s' % e)
-        
-        self.do_handshake()
-
-class MySQLTCPConnection(MySQLBaseConnection):
-    """Opens a TCP connection to the MySQL Server."""
-    
-    def __init__(self, prtcls=None, host='127.0.0.1', port=3306):
-        MySQLBaseConnection.__init__(self, prtcls=prtcls)
-        self.server_host = host
-        self.server_port = port
-    
-    def get_address(self):
-        return "%s:%s" % (self.server_host,self.server_port)
-        
-    def open_connection(self):
-        """Opens a TCP Connection and checks the MySQL handshake."""
-        try:
-            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-            self.sock.settimeout(self.connection_timeout)
-            self.sock.connect( (self.server_host, self.server_port) )
-        except socket.error, e:
-            raise errors.InterfaceError(errno=2003,
-                values=(self.get_address(),e.errno or e))
-        except StandardError, e:
-            raise errors.InterfaceError('%s' % e)
-        except:
-            raise
-        
-        self.do_handshake()
-        

File open-ihm/data/mysql/connector/constants.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""Various MySQL constants and character sets
-"""
-
-from errors import ProgrammingError
-
-class _constants(object):
-    
-    prefix = ''
-    desc = {}
-    
-    def __new__(cls):
-        raise TypeError, "Can not instanciate from %s" % cls.__name__
-        
-    @classmethod
-    def get_desc(cls,name):
-        try:
-            return cls.desc[name][1]
-        except:
-            return None
-            
-    @classmethod
-    def get_info(cls,n):
-        try:
-            res = {}
-            for v in cls.desc.items():
-                res[v[1][0]] = v[0]
-            return res[n]
-        except:
-            return None
-    
-    @classmethod
-    def get_full_info(cls):
-        res = ()
-        try:
-            res = ["%s : %s" % (k,v[1]) for k,v in cls.desc.items()]
-        except StandardError, e:
-            res = ('No information found in constant class.%s' % e)
-        
-        return res
-
-class _constantflags(_constants):
-    
-    @classmethod
-    def get_bit_info(cls, v):
-        """Get the name of all bits set
-        
-        Returns a list of strings."""
-        res = []
-        for name,d in cls.desc.items():
-            if v & d[0]:
-                res.append(name)
-        return res
-    
-class FieldType(_constants):
-    
-    prefix = 'FIELD_TYPE_'
-    DECIMAL     = 0x00
-    TINY        = 0x01
-    SHORT       = 0x02
-    LONG        = 0x03
-    FLOAT       = 0x04
-    DOUBLE      = 0x05
-    NULL        = 0x06
-    TIMESTAMP   = 0x07
-    LONGLONG    = 0x08
-    INT24       = 0x09
-    DATE        = 0x0a
-    TIME        = 0x0b
-    DATETIME    = 0x0c
-    YEAR        = 0x0d
-    NEWDATE     = 0x0e
-    VARCHAR     = 0x0f
-    BIT         = 0x10
-    NEWDECIMAL  = 0xf6
-    ENUM        = 0xf7
-    SET         = 0xf8
-    TINY_BLOB   = 0xf9
-    MEDIUM_BLOB = 0xfa
-    LONG_BLOB   = 0xfb
-    BLOB        = 0xfc
-    VAR_STRING  = 0xfd
-    STRING      = 0xfe
-    GEOMETRY    = 0xff
-    
-    desc = {
-        'DECIMAL':       (0x00, 'DECIMAL'),
-        'TINY':          (0x01, 'TINY'),
-        'SHORT':         (0x02, 'SHORT'),
-        'LONG':          (0x03, 'LONG'),
-        'FLOAT':         (0x04, 'FLOAT'),
-        'DOUBLE':        (0x05, 'DOUBLE'),
-        'NULL':          (0x06, 'NULL'),
-        'TIMESTAMP':     (0x07, 'TIMESTAMP'),
-        'LONGLONG':      (0x08, 'LONGLONG'),
-        'INT24':         (0x09, 'INT24'),
-        'DATE':          (0x0a, 'DATE'),
-        'TIME':          (0x0b, 'TIME'),
-        'DATETIME':      (0x0c, 'DATETIME'),
-        'YEAR':          (0x0d, 'YEAR'),
-        'NEWDATE':       (0x0e, 'NEWDATE'),
-        'VARCHAR':       (0x0f, 'VARCHAR'),
-        'BIT':           (0x10, 'BIT'),
-        'NEWDECIMAL':    (0xf6, 'NEWDECIMAL'),
-        'ENUM':          (0xf7, 'ENUM'),
-        'SET':           (0xf8, 'SET'),
-        'TINY_BLOB':     (0xf9, 'TINY_BLOB'),
-        'MEDIUM_BLOB':   (0xfa, 'MEDIUM_BLOB'),
-        'LONG_BLOB':     (0xfb, 'LONG_BLOB'),
-        'BLOB':          (0xfc, 'BLOB'),
-        'VAR_STRING':    (0xfd, 'VAR_STRING'),
-        'STRING':        (0xfe, 'STRING'),
-        'GEOMETRY':      (0xff, 'GEOMETRY'),
-    }
-    
-    @classmethod
-    def get_string_types(cls):
-        return [
-            cls.VARCHAR,
-            cls.ENUM,
-            cls.VAR_STRING, cls.STRING,
-            ]
-    
-    @classmethod
-    def get_binary_types(cls):
-        return [
-            cls.TINY_BLOB, cls.MEDIUM_BLOB,
-            cls.LONG_BLOB, cls.BLOB,
-            ]
-    
-    @classmethod
-    def get_number_types(cls):
-        return [
-            cls.DECIMAL, cls.NEWDECIMAL,
-            cls.TINY, cls.SHORT, cls.LONG,
-            cls.FLOAT, cls.DOUBLE,
-            cls.LONGLONG, cls.INT24,
-            cls.BIT,
-            cls.YEAR,
-            ]
-    
-    @classmethod
-    def get_timestamp_types(cls):
-        return [
-            cls.DATETIME, cls.TIMESTAMP,
-            ]
-
-class FieldFlag(_constantflags):
-    """
-    Field flags as found in MySQL sources mysql-src/include/mysql_com.h
-    """
-    _prefix = ''
-    NOT_NULL             = 1 <<  0
-    PRI_KEY              = 1 <<  1
-    UNIQUE_KEY           = 1 <<  2
-    MULTIPLE_KEY         = 1 <<  3
-    BLOB                 = 1 <<  4
-    UNSIGNED             = 1 <<  5
-    ZEROFILL             = 1 <<  6
-    BINARY               = 1 <<  7
-
-    ENUM                 = 1 <<  8
-    AUTO_INCREMENT       = 1 <<  9
-    TIMESTAMP            = 1 << 10
-    SET                  = 1 << 11
-
-    NO_DEFAULT_VALUE     = 1 << 12
-    ON_UPDATE_NOW        = 1 << 13
-    NUM                  = 1 << 14
-    PART_KEY             = 1 << 15
-    GROUP                = 1 << 14    # SAME AS NUM !!!!!!!????
-    UNIQUE               = 1 << 16
-    BINCMP               = 1 << 17
-
-    GET_FIXED_FIELDS     = 1 << 18
-    FIELD_IN_PART_FUNC   = 1 << 19
-    FIELD_IN_ADD_INDEX   = 1 << 20
-    FIELD_IS_RENAMED     = 1 << 21
-
-    desc = {
-        'NOT_NULL':             (1 <<  0, "Field can't be NULL"),
-        'PRI_KEY':              (1 <<  1, "Field is part of a primary key"),
-        'UNIQUE_KEY':           (1 <<  2, "Field is part of a unique key"),
-        'MULTIPLE_KEY':         (1 <<  3, "Field is part of a key"),
-        'BLOB':                 (1 <<  4, "Field is a blob"),
-        'UNSIGNED':             (1 <<  5, "Field is unsigned"),
-        'ZEROFILL':             (1 <<  6, "Field is zerofill"),
-        'BINARY':               (1 <<  7, "Field is binary  "),
-        'ENUM':                 (1 <<  8, "field is an enum"),
-        'AUTO_INCREMENT':       (1 <<  9, "field is a autoincrement field"),
-        'TIMESTAMP':            (1 << 10, "Field is a timestamp"),
-        'SET':                  (1 << 11, "field is a set"),
-        'NO_DEFAULT_VALUE':     (1 << 12, "Field doesn't have default value"),
-        'ON_UPDATE_NOW':        (1 << 13, "Field is set to NOW on UPDATE"),
-        'NUM':                  (1 << 14, "Field is num (for clients)"),
-
-        'PART_KEY':             (1 << 15, "Intern; Part of some key"),
-        'GROUP':                (1 << 14, "Intern: Group field"),   # Same as NUM
-        'UNIQUE':               (1 << 16, "Intern: Used by sql_yacc"),
-        'BINCMP':               (1 << 17, "Intern: Used by sql_yacc"),
-        'GET_FIXED_FIELDS':     (1 << 18, "Used to get fields in item tree"),
-        'FIELD_IN_PART_FUNC':   (1 << 19, "Field part of partition func"),
-        'FIELD_IN_ADD_INDEX':        (1 << 20, "Intern: Field used in ADD INDEX"),
-        'FIELD_IS_RENAMED':          (1 << 21, "Intern: Field is being renamed"),
-    }
-        
-class ServerCmd(_constants):
-    _prefix = 'COM_'
-    SLEEP           =  0
-    QUIT            =  1
-    INIT_DB         =  2 
-    QUERY           =  3
-    FIELD_LIST      =  4
-    CREATE_DB       =  5
-    DROP_DB         =  6
-    REFRESH         =  7
-    SHUTDOWN        =  8
-    STATISTICS      =  9
-    PROCESS_INFO    = 10
-    CONNECT         = 11
-    PROCESS_KILL    = 12
-    DEBUG           = 13
-    PING            = 14
-    TIME            = 15
-    DELAYED_INSERT  = 16
-    CHANGE_USER     = 17
-    BINLOG_DUMP     = 18
-    TABLE_DUMP      = 19
-    CONNECT_OUT     = 20
-    REGISTER_SLAVE  = 21
-    STMT_PREPARE    = 22
-    STMT_EXECUTE    = 23
-    STMT_SEND_LONG_DATA = 24
-    STMT_CLOSE      = 25
-    STMT_RESET      = 26
-    SET_OPTION      = 27
-    STMT_FETCH      = 28
-    DAEMON          = 29
-
-class ClientFlag(_constantflags):
-    """
-    Client Options as found in the MySQL sources mysql-src/include/mysql_com.h
-    """
-    LONG_PASSWD             = 1 << 0
-    FOUND_ROWS              = 1 << 1
-    LONG_FLAG               = 1 << 2
-    CONNECT_WITH_DB         = 1 << 3
-    NO_SCHEMA               = 1 << 4
-    COMPRESS                = 1 << 5
-    ODBC                    = 1 << 6
-    LOCAL_FILES             = 1 << 7
-    IGNORE_SPACE            = 1 << 8
-    PROTOCOL_41             = 1 << 9
-    INTERACTIVE             = 1 << 10
-    SSL                     = 1 << 11
-    IGNORE_SIGPIPE          = 1 << 12
-    TRANSACTIONS            = 1 << 13
-    RESERVED                = 1 << 14
-    SECURE_CONNECTION       = 1 << 15
-    MULTI_STATEMENTS        = 1 << 16
-    MULTI_RESULTS           = 1 << 17
-    SSL_VERIFY_SERVER_CERT  = 1 << 30
-    REMEMBER_OPTIONS        = 1 << 31
-    
-    desc = {
-        'LONG_PASSWD':        (1 <<  0, 'New more secure passwords'),
-        'FOUND_ROWS':         (1 <<  1, 'Found instead of affected rows'),
-        'LONG_FLAG':          (1 <<  2, 'Get all column flags'),
-        'CONNECT_WITH_DB':    (1 <<  3, 'One can specify db on connect'),
-        'NO_SCHEMA':          (1 <<  4, "Don't allow database.table.column"),
-        'COMPRESS':           (1 <<  5, 'Can use compression protocol'),
-        'ODBC':               (1 <<  6, 'ODBC client'),
-        'LOCAL_FILES':        (1 <<  7, 'Can use LOAD DATA LOCAL'),
-        'IGNORE_SPACE':       (1 <<  8, "Ignore spaces before ''"),
-        'PROTOCOL_41':        (1 <<  9, 'New 4.1 protocol'),
-        'INTERACTIVE':        (1 << 10, 'This is an interactive client'),
-        'SSL':                (1 << 11, 'Switch to SSL after handshake'),
-        'IGNORE_SIGPIPE':     (1 << 12, 'IGNORE sigpipes'),
-        'TRANSACTIONS':       (1 << 13, 'Client knows about transactions'),
-        'RESERVED':           (1 << 14, 'Old flag for 4.1 protocol'),
-        'SECURE_CONNECTION':  (1 << 15, 'New 4.1 authentication'),
-        'MULTI_STATEMENTS':   (1 << 16, 'Enable/disable multi-stmt support'),
-        'MULTI_RESULTS':      (1 << 17, 'Enable/disable multi-results'),
-        'SSL_VERIFY_SERVER_CERT':     (1 << 30, ''),
-        'REMEMBER_OPTIONS':           (1 << 31, ''),
-    }
-    
-    default = [
-        LONG_PASSWD,
-        LONG_FLAG,
-        CONNECT_WITH_DB,
-        PROTOCOL_41,
-        TRANSACTIONS,
-        SECURE_CONNECTION,
-        MULTI_STATEMENTS,
-        MULTI_RESULTS,
-    ]
-
-    @classmethod
-    def get_default(cls):
-        flags = 0
-        for f in cls.default:
-            flags |= f
-        return flags
-
-class ServerFlag(_constantflags):
-    """
-    Server flags as found in the MySQL sources mysql-src/include/mysql_com.h
-    """
-    _prefix = 'SERVER_'
-    STATUS_IN_TRANS             = 1 << 0
-    STATUS_AUTOCOMMIT           = 1 << 1
-    MORE_RESULTS_EXISTS         = 1 << 3
-    QUERY_NO_GOOD_INDEX_USED    = 1 << 4
-    QUERY_NO_INDEX_USED         = 1 << 5
-    STATUS_CURSOR_EXISTS        = 1 << 6
-    STATUS_LAST_ROW_SENT        = 1 << 7
-    STATUS_DB_DROPPED           = 1 << 8
-    STATUS_NO_BACKSLASH_ESCAPES = 1 << 9
-
-    desc = {
-        'SERVER_STATUS_IN_TRANS':            (1 << 0, 'Transaction has started'),
-        'SERVER_STATUS_AUTOCOMMIT':          (1 << 1, 'Server in auto_commit mode'),
-        'SERVER_MORE_RESULTS_EXISTS':        (1 << 3, 'Multi query - next query exists'),
-        'SERVER_QUERY_NO_GOOD_INDEX_USED':   (1 << 4, ''),
-        'SERVER_QUERY_NO_INDEX_USED':        (1 << 5, ''),
-        'SERVER_STATUS_CURSOR_EXISTS':       (1 << 6, ''),
-        'SERVER_STATUS_LAST_ROW_SENT':       (1 << 7, ''),
-        'SERVER_STATUS_DB_DROPPED':          (1 << 8, 'A database was dropped'),
-        'SERVER_STATUS_NO_BACKSLASH_ESCAPES':   (1 << 9, ''),
-    }
-
-class RefreshOption(_constants):
-    """Options used when sending the COM_REFRESH server command."""
-    
-    _prefix = 'REFRESH_'
-    GRANT = 1 << 0
-    LOG = 1 << 1
-    TABLES = 1 << 2
-    HOST = 1 << 3
-    STATUS = 1 << 4
-    THREADS = 1 << 5
-    SLAVE = 1 << 6
-    
-    desc = {
-        'GRANT': (1 << 0, 'Refresh grant tables'),
-        'LOG': (1 << 1, 'Start on new log file'),
-        'TABLES': (1 << 2, 'close all tables'),
-        'HOSTS': (1 << 3, 'Flush host cache'),
-        'STATUS': (1 << 4, 'Flush status variables'),
-        'THREADS': (1 << 5, 'Flush thread cache'),
-        'SLAVE': (1 << 6, 'Reset master info and restart slave thread'),
-    }
-    
-class CharacterSet(_constants):
-    """
-    List of supported character sets with their collations. This maps to the
-    character set we get from the server within the handshake packet.
-    
-    To update this list, use the following query:
-      SELECT ID,CHARACTER_SET_NAME, COLLATION_NAME
-         FROM INFORMATION_SCHEMA.COLLATIONS
-         ORDER BY ID
-    
-    This list is hardcoded because we want to avoid doing each time the above
-    query to get the name of the character set used.
-    """
-    
-    _max_id = 211 # SELECT MAX(ID)+1 FROM INFORMATION_SCHEMA.COLLATIONS
-    
-    @classmethod
-    def _init_desc(cls):
-        if not cls.__dict__.has_key('desc'):
-            
-            # Do not forget to update the tests in test_constants!
-            cls.desc = [ None for i in range(cls._max_id)]
-            cls.desc[1] = ('big5','big5_chinese_ci')
-            cls.desc[2] = ('latin2','latin2_czech_cs')
-            cls.desc[3] = ('dec8','dec8_swedish_ci')
-            cls.desc[4] = ('cp850','cp850_general_ci')
-            cls.desc[5] = ('latin1','latin1_german1_ci')
-            cls.desc[6] = ('hp8','hp8_english_ci')
-            cls.desc[7] = ('koi8r','koi8r_general_ci')
-            cls.desc[8] = ('latin1','latin1_swedish_ci')
-            cls.desc[9] = ('latin2','latin2_general_ci')
-            cls.desc[10] = ('swe7','swe7_swedish_ci')
-            cls.desc[11] = ('ascii','ascii_general_ci')
-            cls.desc[12] = ('ujis','ujis_japanese_ci')
-            cls.desc[13] = ('sjis','sjis_japanese_ci')
-            cls.desc[14] = ('cp1251','cp1251_bulgarian_ci')
-            cls.desc[15] = ('latin1','latin1_danish_ci')
-            cls.desc[16] = ('hebrew','hebrew_general_ci')
-            cls.desc[18] = ('tis620','tis620_thai_ci')
-            cls.desc[19] = ('euckr','euckr_korean_ci')
-            cls.desc[20] = ('latin7','latin7_estonian_cs')
-            cls.desc[21] = ('latin2','latin2_hungarian_ci')
-            cls.desc[22] = ('koi8u','koi8u_general_ci')
-            cls.desc[23] = ('cp1251','cp1251_ukrainian_ci')
-            cls.desc[24] = ('gb2312','gb2312_chinese_ci')
-            cls.desc[25] = ('greek','greek_general_ci')
-            cls.desc[26] = ('cp1250','cp1250_general_ci')
-            cls.desc[27] = ('latin2','latin2_croatian_ci')
-            cls.desc[28] = ('gbk','gbk_chinese_ci')
-            cls.desc[29] = ('cp1257','cp1257_lithuanian_ci')
-            cls.desc[30] = ('latin5','latin5_turkish_ci')
-            cls.desc[31] = ('latin1','latin1_german2_ci')
-            cls.desc[32] = ('armscii8','armscii8_general_ci')
-            cls.desc[33] = ('utf8','utf8_general_ci')
-            cls.desc[34] = ('cp1250','cp1250_czech_cs')
-            cls.desc[35] = ('ucs2','ucs2_general_ci')
-            cls.desc[36] = ('cp866','cp866_general_ci')
-            cls.desc[37] = ('keybcs2','keybcs2_general_ci')
-            cls.desc[38] = ('macce','macce_general_ci')
-            cls.desc[39] = ('macroman','macroman_general_ci')
-            cls.desc[40] = ('cp852','cp852_general_ci')
-            cls.desc[41] = ('latin7','latin7_general_ci')
-            cls.desc[42] = ('latin7','latin7_general_cs')
-            cls.desc[43] = ('macce','macce_bin')
-            cls.desc[44] = ('cp1250','cp1250_croatian_ci')
-            cls.desc[47] = ('latin1','latin1_bin')
-            cls.desc[48] = ('latin1','latin1_general_ci')
-            cls.desc[49] = ('latin1','latin1_general_cs')
-            cls.desc[50] = ('cp1251','cp1251_bin')
-            cls.desc[51] = ('cp1251','cp1251_general_ci')
-            cls.desc[52] = ('cp1251','cp1251_general_cs')
-            cls.desc[53] = ('macroman','macroman_bin')
-            cls.desc[57] = ('cp1256','cp1256_general_ci')
-            cls.desc[58] = ('cp1257','cp1257_bin')
-            cls.desc[59] = ('cp1257','cp1257_general_ci')
-            cls.desc[63] = ('binary','binary')
-            cls.desc[64] = ('armscii8','armscii8_bin')
-            cls.desc[65] = ('ascii','ascii_bin')
-            cls.desc[66] = ('cp1250','cp1250_bin')
-            cls.desc[67] = ('cp1256','cp1256_bin')
-            cls.desc[68] = ('cp866','cp866_bin')
-            cls.desc[69] = ('dec8','dec8_bin')
-            cls.desc[70] = ('greek','greek_bin')
-            cls.desc[71] = ('hebrew','hebrew_bin')
-            cls.desc[72] = ('hp8','hp8_bin')
-            cls.desc[73] = ('keybcs2','keybcs2_bin')
-            cls.desc[74] = ('koi8r','koi8r_bin')
-            cls.desc[75] = ('koi8u','koi8u_bin')
-            cls.desc[77] = ('latin2','latin2_bin')
-            cls.desc[78] = ('latin5','latin5_bin')
-            cls.desc[79] = ('latin7','latin7_bin')
-            cls.desc[80] = ('cp850','cp850_bin')
-            cls.desc[81] = ('cp852','cp852_bin')
-            cls.desc[82] = ('swe7','swe7_bin')
-            cls.desc[83] = ('utf8','utf8_bin')
-            cls.desc[84] = ('big5','big5_bin')
-            cls.desc[85] = ('euckr','euckr_bin')
-            cls.desc[86] = ('gb2312','gb2312_bin')
-            cls.desc[87] = ('gbk','gbk_bin')
-            cls.desc[88] = ('sjis','sjis_bin')
-            cls.desc[89] = ('tis620','tis620_bin')
-            cls.desc[90] = ('ucs2','ucs2_bin')
-            cls.desc[91] = ('ujis','ujis_bin')
-            cls.desc[92] = ('geostd8','geostd8_general_ci')
-            cls.desc[93] = ('geostd8','geostd8_bin')
-            cls.desc[94] = ('latin1','latin1_spanish_ci')
-            cls.desc[95] = ('cp932','cp932_japanese_ci')
-            cls.desc[96] = ('cp932','cp932_bin')
-            cls.desc[97] = ('eucjpms','eucjpms_japanese_ci')
-            cls.desc[98] = ('eucjpms','eucjpms_bin')
-            cls.desc[128] = ('ucs2','ucs2_unicode_ci')
-            cls.desc[129] = ('ucs2','ucs2_icelandic_ci')
-            cls.desc[130] = ('ucs2','ucs2_latvian_ci')
-            cls.desc[131] = ('ucs2','ucs2_romanian_ci')
-            cls.desc[132] = ('ucs2','ucs2_slovenian_ci')
-            cls.desc[133] = ('ucs2','ucs2_polish_ci')
-            cls.desc[134] = ('ucs2','ucs2_estonian_ci')
-            cls.desc[135] = ('ucs2','ucs2_spanish_ci')
-            cls.desc[136] = ('ucs2','ucs2_swedish_ci')
-            cls.desc[137] = ('ucs2','ucs2_turkish_ci')
-            cls.desc[138] = ('ucs2','ucs2_czech_ci')
-            cls.desc[139] = ('ucs2','ucs2_danish_ci')
-            cls.desc[140] = ('ucs2','ucs2_lithuanian_ci')
-            cls.desc[141] = ('ucs2','ucs2_slovak_ci')
-            cls.desc[142] = ('ucs2','ucs2_spanish2_ci')
-            cls.desc[143] = ('ucs2','ucs2_roman_ci')
-            cls.desc[144] = ('ucs2','ucs2_persian_ci')
-            cls.desc[145] = ('ucs2','ucs2_esperanto_ci')
-            cls.desc[146] = ('ucs2','ucs2_hungarian_ci')
-            cls.desc[192] = ('utf8','utf8_unicode_ci')
-            cls.desc[193] = ('utf8','utf8_icelandic_ci')
-            cls.desc[194] = ('utf8','utf8_latvian_ci')
-            cls.desc[195] = ('utf8','utf8_romanian_ci')
-            cls.desc[196] = ('utf8','utf8_slovenian_ci')
-            cls.desc[197] = ('utf8','utf8_polish_ci')
-            cls.desc[198] = ('utf8','utf8_estonian_ci')
-            cls.desc[199] = ('utf8','utf8_spanish_ci')
-            cls.desc[200] = ('utf8','utf8_swedish_ci')
-            cls.desc[201] = ('utf8','utf8_turkish_ci')
-            cls.desc[202] = ('utf8','utf8_czech_ci')
-            cls.desc[203] = ('utf8','utf8_danish_ci')
-            cls.desc[204] = ('utf8','utf8_lithuanian_ci')
-            cls.desc[205] = ('utf8','utf8_slovak_ci')
-            cls.desc[206] = ('utf8','utf8_spanish2_ci')
-            cls.desc[207] = ('utf8','utf8_roman_ci')
-            cls.desc[208] = ('utf8','utf8_persian_ci')
-            cls.desc[209] = ('utf8','utf8_esperanto_ci')
-            cls.desc[210] = ('utf8','utf8_hungarian_ci')
-
-    @classmethod
-    def get_info(cls,setid):
-        """Returns information about the charset for given MySQL ID."""
-        cls._init_desc()
-        res = ()
-        errmsg =  "Character set with id '%d' unsupported." % (setid)
-        try:
-            res = cls.desc[setid]
-        except:
-            raise ProgrammingError, errmsg
-
-        if res is None:
-            raise ProgrammingError, errmsg
-
-        return res
-
-    @classmethod
-    def get_desc(cls,setid):
-        """Returns info string about the charset for given MySQL ID."""
-        res = ()
-        try:
-            res = "%s/%s" % self.get_info(setid)
-        except ProgrammingError, e:
-            raise
-        else:
-            return res
-    
-    @classmethod
-    def get_charset_info(cls, name, collation=None):
-        """Returns information about the charset and optional collation."""
-        cls._init_desc()
-        l = len(cls.desc)
-        errmsg =  "Character set '%s' unsupported." % (name)
-        
-        if collation is None:
-            collation = '%s_general_ci' % (name)
-        
-        # Search the list and return when found
-        idx = 0
-        for info in cls.desc:
-            if info and info[0] == name and info[1] == collation:
-                return (idx,info[0],info[1])
-            idx += 1
-        
-        # If we got here, we didn't find the charset
-        raise ProgrammingError, errmsg
-        
-    @classmethod
-    def get_supported(cls):
-        """Returns a list with names of all supproted character sets."""
-        res = []
-        for info in cls.desc:
-            if info and info[0] not in res:
-                res.append(info[0])
-        return tuple(res)
-
-    

File open-ihm/data/mysql/connector/conversion.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""Converting MySQL and Python types
-"""
-
-import struct
-import datetime
-import time
-from decimal import Decimal
-
-import errors
-from constants import FieldType, FieldFlag
-
-class ConverterBase(object):
-    
-    def __init__(self, charset='utf8', use_unicode=True):
-        self.python_types = None
-        self.mysql_types = None
-        self.set_charset(charset)
-        self.set_unicode(use_unicode)
-        
-    def set_charset(self, charset):
-        if charset is not None:
-            self.charset = charset
-        else:
-            # default to utf8
-            self.charset = 'utf8'
-    
-    def set_unicode(self, value=True):
-        self.use_unicode = value
-    
-    def to_mysql(self, value):
-        return value
-    
-    def to_python(self, vtype, value):
-        return value
-    
-    def escape(self, buf):
-        return buf
-    
-    def quote(self, buf):
-        return str(buf)
-
-class MySQLConverter(ConverterBase):
-    """
-    A converted class grouping:
-     o escape method: for escpaing values send to MySQL
-     o quoting method: for quoting values send to MySQL in statements
-     o conversion mapping: maps Python and MySQL data types to
-       function for converting them.
-       
-    This class should be overloaded whenever one needs differences
-    in how values are to be converted. Each MySQLConnection object
-    has a default_converter property, which can be set like
-      MySQL.converter(CustomMySQLConverter)
-      
-    """
-    def __init__(self, charset=None, use_unicode=True):
-        ConverterBase.__init__(self, charset, use_unicode)
-    
-    def _get_python_mysql(self, t):            
-        # Python types
-        python_types = {
-            int : int,
-            str : self._str_to_mysql,
-            long : long,
-            float : float,
-            unicode : self._unicode_to_mysql,
-            bool : self._bool_to_mysql,
-            type(None) : self._none_to_mysql,
-            datetime.datetime : self._datetime_to_mysql,
-            datetime.date : self._date_to_mysql,
-            datetime.time : self._time_to_mysql,
-            time.struct_time : self._struct_time_to_mysql,
-            datetime.timedelta : self._timedelta_to_mysql,
-            Decimal : self._decimal_to_mysql,
-        }
-        return python_types[t]
-    
-    def _get_mysql_python(self, t):
-        # MySQL types
-        mysql_types = {
-            FieldType.TINY : self._int,
-            FieldType.SHORT : self._int,
-            FieldType.INT24 : self._int,
-            FieldType.LONG : self._long,
-            FieldType.LONGLONG : self._long,
-            FieldType.FLOAT : self._float,
-            FieldType.DOUBLE : self._float,
-            FieldType.DECIMAL : self._decimal,
-            FieldType.NEWDECIMAL : self._decimal,
-            FieldType.VAR_STRING : self._STRING_to_python,
-            FieldType.STRING : self._STRING_to_python,
-            FieldType.SET : self._SET_to_python,
-            FieldType.TIME : self._TIME_to_python,
-            FieldType.DATE : self._DATE_to_python,
-            FieldType.NEWDATE : self._DATE_to_python,
-            FieldType.DATETIME : self._DATETIME_to_python,
-            FieldType.TIMESTAMP : self._DATETIME_to_python,
-            FieldType.BLOB : self._BLOB_to_python,
-            FieldType.YEAR: self._YEAR_to_python,
-            FieldType.BIT: self._BIT_to_python,
-        }
-        return mysql_types[t]
-    
-    def escape(self, value):
-        """
-        Escapes special characters as they are expected to by when MySQL
-        receives them.
-        As found in MySQL source mysys/charset.c
-        
-        Returns the value if not a string, or the escaped string.
-        """
-        if value is None:
-            return value
-        elif isinstance(value, (int,float,long,Decimal)):
-            return value
-        res = value
-        res = res.replace('\\','\\\\')
-        res = res.replace('\n','\\n')
-        res = res.replace('\r','\\r')
-        res = res.replace('\047','\134\047') # single quotes
-        res = res.replace('\042','\134\042') # double quotes
-        res = res.replace('\032','\134\032') # for Win32
-        return res
-    
-    def quote(self, buf):
-        """
-        Quote the parameters for commands. General rules:
-          o numbers are returns as str type (because operation expect it)
-          o None is returned as str('NULL')
-          o String are quoted with single quotes '<string>'
-        
-        Returns a string.
-        """
-        if isinstance(buf, (int,float,long,Decimal)):
-            return str(buf)
-        elif isinstance(buf, type(None)):
-            return "NULL"
-        else:
-            # Anything else would be a string
-            return "'%s'" % buf 
-    
-    def to_mysql(self, value):
-        vtype = type(value)
-        return self._get_python_mysql(vtype)(value)
-    
-    def _str_to_mysql(self, value):
-        return str(value)
-        
-    def _unicode_to_mysql(self, value):
-        """
-        Encodes value, a Python unicode string, to whatever the
-        character set for this converter is set too.
-        """
-        return value.encode(self.charset)
-    
-    def _bool_to_mysql(self, value):
-        if value:
-            return 1
-        else:
-            return 0
-        
-    def _none_to_mysql(self, value):
-        """
-        This would return what None would be in MySQL, but instead we
-        leave it None and return it right away. The actual convertion
-        from None to NULL happens in the quoting functionality.
-        
-        Return None.
-        """
-        return None
-        
-    def _datetime_to_mysql(self, value):
-        """
-        Converts a datetime instance to a string suitable for MySQL.
-        The returned string has format: %Y-%m-%d %H:%M:%S
-        
-        If the instance isn't a datetime.datetime type, it return None.
-        
-        Returns a string.
-        """
-        return '%d-%02d-%02d %02d:%02d:%02d' % (
-            value.year, value.month, value.day,
-            value.hour, value.minute, value.second)
-    
-    def _date_to_mysql(self, value):
-        """
-        Converts a date instance to a string suitable for MySQL.
-        The returned string has format: %Y-%m-%d
-        
-        If the instance isn't a datetime.date type, it return None.
-        
-        Returns a string.
-        """
-        return '%d-%02d-%02d' % (value.year, value.month, value.day)
-    
-    def _time_to_mysql(self, value):
-        """
-        Converts a time instance to a string suitable for MySQL.
-        The returned string has format: %H:%M:%S
-        
-        If the instance isn't a datetime.time type, it return None.
-        
-        Returns a string or None when not valid.
-        """
-        return value.strftime('%H:%M:%S')
-    
-    def _struct_time_to_mysql(self, value):
-        """
-        Converts a time.struct_time sequence to a string suitable
-        for MySQL.
-        The returned string has format: %Y-%m-%d %H:%M:%S
-        
-        Returns a string or None when not valid.
-        """
-        return time.strftime('%Y-%m-%d %H:%M:%S',value)
-        
-    def _timedelta_to_mysql(self, value):
-        """
-        Converts a timedelta instance to a string suitable for MySQL.
-        The returned string has format: %H:%M:%S
-
-        Returns a string.
-        """
-        (hours, r) = divmod(value.seconds, 3600)
-        (mins, secs) = divmod(r, 60)
-        hours = hours + (value.days * 24)
-        return '%02d:%02d:%02d' % (hours,mins,secs)
-    
-    def _decimal_to_mysql(self, value):
-        """
-        Converts a decimal.Decimal instance to a string suitable for
-        MySQL.
-        
-        Returns a string or None when not valid.
-        """
-        if isinstance(value, Decimal):
-            return str(value)
-        
-        return None
-         
-    def to_python(self, flddsc, value):
-        """
-        Converts a given value coming from MySQL to a certain type in Python.
-        The flddsc contains additional information for the field in the
-        table. It's an element from MySQLCursor.description.
-        
-        Returns a mixed value.
-        """
-        res = value
-        
-        if value == '\x00' and flddsc[1] != FieldType.BIT:
-            # Don't go further when we hit a NULL value
-            return None
-        if value is None:
-            return None
-            
-        try:
-            res = self._get_mysql_python(flddsc[1])(value, flddsc)
-        except KeyError:
-            # If one type is not defined, we just return the value as str
-            return str(value)
-        except ValueError, e:
-            raise ValueError, "%s (field %s)" % (e, flddsc[0])
-        except TypeError, e:
-            raise TypeError, "%s (field %s)" % (e, flddsc[0])
-        except:
-            raise
-        
-        return res
-    
-    def _float(self, v, desc=None):
-        """
-        Returns v as float type.
-        """
-        return float(v)
-    
-    def _int(self, v, desc=None):
-        """
-        Returns v as int type.
-        """
-        return int(v)
-        
-    def _long(self, v, desc=None):
-        """
-        Returns v as long type.
-        """
-        return int(v)
-    
-    def _decimal(self, v, desc=None):
-        """
-        Returns v as a decimal.Decimal.
-        """
-        return Decimal(v)
-        
-    def _str(self, v, desc=None):
-        """
-        Returns v as str type.
-        """
-        return str(v)
-    
-    def _BIT_to_python(self, v, dsc=None):
-        """Returns BIT columntype as integer"""
-        s = v
-        if len(s) < 8:
-            s = '\x00'*(8-len(s)) + s
-        return struct.unpack('>Q', s)[0]
-    
-    def _DATE_to_python(self, v, dsc=None):
-        """
-        Returns DATE column type as datetime.date type.
-        """
-        pv = None
-        try:
-            pv = datetime.date(*[ int(s) for s in v.split('-')])
-        except ValueError:
-            return None
-        else:
-            return pv
-            
-    def _TIME_to_python(self, v, dsc=None):
-        """
-        Returns TIME column type as datetime.time type.
-        """
-        pv = None
-        try:
-            (h, m, s) = [ int(s) for s in v.split(':')]
-            pv = datetime.timedelta(hours=h,minutes=m,seconds=s)
-        except ValueError:
-            raise ValueError, "Could not convert %s to python datetime.timedelta" % v
-        else:
-            return pv
-            
-    def _DATETIME_to_python(self, v, dsc=None):
-        """
-        Returns DATETIME column type as datetime.datetime type.
-        """
-        pv = None
-        try:
-            pv = datetime.datetime(*time.strptime(v, "%Y-%m-%d %H:%M:%S")[0:6])
-        except ValueError:
-            pv = None
-        
-        return pv
-    
-    def _YEAR_to_python(self, v, desc=None):
-        """Returns YEAR column type as integer"""
-        try:
-            year = int(v)
-        except ValueError:
-            raise ValueError("Failed converting YEAR to int (%s)" % v)
-        
-        return year
-
-    def _SET_to_python(self, v, dsc=None):
-        """Returns SET column typs as set
-        
-        Actually, MySQL protocol sees a SET as a string type field. So this
-        code isn't called directly, but used by STRING_to_python() method.
-        
-        Returns SET column type as a set.
-        """
-        pv = None
-        try:
-            pv = set(v.split(','))
-        except ValueError:
-            raise ValueError, "Could not convert SET %s to a set." % v
-        return pv
-
-    def _STRING_to_python(self, v, dsc=None):
-        """
-        Note that a SET is a string too, but using the FieldFlag we can see
-        whether we have to split it.
-        
-        Returns string typed columns as string type.
-        """
-        if dsc is not None:
-            # Check if we deal with a SET
-            if dsc[7] & FieldFlag.SET:
-                return self._SET_to_python(v, dsc)
-            if dsc[7] & FieldFlag.BINARY:
-                return v
-        
-        if self.use_unicode:
-            try:
-                return unicode(v, self.charset)
-            except:
-                raise
-        return str(v)
-
-    def _BLOB_to_python(self, v, dsc=None):
-        if dsc is not None:
-            if dsc[7] & FieldFlag.BINARY:
-                return v
-        
-        return self._STRING_to_python(v, dsc)
-    

File open-ihm/data/mysql/connector/cursor.py

-# MySQL Connector/Python - MySQL driver written in Python.
-# Copyright 2009 Sun Microsystems, Inc. All rights reserved
-# Use is subject to license terms. (See COPYING)
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation.
-# 
-# There are special exceptions to the terms and conditions of the GNU
-# General Public License as it is applied to this software. View the
-# full text of the exception in file EXCEPTIONS-CLIENT in the directory
-# of this software distribution or see the FOSS License Exception at
-# www.mysql.com.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""Cursor classes
-"""
-
-import weakref
-
-import connection
-import protocol
-import errors
-import utils
-
-class CursorBase(object):
-    """
-    Base for defining MySQLCursor. This class is a skeleton and defines
-    methods and members as required for the Python Database API
-    Specification v2.0.
-    
-    It's better to inherite from MySQLCursor.
-    """
-    
-    def __init__(self):
-        self.description = None
-        self.rowcount = -1
-        self.arraysize = 1
-    
-    def __del__(self):
-        self.close()
-    
-    def callproc(self, procname, args=()):
-        pass
-    
-    def close(self):
-        pass
-    
-    def execute(self, operation, params=()):
-        pass
-    
-    def executemany(self, operation, seqparams):
-        pass
-    
-    def fetchone(self):
-        pass
-    
-    def fetchmany(self, size=1):
-        pass
-    
-    def fetchall(self):
-        pass
-    
-    def nextset(self):
-        pass
-    
-    def setinputsizes(self, sizes):
-        pass
-    
-    def setoutputsize(self, size, column=None):
-        pass
-    
-    def reset(self):
-        pass
-        
-class MySQLCursor(CursorBase):
-    """
-    Default cursor which fetches all rows and stores it for later
-    usage. It uses the converter set for the MySQLConnection to map
-    MySQL types to Python types automatically.
-    
-    This class should be inherited whenever other functionallity is
-    required. An example would to change the fetch* member functions
-    to return dictionaries instead of lists of values.
-    
-    Implements the Python Database API Specification v2.0.
-    
-    Possible parameters are:
-    
-    db
-        A MySQLConnection instance.
-    """
-
-    def __init__(self, db=None):
-        CursorBase.__init__(self)
-        self.db = None
-        self._result = []
-        self._nextrow = (None, None)
-        self.lastrowid = None
-        self._warnings = None
-        self._warning_count = 0
-        self._executed = None
-        self._have_result = False
-        self._raise_on_warnings = True
-        if db is not None:
-            self.set_connection(db)
-    
-    def __iter__(self):
-        """
-        Iteration over the result set which calls self.fetchone()
-        and returns the next row.
-        """
-        return iter(self.fetchone, None)
-        
-    def set_connection(self, db):
-        try:
-            if isinstance(db.conn.protocol,protocol.MySQLProtocol):
-                self.db = weakref.ref(db)
-                if self not in self.db().cursors:
-                    self.db().cursors.append(self)
-        except:
-            raise errors.InterfaceError(errno=2048)
-
-    def _reset_result(self):
-        del self._result[:]
-        self.rowcount = -1
-        self._nextrow = (None, None)
-        self._have_result = False
-        try:
-            self.db().unread_result = False
-        except:
-            pass
-        self._warnings = None
-        self._warning_count = 0
-        self.description = ()
-        self.reset()
-        
-    def next(self):
-        """
-        Used for iterating over the result set. Calles self.fetchone()
-        to get the next row.
-        """
-        try:
-            row = self.fetchone()
-        except errors.InterfaceError:
-            raise StopIteration
-        if not row:
-            raise StopIteration
-        return row
-    
-    def close(self):
-        """
-        Close the cursor, disconnecting it from the MySQL object.
-        
-        Returns True when succesful, otherwise False.
-        """
-        if self.db is None:
-            return False
-        
-        try:
-            self._reset_result()
-            self.db().remove_cursor(self)
-            self.db = None
-        except:
-            return False
-        
-        return True
-    
-    def _process_params_dict(self, params):
-        try:
-            to_mysql = self.db().converter.to_mysql
-            escape = self.db().converter.escape
-            quote = self.db().converter.quote
-            res = {}
-            for k,v in params.items():
-                c = v
-                c = to_mysql(c)
-                c = escape(c)
-                c = quote(c)
-                res[k] = c
-        except StandardError, e:
-            raise errors.ProgrammingError(
-                "Failed processing pyformat-parameters; %s" % e)
-        else:
-            return res
-            
-        return None
-    
-    def _process_params(self, params):
-        """
-        Process the parameters which were given when self.execute() was
-        called. It does following using the MySQLConnection converter:
-        * Convert Python types to MySQL types
-        * Escapes characters required for MySQL.
-        * Quote values when needed.
-        
-        Returns a list.
-        """
-        if isinstance(params,dict):
-            return self._process_params_dict(params)
-        
-        try:
-            res = params
-
-            to_mysql = self.db().converter.to_mysql
-            escape = self.db().converter.escape
-            quote = self.db().converter.quote
-
-            res = map(to_mysql,res)
-            res = map(escape,res)
-            res = map(quote,res)
-        except StandardError, e:
-            raise errors.ProgrammingError(
-                "Failed processing format-parameters; %s" % e)
-        else:
-            return tuple(res)
-        return None
-    
-    def _get_description(self, res=None):
-        """
-        Gets the description of the fields out of a result we got from
-        the MySQL Server. If res is None then self.description is
-        returned (which can be None).
-        
-        Returns a list or None when no descriptions are available.
-        """
-        if not res:
-            return self.description
-        
-        desc = []
-        try:
-            for fld in res[1]:
-                if not isinstance(fld, protocol.FieldPacket):
-                    raise errors.ProgrammingError(
-                        "Can only get description from protocol.FieldPacket")
-                desc.append(fld.get_description())
-        except TypeError:
-            raise errors.ProgrammingError(
-                "_get_description needs a list as argument."
-                )
-        return desc
-
-    def _row_to_python(self, rowdata, desc=None):
-        res = ()
-        try:
-            to_python = self.db().converter.to_python
-            if not desc:
-                desc = self.description
-            for idx,v in enumerate(rowdata):
-                flddsc = desc[idx]
-                res += (to_python(flddsc, v),)
-        except StandardError, e:
-            raise errors.InterfaceError(
-                "Failed converting row to Python types; %s" % e)
-        else:
-            return res
-    
-        return None
-        
-    def _handle_noresultset(self, res):
-        """Handles result of execute() when there is no result set."""
-        try:
-            self.rowcount = res.affected_rows
-            self.lastrowid = res.insert_id
-            self._warning_count = res.warning_count
-            if self.db().get_warnings is True and self._warning_count:
-                self._warnings = self._fetch_warnings()
-        except errors.Error:
-            raise
-        except StandardError, e:
-            raise errors.ProgrammingError(
-                "Failed handling non-resultset; %s" % e)
-    
-    def _handle_resultset(self):
-        pass
-        
-    def execute(self, operation, params=None):
-        """
-        Executes the given operation. The parameters given through params
-        are used to substitute %%s in the operation string.
-        For example, getting all rows where id is 5:
-          cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))
-        
-        If warnings where generated, and db.get_warnings is True, then
-        self._warnings will be a list containing these warnings.
-        
-        Raises exceptions when any error happens.
-        """
-        if not operation:
-            return 0
-        if self.db().unread_result is True:
-            raise errors.InternalError("Unread result found.")
-        
-        self._reset_result()
-        stmt = ''
-        
-        # Make sure we send the query in correct character set
-        try:
-            if isinstance(operation, unicode):
-                operation.encode(self.db().charset_name)
-            if params is not None:
-                try:
-                    stmt = operation % self._process_params(params)
-                except TypeError:
-                    raise errors.ProgrammingError(
-                        "Wrong number of arguments during string formatting")
-            else:
-                stmt = operation
-            
-            res = self.db().protocol().cmd_query(stmt)
-            if isinstance(res, protocol.OKResultPacket):
-                self.db().unread_result = False
-                self._have_result = False
-                self._handle_noresultset(res)
-            else:
-                self.description = self._get_description(res)
-                self.db().unread_result = True
-                self._have_result = True
-                self._handle_resultset()
-        except errors.Error:
-            raise
-        except StandardError, e:
-            raise errors.InterfaceError(
-                "Failed executing the operation; %s" % e)
-        else:
-            self._executed = stmt
-            return self.rowcount
-            
-        return 0
-    
-    def executemany(self, operation, seq_params):
-        """Loops over seq_params and calls excute()"""
-        if not operation:
-            return 0
-        if self.db().unread_result is True:
-            raise errors.InternalError("Unread result found.")
-        
-        rowcnt = 0
-        try:
-            for params in seq_params:
-                self.execute(operation, params)
-                if self._have_result:
-                    self.fetchall()
-                rowcnt += self.rowcount
-        except (ValueError,TypeError), e:
-            raise errors.InterfaceError(
-                "Failed executing the operation; %s" % e)
-        except:
-            # Raise whatever execute() raises
-            raise
-        
-        self.rowcount = rowcnt
-        return rowcnt
-    
-    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()
-          
-          The last print should output ('5', '5', 25L)
-
-        Does not return a value, but a result set will be
-        available when the CALL-statement execute succesfully.
-        Raises exceptions when something is wrong.
-        """
-        argfmt = "@_%s_arg%d"
-        
-        try:
-            procargs = self._process_params(args)
-            argnames = []
-        
-            for idx,arg in enumerate(procargs):
-                argname = argfmt % (procname, idx+1)
-                argnames.append(argname)
-                setquery = "SET %s=%%s" % argname
-                self.execute(setquery, (arg,))
-        
-            call = "CALL %s(%s)" % (procname,','.join(argnames))
-            res = self.db().protocol().cmd_query(call)
-            
-            select = "SELECT %s" % ','.join(argnames)
-            self.execute(select)
-            
-        except errors.Error:
-            raise
-        except StandardError, e:
-            raise errors.InterfaceError(
-                "Failed calling stored routine; %s" % e)
-    
-    def getlastrowid(self):
-        return self.lastrowid
-        
-    def _fetch_warnings(self):
-        """
-        Fetch warnings doing a SHOW WARNINGS. Can be called after getting
-        the result.
-
-        Returns a result set or None when there were no warnings.
-        """
-        res = []
-        try:
-            c = self.db().cursor()
-            cnt = c.execute("SHOW WARNINGS")
-            res = c.fetchall()
-            c.close()
-        except StandardError, e:
-            raise errors.InterfaceError(
-                "Failed getting warnings; %s" % e)
-        
-        if self.db().raise_on_warnings is True:
-            msg = '; '.join([ "(%s) %s" % (r[1],r[2]) for r in res])
-            if res[0][1] == 1366:
-                c = self.db().cursor()
-                cnt = c.execute("SHOW CREATE TABLE mytable2")
-                print c.fetchall()
-                c.close()
-            raise errors.get_mysql_exception(res[0][1],res[0][2])
-        else:
-            if len(res):
-                return res
-            
-        return None
-    
-    def _handle_eof(self, eof):
-        self._have_result = False
-        self.db().unread_result = False
-        self._nextrow = (None, None)
-        self._warning_count = eof.warning_count
-        if self.db().get_warnings is True and eof.warning_count:
-            self._warnings = self._fetch_warnings()
-    
-    def _fetch_row(self):
-        if self._have_result is False:
-            return None
-        row = None
-        try:
-            if self._nextrow == (None, None):
-                (row, eof) = self.db().protocol().result_get_row()
-            else:
-                (row, eof) = self._nextrow
-            if row:
-                (foo, eof) = self._nextrow = self.db().protocol().result_get_row()
-                if eof is not None:
-                    self._handle_eof(eof)
-                if self.rowcount == -1:
-                    self.rowcount = 1
-                else:
-                    self.rowcount += 1
-            if eof:
-                self._handle_eof(eof)
-        except:
-            raise
-        else:
-            return row
-            
-        return None
-    
-    def fetchwarnings(self):
-        return self._warnings
-        
-    def fetchone(self):
-        row = self._fetch_row()
-        if row:
-            return self._row_to_python(row)
-        return None
-        
-    def fetchmany(self,size=None):
-        res = []
-        cnt = (size or self.arraysize)
-        while cnt > 0 and self._have_result:
-            cnt -= 1
-            row = self.fetchone()
-            if row:
-                res.append(row)
-            
-        return res
-    
-    def fetchall(self):
-        if self._have_result is False:
-            raise errors.InterfaceError("No result set to fetch from.")
-        res = []
-        row = None
-        while self.db().unread_result:
-            row = self.fetchone()
-            if row:
-                res.append(row)
-        return res
-        
-    def __unicode__(self):
-        fmt = "MySQLCursor: %s"
-        if self._executed:
-            if len(self._executed) > 30:
-                res = fmt % (self._executed[:30] + '..')
-            else:
-                res = fmt % (self._executed)
-        else:
-            res = fmt % '(Nothing executed yet)'
-        return res
-    
-    def __str__(self):
-        return repr(self.__unicode__())
-
-class MySQLCursorBuffered(MySQLCursor):
-    """Cursor which fetches rows within execute()"""
-    
-    def __init__(self, db=None):
-        MySQLCursor.__init__(self, db)
-        self._rows = None
-        self._next_row = 0
-