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
RevLine 
[3260]1# -*- coding: UTF-8 -*-
[1021]2#
[3260]3# PyKota : Print Quotas for CUPS
[1021]4#
[3275]5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
[3260]6# This program is free software: you can redistribute it and/or modify
[1021]7# it under the terms of the GNU General Public License as published by
[3260]8# the Free Software Foundation, either version 3 of the License, or
[1021]9# (at your option) any later version.
[3260]10#
[1021]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
[3260]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[1021]18#
19# $Id$
20#
[2033]21#
[1021]22
[3184]23"""This module defines a class to access to a PostgreSQL database backend."""
24
[2741]25import time
[2599]26from types import StringType
27
[3288]28from pykota.errors import PyKotaStorageError
29from pykota.storage import BaseStorage
[1327]30from pykota.storages.sql import SQLStorage
[1021]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]
[2031]38else :   
39    try :
40        PGError = pg.Error
41    except AttributeError :   
42        PGError = pg.error
[1021]43
[1327]44class Storage(BaseStorage, SQLStorage) :
[1021]45    def __init__(self, pykotatool, host, dbname, user, passwd) :
46        """Opens the PostgreSQL database connection."""
[1130]47        BaseStorage.__init__(self, pykotatool)
[1021]48        try :
49            (host, port) = host.split(":")
50            port = int(port)
51        except ValueError :   
[2874]52            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
[1021]53       
[2418]54        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
[3182]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
[2210]60        self.closed = 0
[2960]61        try :
62            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
63        except PGError, msg :   
[2972]64            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
[2210]65        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
[1021]66           
[1113]67    def close(self) :   
[1021]68        """Closes the database connection."""
69        if not self.closed :
70            self.database.close()
71            self.closed = 1
[1130]72            self.tool.logdebug("Database closed.")
[1021]73       
[1041]74    def beginTransaction(self) :   
75        """Starts a transaction."""
[2741]76        self.before = time.time()
[1041]77        self.database.query("BEGIN;")
[1130]78        self.tool.logdebug("Transaction begins...")
[1041]79       
80    def commitTransaction(self) :   
81        """Commits a transaction."""
82        self.database.query("COMMIT;")
[2741]83        after = time.time()
[1130]84        self.tool.logdebug("Transaction committed.")
[3182]85        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]86       
87    def rollbackTransaction(self) :     
88        """Rollbacks a transaction."""
89        self.database.query("ROLLBACK;")
[2741]90        after = time.time()
[1130]91        self.tool.logdebug("Transaction aborted.")
[3182]92        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[1041]93       
[1717]94    def doRawSearch(self, query) :
95        """Does a raw search query."""
[1021]96        query = query.strip()   
97        if not query.endswith(';') :   
98            query += ';'
99        try :
[2741]100            before = time.time()
[1130]101            self.tool.logdebug("QUERY : %s" % query)
[1021]102            result = self.database.query(query)
[2031]103        except PGError, msg :   
[2033]104            raise PyKotaStorageError, str(msg)
[1021]105        else :   
[2741]106            after = time.time()
[3182]107            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1717]108            return result
[1041]109           
[1717]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       
[1041]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 :
[2741]122            before = time.time()
[1130]123            self.tool.logdebug("QUERY : %s" % query)
[1041]124            result = self.database.query(query)
[2031]125        except PGError, msg :   
[2773]126            self.tool.logdebug("Query failed : %s" % repr(msg))
[2033]127            raise PyKotaStorageError, str(msg)
[1068]128        else :   
[2741]129            after = time.time()
[3182]130            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[1068]131            return result
[1041]132           
[1021]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"
[1520]139        elif type(field) == type(0L) :   
140            typ = "int"
[1021]141        else :   
142            typ = "text"
143        return pg._quote(field, typ)
[2593]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 :
[3291]156                        fields[j] = self.databaseToUnicode(field) 
[2593]157                entries[i] = tuple(fields)   
158            return entries
159       
Note: See TracBrowser for help on using the browser.