root / pykota / branches / 1.26_fixes / pykota / storages / pgstorage.py @ 3500

Revision 3500, 6.1 kB (checked in by jerome, 15 years ago)

Backported from @3498, fixes #43.

  • 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.DB(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.quote = self.database._quote
64        except AttributeError : # pg <v4.x
65            self.quote = pg._quote
66        try :
67            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
68        except PGError, msg :
69            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
70        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
71
72    def close(self) :
73        """Closes the database connection."""
74        if not self.closed :
75            self.database.close()
76            self.closed = 1
77            self.tool.logdebug("Database closed.")
78
79    def beginTransaction(self) :
80        """Starts a transaction."""
81        self.before = time.time()
82        self.database.query("BEGIN;")
83        self.tool.logdebug("Transaction begins...")
84
85    def commitTransaction(self) :
86        """Commits a transaction."""
87        self.database.query("COMMIT;")
88        after = time.time()
89        self.tool.logdebug("Transaction committed.")
90        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
91
92    def rollbackTransaction(self) :
93        """Rollbacks a transaction."""
94        self.database.query("ROLLBACK;")
95        after = time.time()
96        self.tool.logdebug("Transaction aborted.")
97        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
98
99    def doRawSearch(self, query) :
100        """Does a raw search query."""
101        query = query.strip()
102        if not query.endswith(';') :
103            query += ';'
104        try :
105            before = time.time()
106            self.tool.logdebug("QUERY : %s" % query)
107            result = self.database.query(query)
108        except PGError, msg :
109            raise PyKotaStorageError, str(msg)
110        else :
111            after = time.time()
112            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
113            return result
114
115    def doSearch(self, query) :
116        """Does a search query."""
117        result = self.doRawSearch(query)
118        if (result is not None) and (result.ntuples() > 0) :
119            return result.dictresult()
120
121    def doModify(self, query) :
122        """Does a (possibly multiple) modify query."""
123        query = query.strip()
124        if not query.endswith(';') :
125            query += ';'
126        try :
127            before = time.time()
128            self.tool.logdebug("QUERY : %s" % query)
129            result = self.database.query(query)
130        except PGError, msg :
131            self.tool.logdebug("Query failed : %s" % repr(msg))
132            raise PyKotaStorageError, str(msg)
133        else :
134            after = time.time()
135            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
136            return result
137
138    def doQuote(self, field) :
139        """Quotes a field for use as a string in SQL queries."""
140        if type(field) == type(0.0) :
141            typ = "decimal"
142        elif type(field) == type(0) :
143            typ = "int"
144        elif type(field) == type(0L) :
145            typ = "int"
146        else :
147            typ = "text"
148        return self.quote(field, typ)
149
150    def prepareRawResult(self, result) :
151        """Prepares a raw result by including the headers."""
152        if result.ntuples() > 0 :
153            entries = [result.listfields()]
154            entries.extend(result.getresult())
155            nbfields = len(entries[0])
156            for i in range(1, len(entries)) :
157                fields = list(entries[i])
158                for j in range(nbfields) :
159                    field = fields[j]
160                    if type(field) == StringType :
161                        fields[j] = self.databaseToUserCharset(field)
162                entries[i] = tuple(fields)
163            return entries
Note: See TracBrowser for help on using the browser.