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

Revision 1024, 21.5 kB (checked in by jalet, 21 years ago)

wrongly placed code.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 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 2 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, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.2  2003/06/12 21:09:57  jalet
24# wrongly placed code.
25#
26# Revision 1.1  2003/06/10 16:37:54  jalet
27# Deletion of the second user which is not needed anymore.
28# Added a debug configuration field in /etc/pykota.conf
29# All queries can now be sent to the logger in debug mode, this will
30# greatly help improve performance when time for this will come.
31#
32#
33#
34#
35
36import fnmatch
37
38from pykota.storage import PyKotaStorageError
39
40try :
41    import pg
42except ImportError :   
43    import sys
44    # TODO : to translate or not to translate ?
45    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
46
47class Storage :
48    def __init__(self, pykotatool, host, dbname, user, passwd) :
49        """Opens the PostgreSQL database connection."""
50        self.tool = pykotatool
51        self.debug = pykotatool.config.getDebug()
52        self.closed = 1
53        try :
54            (host, port) = host.split(":")
55            port = int(port)
56        except ValueError :   
57            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
58       
59        try :
60            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
61        except pg.error, msg :
62            raise PyKotaStorageError, msg
63        else :   
64            self.closed = 0
65            if self.debug :
66                self.tool.logger.log_message("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user), "debug")
67           
68    def __del__(self) :       
69        """Closes the database connection."""
70        if not self.closed :
71            self.database.close()
72            self.closed = 1
73            if self.debug :
74                self.tool.logger.log_message("Database closed.", "debug")
75       
76    def doQuery(self, query) :
77        """Does a query."""
78        if type(query) in (type([]), type(())) :
79            query = ";".join(query)
80        query = query.strip()   
81        if not query.endswith(';') :   
82            query += ';'
83        self.database.query("BEGIN;")
84        if self.debug :
85            self.tool.logger.log_message("Transaction began.", "debug")
86        try :
87            if self.debug :
88                self.tool.logger.log_message("QUERY : %s" % query, "debug")
89            result = self.database.query(query)
90        except pg.error, msg :   
91            self.database.query("ROLLBACK;")
92            if self.debug :
93                self.tool.logger.log_message("Transaction aborted.", "debug")
94            raise PyKotaStorageError, msg
95        else :   
96            self.database.query("COMMIT;")
97            if self.debug :
98                self.tool.logger.log_message("Transaction committed.", "debug")
99            return result
100       
101    def doQuote(self, field) :
102        """Quotes a field for use as a string in SQL queries."""
103        if type(field) == type(0.0) : 
104            typ = "decimal"
105        elif type(field) == type(0) :   
106            typ = "int"
107        else :   
108            typ = "text"
109        return pg._quote(field, typ)
110       
111    def doParseResult(self, result) :
112        """Returns the result as a list of Python mappings."""
113        if (result is not None) and (result.ntuples() > 0) :
114            return result.dictresult()
115           
116    def getMatchingPrinters(self, printerpattern) :
117        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
118        printerslist = []
119        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
120        # but we don't because other storages semantics may be different, so every
121        # storage should use fnmatch to match patterns and be storage agnostic
122        result = self.doQuery("SELECT id, printername FROM printers")
123        result = self.doParseResult(result)
124        if result is not None :
125            for printer in result :
126                if fnmatch.fnmatchcase(printer["printername"], printerpattern) :
127                    printerslist.append((printer["id"], printer["printername"]))
128        return printerslist       
129           
130    def getPrinterId(self, printername) :       
131        """Returns a printerid given a printername."""
132        result = self.doQuery("SELECT id FROM printers WHERE printername=%s" % self.doQuote(printername))
133        try :
134            return self.doParseResult(result)[0]["id"]
135        except TypeError :      # Not found   
136            return
137           
138    def getPrinterPrices(self, printerid) :       
139        """Returns a printer prices per page and per job given a printerid."""
140        result = self.doQuery("SELECT priceperpage, priceperjob FROM printers WHERE id=%s" % self.doQuote(printerid))
141        try :
142            printerprices = self.doParseResult(result)[0]
143            return (printerprices["priceperpage"], printerprices["priceperjob"])
144        except TypeError :      # Not found   
145            return
146           
147    def setPrinterPrices(self, printerid, perpage, perjob) :
148        """Sets prices per job and per page for a given printer."""
149        self.doQuery("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(perpage), self.doQuote(perjob), self.doQuote(printerid)))
150   
151    def getUserId(self, username) :
152        """Returns a userid given a username."""
153        result = self.doQuery("SELECT id FROM users WHERE username=%s" % self.doQuote(username))
154        try :
155            return self.doParseResult(result)[0]["id"]
156        except TypeError :      # Not found
157            return
158           
159    def getGroupId(self, groupname) :
160        """Returns a groupid given a grupname."""
161        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
162        try :
163            return self.doParseResult(result)[0]["id"]
164        except TypeError :      # Not found
165            return
166           
167    def getJobHistoryId(self, jobid, userid, printerid) :       
168        """Returns the history line's id given a (jobid, userid, printerid)."""
169        result = self.doQuery("SELECT id FROM jobhistory WHERE jobid=%s AND userid=%s AND printerid=%s" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid)))
170        try :
171            return self.doParseResult(result)[0]["id"]
172        except TypeError :      # Not found   
173            return
174           
175    def getPrinterUsers(self, printerid) :       
176        """Returns the list of userids and usernames which uses a given printer."""
177        result = self.doQuery("SELECT DISTINCT id, username FROM users WHERE id IN (SELECT userid FROM userpquota WHERE printerid=%s) ORDER BY username" % self.doQuote(printerid))
178        result = self.doParseResult(result)
179        if result is None :
180            return []
181        else :   
182            return [(record["id"], record["username"]) for record in result]
183       
184    def getPrinterGroups(self, printerid) :       
185        """Returns the list of groups which uses a given printer."""
186        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s)" % self.doQuote(printerid))
187        result = self.doParseResult(result)
188        if result is None :
189            return []
190        else :   
191            return [(record["id"], record["groupname"]) for record in result]
192       
193    def getGroupMembersNames(self, groupname) :       
194        """Returns the list of user's names which are member of this group."""
195        groupid = self.getGroupId(groupname)
196        if groupid is None :
197            return []
198        else :
199            result = self.doQuery("SELECT DISTINCT username FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
200            return [record["username"] for record in (self.doParseResult(result) or [])]
201       
202    def getUserGroupsNames(self, userid) :       
203        """Returns the list of groups' names the user is a member of."""
204        result = self.doQuery("SELECT DISTINCT groupname FROM groups WHERE id IN (SELECT groupid FROM groupsmembers WHERE userid=%s)" % self.doQuote(userid))
205        return [record["groupname"] for record in (self.doParseResult(result) or [])]
206       
207    def addPrinter(self, printername) :       
208        """Adds a printer to the quota storage, returns its id."""
209        self.doQuery("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
210        return self.getPrinterId(printername)
211       
212    def addUser(self, username) :       
213        """Adds a user to the quota storage, returns its id."""
214        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
215        return self.getUserId(username)
216       
217    def addGroup(self, groupname) :       
218        """Adds a group to the quota storage, returns its id."""
219        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
220        return self.getGroupId(groupname)
221       
222    def addUserPQuota(self, username, printerid) :
223        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
224        userid = self.getUserId(username)     
225        if userid is None :   
226            userid = self.addUser(username)
227        uqexists = (self.getUserPQuota(userid, printerid) is not None)   
228        if not uqexists : 
229            self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
230        return (userid, printerid)
231       
232    def addGroupPQuota(self, groupname, printerid) :
233        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
234        groupid = self.getGroupId(groupname)     
235        if groupid is None :   
236            groupid = self.addGroup(groupname)
237        gqexists = (self.getGroupPQuota(groupid, printerid) is not None)   
238        if not gqexists : 
239            self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(printerid)))
240        return (groupid, printerid)
241       
242    def increaseUserBalance(self, userid, amount) :   
243        """Increases (or decreases) an user's account balance by a given amount."""
244        self.doQuery("UPDATE users SET balance=balance+(%s), lifetimepaid=lifetimepaid+(%s) WHERE id=%s" % (self.doQuote(amount), self.doQuote(amount), self.doQuote(userid)))
245       
246    def getUserBalance(self, userid) :   
247        """Returns the current account balance for a given user."""
248        result = self.doQuery("SELECT balance, lifetimepaid FROM users WHERE id=%s" % self.doQuote(userid))
249        try :
250            result = self.doParseResult(result)[0]
251        except TypeError :      # Not found   
252            return
253        else :   
254            return (result["balance"], result["lifetimepaid"])
255       
256    def getGroupBalance(self, groupid) :   
257        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
258        result = self.doQuery("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id in (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
259        try :
260            result = self.doParseResult(result)[0]
261        except TypeError :      # Not found   
262            return
263        else :   
264            return (result["balance"], result["lifetimepaid"])
265       
266    def getUserLimitBy(self, userid) :   
267        """Returns the way in which user printing is limited."""
268        result = self.doQuery("SELECT limitby FROM users WHERE id=%s" % self.doQuote(userid))
269        try :
270            return self.doParseResult(result)[0]["limitby"]
271        except TypeError :      # Not found   
272            return
273       
274    def getGroupLimitBy(self, groupid) :   
275        """Returns the way in which group printing is limited."""
276        result = self.doQuery("SELECT limitby FROM groups WHERE id=%s" % self.doQuote(groupid))
277        try :
278            return self.doParseResult(result)[0]["limitby"]
279        except TypeError :      # Not found   
280            return
281       
282    def setUserBalance(self, userid, balance) :   
283        """Sets the account balance for a given user to a fixed value."""
284        (current, lifetimepaid) = self.getUserBalance(userid)
285        difference = balance - current
286        self.increaseUserBalance(userid, difference)
287       
288    def limitUserBy(self, userid, limitby) :   
289        """Limits a given user based either on print quota or on account balance."""
290        self.doQuery("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(userid)))
291       
292    def limitGroupBy(self, groupid, limitby) :   
293        """Limits a given group based either on print quota or on sum of its users' account balances."""
294        self.doQuery("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(groupid)))
295       
296    def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
297        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
298        self.doQuery("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userid), self.doQuote(printerid)))
299       
300    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
301        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
302        self.doQuery("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(groupid), self.doQuote(printerid)))
303       
304    def resetUserPQuota(self, userid, printerid) :   
305        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
306        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
307       
308    def resetGroupPQuota(self, groupid, printerid) :   
309        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
310        self.doQuery("UPDATE grouppquota SET pagecounter=0, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
311       
312    def updateUserPQuota(self, userid, printerid, pagecount) :
313        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
314        jobprice = self.computePrinterJobPrice(printerid, pagecount)
315        queries = []   
316        queries.append("UPDATE userpquota SET lifepagecounter=lifepagecounter+(%s), pagecounter=pagecounter+(%s) WHERE userid=%s AND printerid=%s" % (self.doQuote(pagecount), self.doQuote(pagecount), self.doQuote(userid), self.doQuote(printerid)))
317        queries.append("UPDATE users SET balance=balance-(%s) WHERE id=%s" % (self.doQuote(jobprice), self.doQuote(userid)))
318        self.doQuery(queries)
319       
320    def getUserPQuota(self, userid, printerid) :
321        """Returns the Print Quota information for a given (userid, printerid)."""
322        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
323        try :
324            return self.doParseResult(result)[0]
325        except TypeError :      # Not found   
326            return
327       
328    def getGroupPQuota(self, groupid, printerid) :
329        """Returns the Print Quota information for a given (groupid, printerid)."""
330        result = self.doQuery("SELECT softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
331        try :
332            grouppquota = self.doParseResult(result)[0]
333        except TypeError :   
334            return
335        else :   
336            result = self.doQuery("SELECT SUM(lifepagecounter) as lifepagecounter, SUM(pagecounter) as pagecounter FROM userpquota WHERE printerid=%s AND userid in (SELECT userid FROM groupsmembers WHERE groupid=%s)" % (self.doQuote(printerid), self.doQuote(groupid)))
337            try :
338                result = self.doParseResult(result)[0]
339            except TypeError :      # Not found   
340                return
341            else :   
342                grouppquota.update({"lifepagecounter": result["lifepagecounter"], "pagecounter": result["pagecounter"]})
343                return grouppquota
344       
345    def setUserDateLimit(self, userid, printerid, datelimit) :
346        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
347        self.doQuery("UPDATE userpquota SET datelimit=%s::TIMESTAMP WHERE userid=%s AND printerid=%s" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(userid), self.doQuote(printerid)))
348       
349    def setGroupDateLimit(self, groupid, printerid, datelimit) :
350        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
351        self.doQuery("UPDATE grouppquota SET datelimit=%s::TIMESTAMP WHERE groupid=%s AND printerid=%s" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(groupid), self.doQuote(printerid)))
352       
353    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
354        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
355        self.doQuery("INSERT INTO jobhistory (jobid, userid, printerid, pagecounter, action, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
356        return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
357   
358    def updateJobSizeInHistory(self, historyid, jobsize) :
359        """Updates a job size in the history given the history line's id."""
360        self.doQuery("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(historyid)))
361   
362    def getPrinterPageCounter(self, printerid) :
363        """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
364        result = self.doQuery("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printerid))
365        try :
366            return self.doParseResult(result)[0]
367        except TypeError :      # Not found
368            return
369       
370    def addUserToGroup(self, userid, groupid) :   
371        """Adds an user to a group."""
372        result = self.doQuery("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(groupid), self.doQuote(userid)))
373        try :
374            mexists = self.doParseResult(result)[0]["mexists"]
375        except TypeError :   
376            mexists = 0
377        if not mexists :   
378            self.doQuery("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(userid)))
379       
380    def deleteUser(self, userid) :   
381        """Completely deletes an user from the Quota Storage."""
382        queries = []
383        queries.append("DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(userid))
384        queries.append("DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(userid))
385        queries.append("DELETE FROM userpquota WHERE userid=%s" % self.doQuote(userid))
386        queries.append("DELETE FROM users WHERE id=%s" % self.doQuote(userid))
387        # TODO : What should we do if we delete the last person who used a given printer ?
388        self.doQuery(queries)
389       
390    def deleteGroup(self, groupid) :   
391        """Completely deletes an user from the Quota Storage."""
392        queries = []
393        queries.append("DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(groupid))
394        queries.append("DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(groupid))
395        queries.append("DELETE FROM groups WHERE id=%s" % self.doQuote(groupid))
396        self.doQuery(queries)
397       
398    def computePrinterJobPrice(self, printerid, jobsize) :   
399        """Returns the price for a job on a given printer."""
400        # TODO : create a base class with things like this
401        prices = self.getPrinterPrices(printerid)
402        if prices is None :
403            perpage = perjob = 0.0
404        else :   
405            (perpage, perjob) = prices
406        return perjob + (perpage * jobsize)
407       
Note: See TracBrowser for help on using the browser.