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