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

Revision 2741, 6.2 kB (checked in by jerome, 18 years ago)

Added timing information for SQL queries and transactions.

  • Property svn:keywords set to Author Date Id Revision
RevLine 
[2639]1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
[2644]6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# (c) 2005, 2006 Matt Hyclak <hyclak@math.ohiou.edu>
[2639]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#
[2645]22# $Id$
[2639]23#
24#
25
[2741]26import time
27
[2639]28from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
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 :   
[2644]46            port = -1           # Use the default MySQL port
[2639]47       
48        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
49        self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd)
[2741]50        self.database.autocommit(1)
[2644]51        self.cursor = self.database.cursor()
[2639]52        self.closed = 0
53        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
54           
55    def close(self) :   
56        """Closes the database connection."""
57        if not self.closed :
[2644]58            self.cursor.close()
[2639]59            self.database.close()
60            self.closed = 1
61            self.tool.logdebug("Database closed.")
62       
63    def beginTransaction(self) :   
64        """Starts a transaction."""
[2741]65        self.before = time.time()
[2646]66        self.cursor.execute("BEGIN;")
[2639]67        self.tool.logdebug("Transaction begins...")
68       
69    def commitTransaction(self) :   
70        """Commits a transaction."""
71        self.database.commit()
[2741]72        after = time.time()
[2639]73        self.tool.logdebug("Transaction committed.")
[2741]74        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[2639]75       
76    def rollbackTransaction(self) :     
77        """Rollbacks a transaction."""
78        self.database.rollback()
[2741]79        after = time.time()
[2639]80        self.tool.logdebug("Transaction aborted.")
[2741]81        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[2639]82       
83    def doRawSearch(self, query) :
84        """Does a raw search query."""
85        query = query.strip()   
86        if not query.endswith(';') :   
87            query += ';'
88        try :
[2741]89            before = time.time()
[2639]90            self.tool.logdebug("QUERY : %s" % query)
91            self.cursor.execute(query)
92        except self.database.Error, msg :   
93            raise PyKotaStorageError, str(msg)
94        else :   
[2644]95            # This returns a list of lists. Integers are returned as longs.
[2741]96            result = self.cursor.fetchall()
97            after = time.time()
98            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
99            return result
[2639]100           
101    def doSearch(self, query) :       
102        """Does a search query."""
103        result = self.doRawSearch(query)
[2644]104        if result :
105            rows = []
[2639]106            fields = {}
107            for i in range(len(self.cursor.description)) :
[2644]108                fields[i] = self.cursor.description[i][0]
109            for row in result :
[2639]110                rowdict = {}
111                for field in fields.keys() :
[2644]112                    value = row[field]
113                    try :
114                        value = value.encode("UTF-8")
115                    except:
116                        pass
117                    rowdict[fields[field]] = value
118                rows.append(rowdict)
119            # returns a list of dicts
120            return rows
[2639]121
122    def doModify(self, query) :
123        """Does a (possibly multiple) modify query."""
124        query = query.strip()   
125        if not query.endswith(';') :   
126            query += ';'
127        try :
[2741]128            before = time.time()
[2639]129            self.tool.logdebug("QUERY : %s" % query)
130            self.cursor.execute(query)
131        except self.database.Error, msg :   
132            raise PyKotaStorageError, str(msg)
[2741]133        else :   
134            after = time.time()
135            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[2639]136           
137    def doQuote(self, field) :
138        """Quotes a field for use as a string in SQL queries."""
139        if type(field) == type(0.0) :
140            return field
141        elif type(field) == type(0) :
142            return field
143        elif type(field) == type(0L) :
144            return field
145        elif field is not None :
146            return (self.database.string_literal(field)).encode("UTF-8")
147        else :
[2644]148            self.tool.logdebug("WARNING: field has no type, returning NULL")
[2639]149            return "NULL"
150
151    def prepareRawResult(self, result) :
152        """Prepares a raw result by including the headers."""
153        if result :
154            entries = [tuple([f[0] for f in self.cursor.description])]
[2644]155            for entry in result :
[2639]156                row = []
157                for value in entry :
158                    try :
159                        value = value.encode("UTF-8")
160                    except :
161                        pass
162                    row.append(value)
163                entries.append(tuple(row))
164            return entries
Note: See TracBrowser for help on using the browser.