root / pykota / trunk / pykota / storages / mysqlstorage.py @ 3310

Revision 3310, 6.4 kB (checked in by jerome, 16 years ago)

Added a workaround for buggy versions of python-mysqldb (e.g
1.2.1-p2-4 on my Debian Etch box) which have the double
encoding bug (#1521274 on sourceforge.net).

  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3260]1# -*- coding: UTF-8 -*-
[2639]2#
[3260]3# PyKota : Print Quotas for CUPS
[2639]4#
[3275]5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
[3260]6# This program is free software: you can redistribute it and/or modify
[2639]7# it under the terms of the GNU General Public License as published by
[3260]8# the Free Software Foundation, either version 3 of the License, or
[2639]9# (at your option) any later version.
[3260]10#
[2639]11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
[3260]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[2639]18#
[2645]19# $Id$
[2639]20#
21#
22
[3184]23"""This module defines a class to access to a MySQL database backend."""
24
[3288]25from pykota.errors import PyKotaStorageError
26from pykota.storage import BaseStorage
[2639]27from pykota.storages.sql import SQLStorage
28
29try :
30    import MySQLdb
31except ImportError :   
32    import sys
33    # TODO : to translate or not to translate ?
34    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the MySQL module installed correctly." % sys.version.split()[0]
35
36class Storage(BaseStorage, SQLStorage) :
37    def __init__(self, pykotatool, host, dbname, user, passwd) :
38        """Opens the MySQL database connection."""
39        BaseStorage.__init__(self, pykotatool)
40        try :
41            (host, port) = host.split(":")
42            port = int(port)
43        except ValueError :   
[2874]44            port = 3306           # Use the default MySQL port
[2639]45       
46        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
[3009]47        try :
[3138]48            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd, charset="utf8")
49        except TypeError :   
50            self.tool.logdebug("'charset' argument not allowed with this version of python-mysqldb, retrying without...")
51            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd)
52           
53        try :
[3009]54            self.database.autocommit(1)
55        except AttributeError :   
[3010]56            raise PyKotaStorageError, _("Your version of python-mysqldb is too old. Please install a newer release.")
[2644]57        self.cursor = self.database.cursor()
[2954]58        self.cursor.execute("SET NAMES 'utf8';")
[2821]59        self.cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;") # Same as PostgreSQL and Oracle's default
[3310]60        self.closed = False
[2639]61        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
[3310]62        try :
63            # Here we try to select a string (an &eacute;) which is
64            # already encoded in UTF-8. If python-mysqldb suffers from
65            # the double encoding problem, we will catch the exception
66            # and activate a workaround.
67            self.cursor.execute("SELECT '%s';" % (chr(0xc3) + chr(0xa9))) # &eacute; in UTF-8
68            self.cursor.fetchall()
69        except UnicodeDecodeError :   
70            self.needsworkaround = True
71            self.tool.logdebug("Database needs encoding workaround.")
72        else :
73            self.needsworkaround = False
74            self.tool.logdebug("Database doesn't need encoding workaround.")
[2639]75           
76    def close(self) :   
77        """Closes the database connection."""
78        if not self.closed :
[2644]79            self.cursor.close()
[2639]80            self.database.close()
[3310]81            self.closed = True
[2639]82            self.tool.logdebug("Database closed.")
83       
84    def beginTransaction(self) :   
85        """Starts a transaction."""
[2646]86        self.cursor.execute("BEGIN;")
[2639]87        self.tool.logdebug("Transaction begins...")
88       
89    def commitTransaction(self) :   
90        """Commits a transaction."""
91        self.database.commit()
92        self.tool.logdebug("Transaction committed.")
93       
94    def rollbackTransaction(self) :     
95        """Rollbacks a transaction."""
96        self.database.rollback()
97        self.tool.logdebug("Transaction aborted.")
98       
99    def doRawSearch(self, query) :
100        """Does a raw search query."""
101        query = query.strip()   
102        if not query.endswith(';') :   
103            query += ';'
[3310]104        self.querydebug("QUERY : %s" % query)
105        if self.needsworkaround :   
106            query = query.decode("UTF-8")
[2639]107        try :
108            self.cursor.execute(query)
109        except self.database.Error, msg :   
[3308]110            raise PyKotaStorageError, repr(msg)
[2639]111        else :   
[2644]112            # This returns a list of lists. Integers are returned as longs.
[3310]113            return self.cursor.fetchall()
[2639]114           
115    def doSearch(self, query) :       
116        """Does a search query."""
117        result = self.doRawSearch(query)
[2644]118        if result :
119            rows = []
[2639]120            fields = {}
121            for i in range(len(self.cursor.description)) :
[2644]122                fields[i] = self.cursor.description[i][0]
123            for row in result :
[2639]124                rowdict = {}
125                for field in fields.keys() :
[3310]126                    rowdict[fields[field]] = row[field]
[2644]127                rows.append(rowdict)
128            # returns a list of dicts
129            return rows
[2639]130
131    def doModify(self, query) :
132        """Does a (possibly multiple) modify query."""
133        query = query.strip()   
134        if not query.endswith(';') :   
135            query += ';'
[3310]136        self.querydebug("QUERY : %s" % query)
137        if self.needsworkaround :   
138            query = query.decode("UTF-8")
[2639]139        try :
140            self.cursor.execute(query)
141        except self.database.Error, msg :   
[2773]142            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]143            raise PyKotaStorageError, repr(msg)
[2639]144           
145    def doQuote(self, field) :
146        """Quotes a field for use as a string in SQL queries."""
147        if type(field) == type(0.0) :
148            return field
149        elif type(field) == type(0) :
150            return field
151        elif type(field) == type(0L) :
152            return field
153        elif field is not None :
[3310]154            return self.database.string_literal(field)
[2639]155        else :
156            return "NULL"
157
158    def prepareRawResult(self, result) :
159        """Prepares a raw result by including the headers."""
160        if result :
[3310]161            return [tuple([f[0] for f in self.cursor.description])] \
162                 + list(result)
Note: See TracBrowser for help on using the browser.