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

Revision 2599, 5.0 kB (checked in by jerome, 18 years ago)

Fixed bad import, because some code moved

  • 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 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
25from types import StringType
26
27from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
28from pykota.storages.sql import SQLStorage
29
30try :
31    import pg
32except ImportError :   
33    import sys
34    # TODO : to translate or not to translate ?
35    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
36else :   
37    try :
38        PGError = pg.Error
39    except AttributeError :   
40        PGError = pg.error
41
42class Storage(BaseStorage, SQLStorage) :
43    def __init__(self, pykotatool, host, dbname, user, passwd) :
44        """Opens the PostgreSQL database connection."""
45        BaseStorage.__init__(self, pykotatool)
46        try :
47            (host, port) = host.split(":")
48            port = int(port)
49        except ValueError :   
50            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
51       
52        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
53        self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
54        self.closed = 0
55        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
56           
57    def close(self) :   
58        """Closes the database connection."""
59        if not self.closed :
60            self.database.close()
61            self.closed = 1
62            self.tool.logdebug("Database closed.")
63       
64    def beginTransaction(self) :   
65        """Starts a transaction."""
66        self.database.query("BEGIN;")
67        self.tool.logdebug("Transaction begins...")
68       
69    def commitTransaction(self) :   
70        """Commits a transaction."""
71        self.database.query("COMMIT;")
72        self.tool.logdebug("Transaction committed.")
73       
74    def rollbackTransaction(self) :     
75        """Rollbacks a transaction."""
76        self.database.query("ROLLBACK;")
77        self.tool.logdebug("Transaction aborted.")
78       
79    def doRawSearch(self, query) :
80        """Does a raw search query."""
81        query = query.strip()   
82        if not query.endswith(';') :   
83            query += ';'
84        try :
85            self.tool.logdebug("QUERY : %s" % query)
86            result = self.database.query(query)
87        except PGError, msg :   
88            raise PyKotaStorageError, str(msg)
89        else :   
90            return result
91           
92    def doSearch(self, query) :       
93        """Does a search query."""
94        result = self.doRawSearch(query)
95        if (result is not None) and (result.ntuples() > 0) : 
96            return result.dictresult()
97       
98    def doModify(self, query) :
99        """Does a (possibly multiple) modify query."""
100        query = query.strip()   
101        if not query.endswith(';') :   
102            query += ';'
103        try :
104            self.tool.logdebug("QUERY : %s" % query)
105            result = self.database.query(query)
106        except PGError, msg :   
107            raise PyKotaStorageError, str(msg)
108        else :   
109            return result
110           
111    def doQuote(self, field) :
112        """Quotes a field for use as a string in SQL queries."""
113        if type(field) == type(0.0) : 
114            typ = "decimal"
115        elif type(field) == type(0) :   
116            typ = "int"
117        elif type(field) == type(0L) :   
118            typ = "int"
119        else :   
120            typ = "text"
121        return pg._quote(field, typ)
122       
123    def prepareRawResult(self, result) :
124        """Prepares a raw result by including the headers."""
125        if result.ntuples() > 0 :
126            entries = [result.listfields()]
127            entries.extend(result.getresult())
128            nbfields = len(entries[0])
129            for i in range(1, len(entries)) :
130                fields = list(entries[i])
131                for j in range(nbfields) :
132                    field = fields[j]
133                    if type(field) == StringType :
134                        fields[j] = self.databaseToUserCharset(field) 
135                entries[i] = tuple(fields)   
136            return entries
137       
Note: See TracBrowser for help on using the browser.