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

Revision 3291, 6.1 kB (checked in by jerome, 16 years ago)

Database backends now convert from and to unicode instead of UTF-8.
The data dumper now expects unicode datas from the database.

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