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

Revision 3411, 5.4 kB (checked in by jerome, 16 years ago)

Minor change to please emacs...

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3411]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
[2599]25from types import StringType
26
[3288]27from pykota.errors import PyKotaStorageError
28from pykota.storage import BaseStorage
[1327]29from pykota.storages.sql import SQLStorage
[1021]30
[3294]31from pykota.utils import *                           
32
[1021]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]
[2031]39else :   
40    try :
41        PGError = pg.Error
42    except AttributeError :   
43        PGError = pg.error
[1021]44
[1327]45class Storage(BaseStorage, SQLStorage) :
[1021]46    def __init__(self, pykotatool, host, dbname, user, passwd) :
47        """Opens the PostgreSQL database connection."""
[1130]48        BaseStorage.__init__(self, pykotatool)
[1021]49        try :
50            (host, port) = host.split(":")
51            port = int(port)
52        except ValueError :   
[2874]53            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
[1021]54       
[2418]55        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
[3182]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
[2210]61        self.closed = 0
[2960]62        try :
63            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
64        except PGError, msg :   
[2972]65            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
[2210]66        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
[1021]67           
[1113]68    def close(self) :   
[1021]69        """Closes the database connection."""
70        if not self.closed :
71            self.database.close()
72            self.closed = 1
[1130]73            self.tool.logdebug("Database closed.")
[1021]74       
[1041]75    def beginTransaction(self) :   
76        """Starts a transaction."""
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;")
[1130]83        self.tool.logdebug("Transaction committed.")
[1041]84       
85    def rollbackTransaction(self) :     
86        """Rollbacks a transaction."""
87        self.database.query("ROLLBACK;")
[1130]88        self.tool.logdebug("Transaction aborted.")
[1041]89       
[1717]90    def doRawSearch(self, query) :
91        """Does a raw search query."""
[1021]92        query = query.strip()   
93        if not query.endswith(';') :   
94            query += ';'
95        try :
[3294]96            self.querydebug("QUERY : %s" % query)
[3308]97            return self.database.query(query)
[2031]98        except PGError, msg :   
[3308]99            raise PyKotaStorageError, repr(msg)
[1041]100           
[1717]101    def doSearch(self, query) :       
102        """Does a search query."""
103        result = self.doRawSearch(query)
104        if (result is not None) and (result.ntuples() > 0) : 
105            return result.dictresult()
106       
[1041]107    def doModify(self, query) :
108        """Does a (possibly multiple) modify query."""
109        query = query.strip()   
110        if not query.endswith(';') :   
111            query += ';'
112        try :
[3294]113            self.querydebug("QUERY : %s" % query)
[3308]114            return self.database.query(query)
[2031]115        except PGError, msg :   
[2773]116            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]117            raise PyKotaStorageError, repr(msg)
[1041]118           
[1021]119    def doQuote(self, field) :
120        """Quotes a field for use as a string in SQL queries."""
121        if type(field) == type(0.0) : 
122            typ = "decimal"
123        elif type(field) == type(0) :   
124            typ = "int"
[1520]125        elif type(field) == type(0L) :   
126            typ = "int"
[1021]127        else :   
128            typ = "text"
129        return pg._quote(field, typ)
[2593]130       
131    def prepareRawResult(self, result) :
132        """Prepares a raw result by including the headers."""
133        if result.ntuples() > 0 :
134            entries = [result.listfields()]
135            entries.extend(result.getresult())
136            nbfields = len(entries[0])
137            for i in range(1, len(entries)) :
138                fields = list(entries[i])
139                for j in range(nbfields) :
140                    field = fields[j]
141                    if type(field) == StringType :
[3294]142                        fields[j] = databaseToUnicode(field) 
[2593]143                entries[i] = tuple(fields)   
144            return entries
145       
Note: See TracBrowser for help on using the browser.