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

Revision 2954, 5.6 kB (checked in by jerome, 18 years ago)

Ensures that the databases are created with UTF-8 encoding, and that the
client tells that we will always use UTF-8 when sending datas to the server
or retrieving them.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import time
26from types import StringType
27
28from pykota.storage import PyKotaStorageError, BaseStorage
29from pykota.storages.sql import SQLStorage
30
31try :
32    import pg
33except ImportError :   
34    import sys
35    # TODO : to translate or not to translate ?
36    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
37else :   
38    try :
39        PGError = pg.Error
40    except AttributeError :   
41        PGError = pg.error
42
43class Storage(BaseStorage, SQLStorage) :
44    def __init__(self, pykotatool, host, dbname, user, passwd) :
45        """Opens the PostgreSQL database connection."""
46        BaseStorage.__init__(self, pykotatool)
47        try :
48            (host, port) = host.split(":")
49            port = int(port)
50        except ValueError :   
51            port = 5432         # Use PostgreSQL's default tcp/ip port (5432).
52       
53        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
54        self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
55        self.closed = 0
56        self.database.query("SET CLIENT_ENCODING TO 'UTF-8';")
57        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
58           
59    def close(self) :   
60        """Closes the database connection."""
61        if not self.closed :
62            self.database.close()
63            self.closed = 1
64            self.tool.logdebug("Database closed.")
65       
66    def beginTransaction(self) :   
67        """Starts a transaction."""
68        self.before = time.time()
69        self.database.query("BEGIN;")
70        self.tool.logdebug("Transaction begins...")
71       
72    def commitTransaction(self) :   
73        """Commits a transaction."""
74        self.database.query("COMMIT;")
75        after = time.time()
76        self.tool.logdebug("Transaction committed.")
77        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
78       
79    def rollbackTransaction(self) :     
80        """Rollbacks a transaction."""
81        self.database.query("ROLLBACK;")
82        after = time.time()
83        self.tool.logdebug("Transaction aborted.")
84        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
85       
86    def doRawSearch(self, query) :
87        """Does a raw search query."""
88        query = query.strip()   
89        if not query.endswith(';') :   
90            query += ';'
91        try :
92            before = time.time()
93            self.tool.logdebug("QUERY : %s" % query)
94            result = self.database.query(query)
95        except PGError, msg :   
96            raise PyKotaStorageError, str(msg)
97        else :   
98            after = time.time()
99            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
100            return result
101           
102    def doSearch(self, query) :       
103        """Does a search query."""
104        result = self.doRawSearch(query)
105        if (result is not None) and (result.ntuples() > 0) : 
106            return result.dictresult()
107       
108    def doModify(self, query) :
109        """Does a (possibly multiple) modify query."""
110        query = query.strip()   
111        if not query.endswith(';') :   
112            query += ';'
113        try :
114            before = time.time()
115            self.tool.logdebug("QUERY : %s" % query)
116            result = self.database.query(query)
117        except PGError, msg :   
118            self.tool.logdebug("Query failed : %s" % repr(msg))
119            raise PyKotaStorageError, str(msg)
120        else :   
121            after = time.time()
122            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
123            return result
124           
125    def doQuote(self, field) :
126        """Quotes a field for use as a string in SQL queries."""
127        if type(field) == type(0.0) : 
128            typ = "decimal"
129        elif type(field) == type(0) :   
130            typ = "int"
131        elif type(field) == type(0L) :   
132            typ = "int"
133        else :   
134            typ = "text"
135        return pg._quote(field, typ)
136       
137    def prepareRawResult(self, result) :
138        """Prepares a raw result by including the headers."""
139        if result.ntuples() > 0 :
140            entries = [result.listfields()]
141            entries.extend(result.getresult())
142            nbfields = len(entries[0])
143            for i in range(1, len(entries)) :
144                fields = list(entries[i])
145                for j in range(nbfields) :
146                    field = fields[j]
147                    if type(field) == StringType :
148                        fields[j] = self.databaseToUserCharset(field) 
149                entries[i] = tuple(fields)   
150            return entries
151       
Note: See TracBrowser for help on using the browser.