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

Revision 3184, 7.0 kB (checked in by jerome, 17 years ago)

Added some docstrings.

  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
7# (c) 2005, 2006 Matt Hyclak <hyclak@math.ohiou.edu>
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21#
22# $Id$
23#
24#
25
26"""This module defines a class to access to a MySQL database backend."""
27
28import time
29
30from pykota.storage import PyKotaStorageError, BaseStorage
31from pykota.storages.sql import SQLStorage
32
33try :
34    import MySQLdb
35except ImportError :   
36    import sys
37    # TODO : to translate or not to translate ?
38    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the MySQL module installed correctly." % sys.version.split()[0]
39
40class Storage(BaseStorage, SQLStorage) :
41    def __init__(self, pykotatool, host, dbname, user, passwd) :
42        """Opens the MySQL database connection."""
43        BaseStorage.__init__(self, pykotatool)
44        try :
45            (host, port) = host.split(":")
46            port = int(port)
47        except ValueError :   
48            port = 3306           # Use the default MySQL port
49       
50        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
51        try :
52            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd, charset="utf8")
53        except TypeError :   
54            self.tool.logdebug("'charset' argument not allowed with this version of python-mysqldb, retrying without...")
55            self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd)
56           
57        try :
58            self.database.autocommit(1)
59        except AttributeError :   
60            raise PyKotaStorageError, _("Your version of python-mysqldb is too old. Please install a newer release.")
61        self.cursor = self.database.cursor()
62        self.cursor.execute("SET NAMES 'utf8';")
63        self.cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;") # Same as PostgreSQL and Oracle's default
64        self.closed = 0
65        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
66           
67    def close(self) :   
68        """Closes the database connection."""
69        if not self.closed :
70            self.cursor.close()
71            self.database.close()
72            self.closed = 1
73            self.tool.logdebug("Database closed.")
74       
75    def beginTransaction(self) :   
76        """Starts a transaction."""
77        self.before = time.time()
78        self.cursor.execute("BEGIN;")
79        self.tool.logdebug("Transaction begins...")
80       
81    def commitTransaction(self) :   
82        """Commits a transaction."""
83        self.database.commit()
84        after = time.time()
85        self.tool.logdebug("Transaction committed.")
86        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
87       
88    def rollbackTransaction(self) :     
89        """Rollbacks a transaction."""
90        self.database.rollback()
91        after = time.time()
92        self.tool.logdebug("Transaction aborted.")
93        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
94       
95    def doRawSearch(self, query) :
96        """Does a raw search query."""
97        query = query.strip()   
98        if not query.endswith(';') :   
99            query += ';'
100        try :
101            before = time.time()
102            self.tool.logdebug("QUERY : %s" % query)
103            self.cursor.execute(query)
104        except self.database.Error, msg :   
105            raise PyKotaStorageError, str(msg)
106        else :   
107            # This returns a list of lists. Integers are returned as longs.
108            result = self.cursor.fetchall()
109            after = time.time()
110            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
111            return result
112           
113    def doSearch(self, query) :       
114        """Does a search query."""
115        result = self.doRawSearch(query)
116        if result :
117            rows = []
118            fields = {}
119            for i in range(len(self.cursor.description)) :
120                fields[i] = self.cursor.description[i][0]
121            for row in result :
122                rowdict = {}
123                for field in fields.keys() :
124                    value = row[field]
125                    try :
126                        value = value.encode("UTF-8")
127                    except:
128                        pass
129                    rowdict[fields[field]] = value
130                rows.append(rowdict)
131            # returns a list of dicts
132            return rows
133
134    def doModify(self, query) :
135        """Does a (possibly multiple) modify query."""
136        query = query.strip()   
137        if not query.endswith(';') :   
138            query += ';'
139        try :
140            before = time.time()
141            self.tool.logdebug("QUERY : %s" % query)
142            self.cursor.execute(query)
143        except self.database.Error, msg :   
144            self.tool.logdebug("Query failed : %s" % repr(msg))
145            raise PyKotaStorageError, str(msg)
146        else :   
147            after = time.time()
148            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
149           
150    def doQuote(self, field) :
151        """Quotes a field for use as a string in SQL queries."""
152        if type(field) == type(0.0) :
153            return field
154        elif type(field) == type(0) :
155            return field
156        elif type(field) == type(0L) :
157            return field
158        elif field is not None :
159            newfield = self.database.string_literal(field)
160            try :
161                return newfield.encode("UTF-8")
162            except :   
163                return newfield
164        else :
165            self.tool.logdebug("WARNING: field has no type, returning NULL")
166            return "NULL"
167
168    def prepareRawResult(self, result) :
169        """Prepares a raw result by including the headers."""
170        if result :
171            entries = [tuple([f[0] for f in self.cursor.description])]
172            for entry in result :
173                row = []
174                for value in entry :
175                    try :
176                        value = value.encode("UTF-8")
177                    except :
178                        pass
179                    row.append(value)
180                entries.append(tuple(row))
181            return entries
Note: See TracBrowser for help on using the browser.