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

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

Added timing information for SQL queries and transactions.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[1021]1# PyKota
[1144]2# -*- coding: ISO-8859-15 -*-
[1021]3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
[2622]6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
[1021]7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
[2302]19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
[1021]20#
21# $Id$
22#
[2033]23#
[1021]24
[2741]25import time
[2599]26from types import StringType
27
[1274]28from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
[1327]29from pykota.storages.sql import SQLStorage
[1021]30
31try :
32    import pg
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 PygreSQL module installed correctly." % sys.version.split()[0]
[2031]37else :   
38    try :
39        PGError = pg.Error
40    except AttributeError :   
41        PGError = pg.error
[1021]42
[1327]43class Storage(BaseStorage, SQLStorage) :
[1021]44    def __init__(self, pykotatool, host, dbname, user, passwd) :
45        """Opens the PostgreSQL database connection."""
[1130]46        BaseStorage.__init__(self, pykotatool)
[1021]47        try :
48            (host, port) = host.split(":")
49            port = int(port)
50        except ValueError :   
51            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
52       
[2418]53        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
[2210]54        self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
55        self.closed = 0
56        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
[1021]57           
[1113]58    def close(self) :   
[1021]59        """Closes the database connection."""
60        if not self.closed :
61            self.database.close()
62            self.closed = 1
[1130]63            self.tool.logdebug("Database closed.")
[1021]64       
[1041]65    def beginTransaction(self) :   
66        """Starts a transaction."""
[2741]67        self.before = time.time()
[1041]68        self.database.query("BEGIN;")
[1130]69        self.tool.logdebug("Transaction begins...")
[1041]70       
71    def commitTransaction(self) :   
72        """Commits a transaction."""
73        self.database.query("COMMIT;")
[2741]74        after = time.time()
[1130]75        self.tool.logdebug("Transaction committed.")
[2741]76        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]77       
78    def rollbackTransaction(self) :     
79        """Rollbacks a transaction."""
80        self.database.query("ROLLBACK;")
[2741]81        after = time.time()
[1130]82        self.tool.logdebug("Transaction aborted.")
[2741]83        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]84       
[1717]85    def doRawSearch(self, query) :
86        """Does a raw search query."""
[1021]87        query = query.strip()   
88        if not query.endswith(';') :   
89            query += ';'
90        try :
[2741]91            before = time.time()
[1130]92            self.tool.logdebug("QUERY : %s" % query)
[1021]93            result = self.database.query(query)
[2031]94        except PGError, msg :   
[2033]95            raise PyKotaStorageError, str(msg)
[1021]96        else :   
[2741]97            after = time.time()
98            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1717]99            return result
[1041]100           
[1717]101    def doSearch(self, query) :       
102        """Does a search query."""
103        result = self.doRawSearch(query)
104        if (result is not None) and (result.ntuples() > 0) : 
105            return result.dictresult()
106       
[1041]107    def doModify(self, query) :
108        """Does a (possibly multiple) modify query."""
109        query = query.strip()   
110        if not query.endswith(';') :   
111            query += ';'
112        try :
[2741]113            before = time.time()
[1130]114            self.tool.logdebug("QUERY : %s" % query)
[1041]115            result = self.database.query(query)
[2031]116        except PGError, msg :   
[2033]117            raise PyKotaStorageError, str(msg)
[1068]118        else :   
[2741]119            after = time.time()
120            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1068]121            return result
[1041]122           
[1021]123    def doQuote(self, field) :
124        """Quotes a field for use as a string in SQL queries."""
125        if type(field) == type(0.0) : 
126            typ = "decimal"
127        elif type(field) == type(0) :   
128            typ = "int"
[1520]129        elif type(field) == type(0L) :   
130            typ = "int"
[1021]131        else :   
132            typ = "text"
133        return pg._quote(field, typ)
[2593]134       
135    def prepareRawResult(self, result) :
136        """Prepares a raw result by including the headers."""
137        if result.ntuples() > 0 :
138            entries = [result.listfields()]
139            entries.extend(result.getresult())
140            nbfields = len(entries[0])
141            for i in range(1, len(entries)) :
142                fields = list(entries[i])
143                for j in range(nbfields) :
144                    field = fields[j]
145                    if type(field) == StringType :
146                        fields[j] = self.databaseToUserCharset(field) 
147                entries[i] = tuple(fields)   
148            return entries
149       
Note: See TracBrowser for help on using the browser.