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
Line 
1# -*- coding: utf-8 -*-*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003-2009 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)..." % (repr(host),
56                                                                                                  repr(port),
57                                                                                                  repr(dbname),
58                                                                                                  repr(user)))
59        try :
60            self.database = pg.connect(host=host,
61                                       port=port,
62                                       dbname=dbname,
63                                       user=user,
64                                       passwd=passwd)
65        except PGError, msg :
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
68        self.closed = False
69        try :
70            self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
71        except PGError, msg :
72            self.tool.logdebug("Impossible to set database client encoding to UTF-8 : %s" % msg)
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)))
77
78    def close(self) :
79        """Closes the database connection."""
80        if not self.closed :
81            self.database.close()
82            self.closed = True
83            self.tool.logdebug("Database closed.")
84
85    def beginTransaction(self) :
86        """Starts a transaction."""
87        self.database.query("BEGIN;")
88        self.tool.logdebug("Transaction begins...")
89
90    def commitTransaction(self) :
91        """Commits a transaction."""
92        self.database.query("COMMIT;")
93        self.tool.logdebug("Transaction committed.")
94
95    def rollbackTransaction(self) :
96        """Rollbacks a transaction."""
97        self.database.query("ROLLBACK;")
98        self.tool.logdebug("Transaction aborted.")
99
100    def doRawSearch(self, query) :
101        """Does a raw search query."""
102        query = query.strip()
103        if not query.endswith(';') :
104            query += ';'
105        try :
106            self.querydebug("QUERY : %s" % query)
107            return self.database.query(query)
108        except PGError, msg :
109            raise PyKotaStorageError, repr(msg)
110
111    def doSearch(self, query) :
112        """Does a search query."""
113        result = self.doRawSearch(query)
114        if (result is not None) and (result.ntuples() > 0) :
115            return result.dictresult()
116
117    def doModify(self, query) :
118        """Does a (possibly multiple) modify query."""
119        query = query.strip()
120        if not query.endswith(';') :
121            query += ';'
122        try :
123            self.querydebug("QUERY : %s" % query)
124            return self.database.query(query)
125        except PGError, msg :
126            self.tool.logdebug("Query failed : %s" % repr(msg))
127            raise PyKotaStorageError, repr(msg)
128
129    def doQuote(self, field) :
130        """Quotes a field for use as a string in SQL queries."""
131        if type(field) == type(0.0) :
132            typ = "decimal"
133        elif type(field) == type(0) :
134            typ = "int"
135        elif type(field) == type(0L) :
136            typ = "int"
137        else :
138            typ = "text"
139        return pg._quote(field, typ)
140
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 :
152                        fields[j] = databaseToUnicode(field)
153                entries[i] = tuple(fields)
154            return entries
Note: See TracBrowser for help on using the browser.