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

Revision 3260, 6.0 kB (checked in by jerome, 16 years ago)

Changed license to GNU GPL v3 or later.
Changed Python source encoding from ISO-8859-15 to UTF-8 (only ASCII
was used anyway).

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