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

Revision 2874, 5.5 kB (checked in by jerome, 18 years ago)

Explicitely sets the default TCP ports to use, because it seems that once again, MySQL fails to be smart...

  • 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.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
57           
58    def close(self) :   
59        """Closes the database connection."""
60        if not self.closed :
61            self.database.close()
62            self.closed = 1
63            self.tool.logdebug("Database closed.")
64       
65    def beginTransaction(self) :   
66        """Starts a transaction."""
67        self.before = time.time()
68        self.database.query("BEGIN;")
69        self.tool.logdebug("Transaction begins...")
70       
71    def commitTransaction(self) :   
72        """Commits a transaction."""
73        self.database.query("COMMIT;")
74        after = time.time()
75        self.tool.logdebug("Transaction committed.")
76        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
77       
78    def rollbackTransaction(self) :     
79        """Rollbacks a transaction."""
80        self.database.query("ROLLBACK;")
81        after = time.time()
82        self.tool.logdebug("Transaction aborted.")
83        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
84       
85    def doRawSearch(self, query) :
86        """Does a raw search query."""
87        query = query.strip()   
88        if not query.endswith(';') :   
89            query += ';'
90        try :
91            before = time.time()
92            self.tool.logdebug("QUERY : %s" % query)
93            result = self.database.query(query)
94        except PGError, msg :   
95            raise PyKotaStorageError, str(msg)
96        else :   
97            after = time.time()
98            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
99            return result
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            before = time.time()
114            self.tool.logdebug("QUERY : %s" % query)
115            result = self.database.query(query)
116        except PGError, msg :   
117            self.tool.logdebug("Query failed : %s" % repr(msg))
118            raise PyKotaStorageError, str(msg)
119        else :   
120            after = time.time()
121            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
122            return result
123           
124    def doQuote(self, field) :
125        """Quotes a field for use as a string in SQL queries."""
126        if type(field) == type(0.0) : 
127            typ = "decimal"
128        elif type(field) == type(0) :   
129            typ = "int"
130        elif type(field) == type(0L) :   
131            typ = "int"
132        else :   
133            typ = "text"
134        return pg._quote(field, typ)
135       
136    def prepareRawResult(self, result) :
137        """Prepares a raw result by including the headers."""
138        if result.ntuples() > 0 :
139            entries = [result.listfields()]
140            entries.extend(result.getresult())
141            nbfields = len(entries[0])
142            for i in range(1, len(entries)) :
143                fields = list(entries[i])
144                for j in range(nbfields) :
145                    field = fields[j]
146                    if type(field) == StringType :
147                        fields[j] = self.databaseToUserCharset(field) 
148                entries[i] = tuple(fields)   
149            return entries
150       
Note: See TracBrowser for help on using the browser.