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

Revision 3481, 6.0 kB (checked in by jerome, 15 years ago)

Changed copyright years.
Copyright years are now dynamic when displayed by a command line tool.

  • 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#
[3481]5# (c) 2003-2009 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
[3419]55        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (repr(host),
56                                                                                                  repr(port),
57                                                                                                  repr(dbname),
58                                                                                                  repr(user)))
[3182]59        try :
[3419]60            self.database = pg.connect(host=host,
61                                       port=port,
62                                       dbname=dbname,
63                                       user=user,
64                                       passwd=passwd)
[3413]65        except PGError, msg :
[3182]66            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()
67            raise PGError, msg
[3419]68        self.closed = False
[2960]69        try :
70            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
[3413]71        except PGError, msg :
[2972]72            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
[3419]73        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (repr(host),
74                                                                                       repr(port),
75                                                                                       repr(dbname),
76                                                                                       repr(user)))
[3413]77
78    def close(self) :
[1021]79        """Closes the database connection."""
80        if not self.closed :
81            self.database.close()
[3419]82            self.closed = True
[1130]83            self.tool.logdebug("Database closed.")
[3413]84
85    def beginTransaction(self) :
[1041]86        """Starts a transaction."""
87        self.database.query("BEGIN;")
[1130]88        self.tool.logdebug("Transaction begins...")
[3413]89
90    def commitTransaction(self) :
[1041]91        """Commits a transaction."""
92        self.database.query("COMMIT;")
[1130]93        self.tool.logdebug("Transaction committed.")
[3413]94
95    def rollbackTransaction(self) :
[1041]96        """Rollbacks a transaction."""
97        self.database.query("ROLLBACK;")
[1130]98        self.tool.logdebug("Transaction aborted.")
[3413]99
[1717]100    def doRawSearch(self, query) :
101        """Does a raw search query."""
[3413]102        query = query.strip()
103        if not query.endswith(';') :
[1021]104            query += ';'
105        try :
[3294]106            self.querydebug("QUERY : %s" % query)
[3308]107            return self.database.query(query)
[3413]108        except PGError, msg :
[3308]109            raise PyKotaStorageError, repr(msg)
[3413]110
111    def doSearch(self, query) :
[1717]112        """Does a search query."""
113        result = self.doRawSearch(query)
[3413]114        if (result is not None) and (result.ntuples() > 0) :
[1717]115            return result.dictresult()
[3413]116
[1041]117    def doModify(self, query) :
118        """Does a (possibly multiple) modify query."""
[3413]119        query = query.strip()
120        if not query.endswith(';') :
[1041]121            query += ';'
122        try :
[3294]123            self.querydebug("QUERY : %s" % query)
[3308]124            return self.database.query(query)
[3413]125        except PGError, msg :
[2773]126            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]127            raise PyKotaStorageError, repr(msg)
[3413]128
[1021]129    def doQuote(self, field) :
130        """Quotes a field for use as a string in SQL queries."""
[3413]131        if type(field) == type(0.0) :
[1021]132            typ = "decimal"
[3413]133        elif type(field) == type(0) :
[1021]134            typ = "int"
[3413]135        elif type(field) == type(0L) :
[1520]136            typ = "int"
[3413]137        else :
[1021]138            typ = "text"
139        return pg._quote(field, typ)
[3413]140
[2593]141    def prepareRawResult(self, result) :
142        """Prepares a raw result by including the headers."""
143        if result.ntuples() > 0 :
144            entries = [result.listfields()]
145            entries.extend(result.getresult())
146            nbfields = len(entries[0])
147            for i in range(1, len(entries)) :
148                fields = list(entries[i])
149                for j in range(nbfields) :
150                    field = fields[j]
151                    if type(field) == StringType :
[3413]152                        fields[j] = databaseToUnicode(field)
153                entries[i] = tuple(fields)
[2593]154            return entries
Note: See TracBrowser for help on using the browser.