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

Revision 3413, 5.2 kB (checked in by jerome, 16 years ago)

Removed unnecessary spaces at EOL.

  • 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.
[3413]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.
[3413]15#
[1021]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
[3413]31from pykota.utils import *
[3294]32
[1021]33try :
34    import pg
[3413]35except ImportError :
[1021]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]
[3413]39else :
[2031]40    try :
41        PGError = pg.Error
[3413]42    except AttributeError :
[2031]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)
[3413]52        except ValueError :
[2874]53            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
[3413]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)
[3413]58        except PGError, msg :
[3182]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';")
[3413]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))
[3413]67
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.")
[3413]74
75    def beginTransaction(self) :
[1041]76        """Starts a transaction."""
77        self.database.query("BEGIN;")
[1130]78        self.tool.logdebug("Transaction begins...")
[3413]79
80    def commitTransaction(self) :
[1041]81        """Commits a transaction."""
82        self.database.query("COMMIT;")
[1130]83        self.tool.logdebug("Transaction committed.")
[3413]84
85    def rollbackTransaction(self) :
[1041]86        """Rollbacks a transaction."""
87        self.database.query("ROLLBACK;")
[1130]88        self.tool.logdebug("Transaction aborted.")
[3413]89
[1717]90    def doRawSearch(self, query) :
91        """Does a raw search query."""
[3413]92        query = query.strip()
93        if not query.endswith(';') :
[1021]94            query += ';'
95        try :
[3294]96            self.querydebug("QUERY : %s" % query)
[3308]97            return self.database.query(query)
[3413]98        except PGError, msg :
[3308]99            raise PyKotaStorageError, repr(msg)
[3413]100
101    def doSearch(self, query) :
[1717]102        """Does a search query."""
103        result = self.doRawSearch(query)
[3413]104        if (result is not None) and (result.ntuples() > 0) :
[1717]105            return result.dictresult()
[3413]106
[1041]107    def doModify(self, query) :
108        """Does a (possibly multiple) modify query."""
[3413]109        query = query.strip()
110        if not query.endswith(';') :
[1041]111            query += ';'
112        try :
[3294]113            self.querydebug("QUERY : %s" % query)
[3308]114            return self.database.query(query)
[3413]115        except PGError, msg :
[2773]116            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]117            raise PyKotaStorageError, repr(msg)
[3413]118
[1021]119    def doQuote(self, field) :
120        """Quotes a field for use as a string in SQL queries."""
[3413]121        if type(field) == type(0.0) :
[1021]122            typ = "decimal"
[3413]123        elif type(field) == type(0) :
[1021]124            typ = "int"
[3413]125        elif type(field) == type(0L) :
[1520]126            typ = "int"
[3413]127        else :
[1021]128            typ = "text"
129        return pg._quote(field, typ)
[3413]130
[2593]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 :
[3413]142                        fields[j] = databaseToUnicode(field)
143                entries[i] = tuple(fields)
[2593]144            return entries
Note: See TracBrowser for help on using the browser.