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
Line 
1# -*- coding: UTF-8 -*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
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
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21#
22
23"""This module defines a class to access to a MySQL database backend."""
24
25from pykota.errors import PyKotaStorageError
26from pykota.storage import BaseStorage
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 :   
44            port = 3306           # Use the default MySQL port
45       
46        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
47        try :
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 :
54            self.database.autocommit(1)
55        except AttributeError :   
56            raise PyKotaStorageError, _("Your version of python-mysqldb is too old. Please install a newer release.")
57        self.cursor = self.database.cursor()
58        self.cursor.execute("SET NAMES 'utf8';")
59        self.cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;") # Same as PostgreSQL and Oracle's default
60        self.closed = False
61        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
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.")
75           
76    def close(self) :   
77        """Closes the database connection."""
78        if not self.closed :
79            self.cursor.close()
80            self.database.close()
81            self.closed = True
82            self.tool.logdebug("Database closed.")
83       
84    def beginTransaction(self) :   
85        """Starts a transaction."""
86        self.cursor.execute("BEGIN;")
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 += ';'
104        self.querydebug("QUERY : %s" % query)
105        if self.needsworkaround :   
106            query = query.decode("UTF-8")
107        try :
108            self.cursor.execute(query)
109        except self.database.Error, msg :   
110            raise PyKotaStorageError, repr(msg)
111        else :   
112            # This returns a list of lists. Integers are returned as longs.
113            return self.cursor.fetchall()
114           
115    def doSearch(self, query) :       
116        """Does a search query."""
117        result = self.doRawSearch(query)
118        if result :
119            rows = []
120            fields = {}
121            for i in range(len(self.cursor.description)) :
122                fields[i] = self.cursor.description[i][0]
123            for row in result :
124                rowdict = {}
125                for field in fields.keys() :
126                    rowdict[fields[field]] = row[field]
127                rows.append(rowdict)
128            # returns a list of dicts
129            return rows
130
131    def doModify(self, query) :
132        """Does a (possibly multiple) modify query."""
133        query = query.strip()   
134        if not query.endswith(';') :   
135            query += ';'
136        self.querydebug("QUERY : %s" % query)
137        if self.needsworkaround :   
138            query = query.decode("UTF-8")
139        try :
140            self.cursor.execute(query)
141        except self.database.Error, msg :   
142            self.tool.logdebug("Query failed : %s" % repr(msg))
143            raise PyKotaStorageError, repr(msg)
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 :
154            return self.database.string_literal(field)
155        else :
156            return "NULL"
157
158    def prepareRawResult(self, result) :
159        """Prepares a raw result by including the headers."""
160        if result :
161            return [tuple([f[0] for f in self.cursor.description])] \
162                 + list(result)
Note: See TracBrowser for help on using the browser.