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
Line 
1# -*- coding: utf-8 -*-*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
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
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21#
22
23"""This module defines a class to access to a PostgreSQL database backend."""
24
25from types import StringType
26
27from pykota.errors import PyKotaStorageError
28from pykota.storage import BaseStorage
29from pykota.storages.sql import SQLStorage
30
31from pykota.utils import *                           
32
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]
39else :   
40    try :
41        PGError = pg.Error
42    except AttributeError :   
43        PGError = pg.error
44
45class Storage(BaseStorage, SQLStorage) :
46    def __init__(self, pykotatool, host, dbname, user, passwd) :
47        """Opens the PostgreSQL database connection."""
48        BaseStorage.__init__(self, pykotatool)
49        try :
50            (host, port) = host.split(":")
51            port = int(port)
52        except ValueError :   
53            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
54       
55        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
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
61        self.closed = 0
62        try :
63            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
64        except PGError, msg :   
65            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
66        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
67           
68    def close(self) :   
69        """Closes the database connection."""
70        if not self.closed :
71            self.database.close()
72            self.closed = 1
73            self.tool.logdebug("Database closed.")
74       
75    def beginTransaction(self) :   
76        """Starts a transaction."""
77        self.database.query("BEGIN;")
78        self.tool.logdebug("Transaction begins...")
79       
80    def commitTransaction(self) :   
81        """Commits a transaction."""
82        self.database.query("COMMIT;")
83        self.tool.logdebug("Transaction committed.")
84       
85    def rollbackTransaction(self) :     
86        """Rollbacks a transaction."""
87        self.database.query("ROLLBACK;")
88        self.tool.logdebug("Transaction aborted.")
89       
90    def doRawSearch(self, query) :
91        """Does a raw search query."""
92        query = query.strip()   
93        if not query.endswith(';') :   
94            query += ';'
95        try :
96            self.querydebug("QUERY : %s" % query)
97            return self.database.query(query)
98        except PGError, msg :   
99            raise PyKotaStorageError, repr(msg)
100           
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       
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 :
113            self.querydebug("QUERY : %s" % query)
114            return self.database.query(query)
115        except PGError, msg :   
116            self.tool.logdebug("Query failed : %s" % repr(msg))
117            raise PyKotaStorageError, repr(msg)
118           
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"
125        elif type(field) == type(0L) :   
126            typ = "int"
127        else :   
128            typ = "text"
129        return pg._quote(field, typ)
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 :
142                        fields[j] = databaseToUnicode(field) 
143                entries[i] = tuple(fields)   
144            return entries
145       
Note: See TracBrowser for help on using the browser.