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
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# 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
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25"""This module defines a class to access to a PostgreSQL database backend."""
26
27import time
28from types import StringType
29
30from pykota.storage import PyKotaStorageError, BaseStorage
31from pykota.storages.sql import SQLStorage
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]
39else :   
40    try :
41        PGError = pg.Error
42    except AttributeError :   
43        PGError = pg.error
44
45class Storage(BaseStorage, SQLStorage) :
46    def __init__(self, pykotatool, host, dbname, user, passwd) :
47        """Opens the PostgreSQL database connection."""
48        BaseStorage.__init__(self, pykotatool)
49        try :
50            (host, port) = host.split(":")
51            port = int(port)
52        except ValueError :   
53            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
54       
55        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
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
61        self.closed = 0
62        try :
63            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
64        except PGError, msg :   
65            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
66        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
67           
68    def close(self) :   
69        """Closes the database connection."""
70        if not self.closed :
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.database.query("BEGIN;")
79        self.tool.logdebug("Transaction begins...")
80       
81    def commitTransaction(self) :   
82        """Commits a transaction."""
83        self.database.query("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.query("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            result = self.database.query(query)
104        except PGError, msg :   
105            raise PyKotaStorageError, str(msg)
106        else :   
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 is not None) and (result.ntuples() > 0) : 
115            return result.dictresult()
116       
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 :
123            before = time.time()
124            self.tool.logdebug("QUERY : %s" % query)
125            result = self.database.query(query)
126        except PGError, msg :   
127            self.tool.logdebug("Query failed : %s" % repr(msg))
128            raise PyKotaStorageError, str(msg)
129        else :   
130            after = time.time()
131            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
132            return result
133           
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"
140        elif type(field) == type(0L) :   
141            typ = "int"
142        else :   
143            typ = "text"
144        return pg._quote(field, typ)
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.