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

Revision 2033, 8.4 kB (checked in by jalet, 19 years ago)

Convert PygreSQL's new exception into a string before re-raising it

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.39  2005/01/19 08:56:30  jalet
25# Convert PygreSQL's new exception into a string before re-raising it
26#
27# Revision 1.38  2005/01/19 08:48:17  jalet
28# Fix exception's name wrt newer versions of PygreSQL
29#
30# Revision 1.37  2004/09/14 22:29:12  jalet
31# First version of dumpykota. Works fine but only with PostgreSQL backend
32# for now.
33#
34# Revision 1.36  2004/06/03 23:14:11  jalet
35# Now stores the job's size in bytes in the database.
36# Preliminary work on payments storage : database schemas are OK now,
37# but no code to store payments yet.
38# Removed schema picture, not relevant anymore.
39#
40# Revision 1.35  2004/02/02 22:44:16  jalet
41# Preliminary work on Relationnal Database Independance via DB-API 2.0
42#
43# Revision 1.34  2004/01/12 15:12:50  jalet
44# Small fix for history
45#
46# Revision 1.33  2004/01/12 14:44:47  jalet
47# Missing space in SQL query
48#
49# Revision 1.32  2004/01/12 14:35:02  jalet
50# Printing history added to CGI script.
51#
52# Revision 1.31  2004/01/10 09:44:02  jalet
53# Fixed potential accuracy problem if a user printed on several printers at
54# the very same time.
55#
56# Revision 1.30  2004/01/08 16:33:27  jalet
57# Additionnal check to not create a circular printers group.
58#
59# Revision 1.29  2004/01/08 16:24:49  jalet
60# edpykota now supports adding printers to printer groups.
61#
62# Revision 1.28  2004/01/08 14:10:33  jalet
63# Copyright year changed.
64#
65# Revision 1.27  2004/01/06 14:24:59  jalet
66# Printer groups should be cached now, if caching is enabled.
67#
68# Revision 1.26  2003/12/29 14:12:48  uid67467
69# Tries to workaround possible integrity violations when retrieving printer groups
70#
71# Revision 1.25  2003/12/27 16:49:25  uid67467
72# Should be ok now.
73#
74# Revision 1.24  2003/11/29 22:02:14  jalet
75# Don't try to retrieve the user print quota information if current printer
76# doesn't exist.
77#
78# Revision 1.23  2003/11/23 19:01:37  jalet
79# Job price added to history
80#
81# Revision 1.22  2003/11/21 14:28:46  jalet
82# More complete job history.
83#
84# Revision 1.21  2003/11/12 13:06:38  jalet
85# Bug fix wrt no user/group name command line argument to edpykota
86#
87# Revision 1.20  2003/10/09 21:25:26  jalet
88# Multiple printer names or wildcards can be passed on the command line
89# separated with commas.
90# Beta phase.
91#
92# Revision 1.19  2003/10/08 07:01:20  jalet
93# Job history can be disabled.
94# Some typos in README.
95# More messages in setup script.
96#
97# Revision 1.18  2003/10/07 09:07:30  jalet
98# Character encoding added to please latest version of Python
99#
100# Revision 1.17  2003/10/06 13:12:28  jalet
101# More work on caching
102#
103# Revision 1.16  2003/10/03 18:01:49  jalet
104# Nothing interesting...
105#
106# Revision 1.15  2003/10/03 12:27:03  jalet
107# Several optimizations, especially with LDAP backend
108#
109# Revision 1.14  2003/10/03 08:57:55  jalet
110# Caching mechanism now caches all that's cacheable.
111#
112# Revision 1.13  2003/10/02 20:23:18  jalet
113# Storage caching mechanism added.
114#
115# Revision 1.12  2003/08/17 14:20:25  jalet
116# Bug fix by Oleg Biteryakov
117#
118# Revision 1.11  2003/07/29 20:55:17  jalet
119# 1.14 is out !
120#
121# Revision 1.10  2003/07/16 21:53:08  jalet
122# Really big modifications wrt new configuration file's location and content.
123#
124# Revision 1.9  2003/07/14 17:20:15  jalet
125# Bug in postgresql storage when modifying the prices for a printer
126#
127# Revision 1.8  2003/07/14 14:18:17  jalet
128# Wrong documentation strings
129#
130# Revision 1.7  2003/07/09 20:17:07  jalet
131# Email field added to PostgreSQL schema
132#
133# Revision 1.6  2003/07/07 11:49:24  jalet
134# Lots of small fixes with the help of PyChecker
135#
136# Revision 1.5  2003/07/07 08:33:19  jalet
137# Bug fix due to a typo in LDAP code
138#
139# Revision 1.4  2003/06/30 13:54:21  jalet
140# Sorts by user / group name
141#
142# Revision 1.3  2003/06/25 14:10:01  jalet
143# Hey, it may work (edpykota --reset excepted) !
144#
145# Revision 1.2  2003/06/12 21:09:57  jalet
146# wrongly placed code.
147#
148# Revision 1.1  2003/06/10 16:37:54  jalet
149# Deletion of the second user which is not needed anymore.
150# Added a debug configuration field in /etc/pykota.conf
151# All queries can now be sent to the logger in debug mode, this will
152# greatly help improve performance when time for this will come.
153#
154#
155#
156#
157
158from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
159from pykota.storages.sql import SQLStorage
160
161try :
162    import pg
163except ImportError :   
164    import sys
165    # TODO : to translate or not to translate ?
166    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
167else :   
168    try :
169        PGError = pg.Error
170    except AttributeError :   
171        PGError = pg.error
172
173class Storage(BaseStorage, SQLStorage) :
174    def __init__(self, pykotatool, host, dbname, user, passwd) :
175        """Opens the PostgreSQL database connection."""
176        BaseStorage.__init__(self, pykotatool)
177        try :
178            (host, port) = host.split(":")
179            port = int(port)
180        except ValueError :   
181            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
182       
183        try :
184            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
185        except PGError, msg :
186            raise PyKotaStorageError, str(msg)
187        else :   
188            self.closed = 0
189            self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
190           
191    def close(self) :   
192        """Closes the database connection."""
193        if not self.closed :
194            self.database.close()
195            self.closed = 1
196            self.tool.logdebug("Database closed.")
197       
198    def beginTransaction(self) :   
199        """Starts a transaction."""
200        self.database.query("BEGIN;")
201        self.tool.logdebug("Transaction begins...")
202       
203    def commitTransaction(self) :   
204        """Commits a transaction."""
205        self.database.query("COMMIT;")
206        self.tool.logdebug("Transaction committed.")
207       
208    def rollbackTransaction(self) :     
209        """Rollbacks a transaction."""
210        self.database.query("ROLLBACK;")
211        self.tool.logdebug("Transaction aborted.")
212       
213    def doRawSearch(self, query) :
214        """Does a raw search query."""
215        query = query.strip()   
216        if not query.endswith(';') :   
217            query += ';'
218        try :
219            self.tool.logdebug("QUERY : %s" % query)
220            result = self.database.query(query)
221        except PGError, msg :   
222            raise PyKotaStorageError, str(msg)
223        else :   
224            return result
225           
226    def doSearch(self, query) :       
227        """Does a search query."""
228        result = self.doRawSearch(query)
229        if (result is not None) and (result.ntuples() > 0) : 
230            return result.dictresult()
231       
232    def doModify(self, query) :
233        """Does a (possibly multiple) modify query."""
234        query = query.strip()   
235        if not query.endswith(';') :   
236            query += ';'
237        try :
238            self.tool.logdebug("QUERY : %s" % query)
239            result = self.database.query(query)
240        except PGError, msg :   
241            raise PyKotaStorageError, str(msg)
242        else :   
243            return result
244           
245    def doQuote(self, field) :
246        """Quotes a field for use as a string in SQL queries."""
247        if type(field) == type(0.0) : 
248            typ = "decimal"
249        elif type(field) == type(0) :   
250            typ = "int"
251        elif type(field) == type(0L) :   
252            typ = "int"
253        else :   
254            typ = "text"
255        return pg._quote(field, typ)
Note: See TracBrowser for help on using the browser.