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

Revision 3294, 6.8 kB (checked in by jerome, 16 years ago)

Added modules to store utility functions and application
intialization code, which has nothing to do in classes.
Modified tool.py accordingly (far from being finished)
Use these new modules where necessary.
Now converts all command line arguments to unicode before
beginning to work. Added a proper logging method for already
encoded query strings.

  • 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
25import time
26
27from pykota.errors import PyKotaStorageError
28from pykota.storage import BaseStorage
29from pykota.storages.sql import SQLStorage
30
31try :
32    import MySQLdb
33except ImportError :   
34    import sys
35    # TODO : to translate or not to translate ?
36    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the MySQL module installed correctly." % sys.version.split()[0]
37
38class Storage(BaseStorage, SQLStorage) :
39    def __init__(self, pykotatool, host, dbname, user, passwd) :
40        """Opens the MySQL database connection."""
41        BaseStorage.__init__(self, pykotatool)
42        try :
43            (host, port) = host.split(":")
44            port = int(port)
45        except ValueError :   
46            port = 3306           # Use the default MySQL port
47       
48        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
49        try :
50            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd, charset="utf8")
51        except TypeError :   
52            self.tool.logdebug("'charset' argument not allowed with this version of python-mysqldb, retrying without...")
53            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd)
54           
55        try :
56            self.database.autocommit(1)
57        except AttributeError :   
58            raise PyKotaStorageError, _("Your version of python-mysqldb is too old. Please install a newer release.")
59        self.cursor = self.database.cursor()
60        self.cursor.execute("SET NAMES 'utf8';")
61        self.cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;") # Same as PostgreSQL and Oracle's default
62        self.closed = 0
63        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
64           
65    def close(self) :   
66        """Closes the database connection."""
67        if not self.closed :
68            self.cursor.close()
69            self.database.close()
70            self.closed = 1
71            self.tool.logdebug("Database closed.")
72       
73    def beginTransaction(self) :   
74        """Starts a transaction."""
75        self.before = time.time()
76        self.cursor.execute("BEGIN;")
77        self.tool.logdebug("Transaction begins...")
78       
79    def commitTransaction(self) :   
80        """Commits a transaction."""
81        self.database.commit()
82        after = time.time()
83        self.tool.logdebug("Transaction committed.")
84        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
85       
86    def rollbackTransaction(self) :     
87        """Rollbacks a transaction."""
88        self.database.rollback()
89        after = time.time()
90        self.tool.logdebug("Transaction aborted.")
91        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
92       
93    def doRawSearch(self, query) :
94        """Does a raw search query."""
95        query = query.strip()   
96        if not query.endswith(';') :   
97            query += ';'
98        try :
99            before = time.time()
100            self.querydebug("QUERY : %s" % query)
101            self.cursor.execute(query)
102        except self.database.Error, msg :   
103            raise PyKotaStorageError, str(msg)
104        else :   
105            # This returns a list of lists. Integers are returned as longs.
106            result = self.cursor.fetchall()
107            after = time.time()
108            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
109            return result
110           
111    def doSearch(self, query) :       
112        """Does a search query."""
113        result = self.doRawSearch(query)
114        if result :
115            rows = []
116            fields = {}
117            for i in range(len(self.cursor.description)) :
118                fields[i] = self.cursor.description[i][0]
119            for row in result :
120                rowdict = {}
121                for field in fields.keys() :
122                    value = row[field]
123                    try :
124                        value = value.encode("UTF-8")
125                    except:
126                        pass
127                    rowdict[fields[field]] = value
128                rows.append(rowdict)
129            # returns a list of dicts
130            return rows
131
132    def doModify(self, query) :
133        """Does a (possibly multiple) modify query."""
134        query = query.strip()   
135        if not query.endswith(';') :   
136            query += ';'
137        try :
138            before = time.time()
139            self.querydebug("QUERY : %s" % query)
140            self.cursor.execute(query)
141        except self.database.Error, msg :   
142            self.tool.logdebug("Query failed : %s" % repr(msg))
143            raise PyKotaStorageError, str(msg)
144        else :   
145            after = time.time()
146            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
147           
148    def doQuote(self, field) :
149        """Quotes a field for use as a string in SQL queries."""
150        if type(field) == type(0.0) :
151            return field
152        elif type(field) == type(0) :
153            return field
154        elif type(field) == type(0L) :
155            return field
156        elif field is not None :
157            newfield = self.database.string_literal(field)
158            try :
159                return newfield.encode("UTF-8")
160            except :   
161                return newfield
162        else :
163            self.tool.logdebug("WARNING: field has no type, returning NULL")
164            return "NULL"
165
166    def prepareRawResult(self, result) :
167        """Prepares a raw result by including the headers."""
168        if result :
169            entries = [tuple([f[0] for f in self.cursor.description])]
170            for entry in result :
171                row = []
172                for value in entry :
173                    try :
174                        value = value.encode("UTF-8")
175                    except :
176                        pass
177                    row.append(value)
178                entries.append(tuple(row))
179            return entries
Note: See TracBrowser for help on using the browser.