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

Revision 3527, 6.1 kB (checked in by jerome, 14 years ago)

Moved some code around.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3489]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 :
[3499]60            self.database = pg.DB(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 :
[3499]70            self.quote = self.database._quote
71        except AttributeError : # pg <v4.x
72            self.quote = pg._quote
73        try :
[2960]74            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
[3413]75        except PGError, msg :
[2972]76            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
[3419]77        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (repr(host),
78                                                                                       repr(port),
79                                                                                       repr(dbname),
80                                                                                       repr(user)))
[3413]81
82    def close(self) :
[1021]83        """Closes the database connection."""
84        if not self.closed :
85            self.database.close()
[3419]86            self.closed = True
[1130]87            self.tool.logdebug("Database closed.")
[3413]88
89    def beginTransaction(self) :
[1041]90        """Starts a transaction."""
91        self.database.query("BEGIN;")
[1130]92        self.tool.logdebug("Transaction begins...")
[3413]93
94    def commitTransaction(self) :
[1041]95        """Commits a transaction."""
96        self.database.query("COMMIT;")
[1130]97        self.tool.logdebug("Transaction committed.")
[3413]98
99    def rollbackTransaction(self) :
[1041]100        """Rollbacks a transaction."""
101        self.database.query("ROLLBACK;")
[1130]102        self.tool.logdebug("Transaction aborted.")
[3413]103
[1717]104    def doRawSearch(self, query) :
105        """Does a raw search query."""
[3413]106        query = query.strip()
107        if not query.endswith(';') :
[1021]108            query += ';'
[3527]109        self.querydebug("QUERY : %s" % query)
[1021]110        try :
[3308]111            return self.database.query(query)
[3413]112        except PGError, msg :
[3308]113            raise PyKotaStorageError, repr(msg)
[3413]114
115    def doSearch(self, query) :
[1717]116        """Does a search query."""
117        result = self.doRawSearch(query)
[3413]118        if (result is not None) and (result.ntuples() > 0) :
[1717]119            return result.dictresult()
[3413]120
[1041]121    def doModify(self, query) :
122        """Does a (possibly multiple) modify query."""
[3413]123        query = query.strip()
124        if not query.endswith(';') :
[1041]125            query += ';'
[3527]126        self.querydebug("QUERY : %s" % query)
[1041]127        try :
[3308]128            return self.database.query(query)
[3413]129        except PGError, msg :
[2773]130            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]131            raise PyKotaStorageError, repr(msg)
[3413]132
[1021]133    def doQuote(self, field) :
134        """Quotes a field for use as a string in SQL queries."""
[3413]135        if type(field) == type(0.0) :
[1021]136            typ = "decimal"
[3413]137        elif type(field) == type(0) :
[1021]138            typ = "int"
[3413]139        elif type(field) == type(0L) :
[1520]140            typ = "int"
[3413]141        else :
[1021]142            typ = "text"
[3499]143        return self.quote(field, typ)
[3413]144
[2593]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 :
[3413]156                        fields[j] = databaseToUnicode(field)
157                entries[i] = tuple(fields)
[2593]158            return entries
Note: See TracBrowser for help on using the browser.