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

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

Added some docstrings.

  • 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#
[3133]6# (c) 2003, 2004, 2005, 2006, 2007 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
[3184]25"""This module defines a class to access to a PostgreSQL database backend."""
26
[2741]27import time
[2599]28from types import StringType
29
[2830]30from pykota.storage import PyKotaStorageError, BaseStorage
[1327]31from pykota.storages.sql import SQLStorage
[1021]32
33try :
34    import pg
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 PygreSQL module installed correctly." % sys.version.split()[0]
[2031]39else :   
40    try :
41        PGError = pg.Error
42    except AttributeError :   
43        PGError = pg.error
[1021]44
[1327]45class Storage(BaseStorage, SQLStorage) :
[1021]46    def __init__(self, pykotatool, host, dbname, user, passwd) :
47        """Opens the PostgreSQL database connection."""
[1130]48        BaseStorage.__init__(self, pykotatool)
[1021]49        try :
50            (host, port) = host.split(":")
51            port = int(port)
52        except ValueError :   
[2874]53            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
[1021]54       
[2418]55        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
[3182]56        try :
57            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
58        except PGError, msg :   
59            msg = "%(msg)s --- the most probable cause of your problem is that PostgreSQL is down, or doesn't accept incoming connections because you didn't configure it as explained in PyKota's documentation." % locals()
60            raise PGError, msg
[2210]61        self.closed = 0
[2960]62        try :
63            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
64        except PGError, msg :   
[2972]65            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
[2210]66        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
[1021]67           
[1113]68    def close(self) :   
[1021]69        """Closes the database connection."""
70        if not self.closed :
71            self.database.close()
72            self.closed = 1
[1130]73            self.tool.logdebug("Database closed.")
[1021]74       
[1041]75    def beginTransaction(self) :   
76        """Starts a transaction."""
[2741]77        self.before = time.time()
[1041]78        self.database.query("BEGIN;")
[1130]79        self.tool.logdebug("Transaction begins...")
[1041]80       
81    def commitTransaction(self) :   
82        """Commits a transaction."""
83        self.database.query("COMMIT;")
[2741]84        after = time.time()
[1130]85        self.tool.logdebug("Transaction committed.")
[3182]86        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]87       
88    def rollbackTransaction(self) :     
89        """Rollbacks a transaction."""
90        self.database.query("ROLLBACK;")
[2741]91        after = time.time()
[1130]92        self.tool.logdebug("Transaction aborted.")
[3182]93        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]94       
[1717]95    def doRawSearch(self, query) :
96        """Does a raw search query."""
[1021]97        query = query.strip()   
98        if not query.endswith(';') :   
99            query += ';'
100        try :
[2741]101            before = time.time()
[1130]102            self.tool.logdebug("QUERY : %s" % query)
[1021]103            result = self.database.query(query)
[2031]104        except PGError, msg :   
[2033]105            raise PyKotaStorageError, str(msg)
[1021]106        else :   
[2741]107            after = time.time()
[3182]108            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1717]109            return result
[1041]110           
[1717]111    def doSearch(self, query) :       
112        """Does a search query."""
113        result = self.doRawSearch(query)
114        if (result is not None) and (result.ntuples() > 0) : 
115            return result.dictresult()
116       
[1041]117    def doModify(self, query) :
118        """Does a (possibly multiple) modify query."""
119        query = query.strip()   
120        if not query.endswith(';') :   
121            query += ';'
122        try :
[2741]123            before = time.time()
[1130]124            self.tool.logdebug("QUERY : %s" % query)
[1041]125            result = self.database.query(query)
[2031]126        except PGError, msg :   
[2773]127            self.tool.logdebug("Query failed : %s" % repr(msg))
[2033]128            raise PyKotaStorageError, str(msg)
[1068]129        else :   
[2741]130            after = time.time()
[3182]131            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1068]132            return result
[1041]133           
[1021]134    def doQuote(self, field) :
135        """Quotes a field for use as a string in SQL queries."""
136        if type(field) == type(0.0) : 
137            typ = "decimal"
138        elif type(field) == type(0) :   
139            typ = "int"
[1520]140        elif type(field) == type(0L) :   
141            typ = "int"
[1021]142        else :   
143            typ = "text"
144        return pg._quote(field, typ)
[2593]145       
146    def prepareRawResult(self, result) :
147        """Prepares a raw result by including the headers."""
148        if result.ntuples() > 0 :
149            entries = [result.listfields()]
150            entries.extend(result.getresult())
151            nbfields = len(entries[0])
152            for i in range(1, len(entries)) :
153                fields = list(entries[i])
154                for j in range(nbfields) :
155                    field = fields[j]
156                    if type(field) == StringType :
157                        fields[j] = self.databaseToUserCharset(field) 
158                entries[i] = tuple(fields)   
159            return entries
160       
Note: See TracBrowser for help on using the browser.