root / pykota / trunk / pykota / storages / sql.py @ 1016

Revision 1016, 21.7 kB (checked in by jalet, 21 years ago)

More good work on LDAP storage.

  • 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.32  2003/06/05 11:19:13  jalet
24# More good work on LDAP storage.
25#
26# Revision 1.31  2003/04/30 13:36:40  jalet
27# Stupid accounting method was added.
28#
29# Revision 1.30  2003/04/27 08:04:15  jalet
30# LDAP storage backend's skeleton added. DOESN'T WORK.
31#
32# Revision 1.29  2003/04/23 22:13:57  jalet
33# Preliminary support for LPRng added BUT STILL UNTESTED.
34#
35# Revision 1.28  2003/04/17 09:26:21  jalet
36# repykota now reports account balances too.
37#
38# Revision 1.27  2003/04/16 12:35:49  jalet
39# Groups quota work now !
40#
41# Revision 1.26  2003/04/16 08:53:14  jalet
42# Printing can now be limited either by user's account balance or by
43# page quota (the default). Quota report doesn't include account balance
44# yet, though.
45#
46# Revision 1.25  2003/04/15 21:58:33  jalet
47# edpykota now accepts a --delete option.
48# Preparation to allow edpykota to accept much more command line options
49# (WARNING : docstring is OK, but code isn't !)
50#
51# Revision 1.24  2003/04/15 13:55:28  jalet
52# Options --limitby and --balance added to edpykota
53#
54# Revision 1.23  2003/04/15 11:30:57  jalet
55# More work done on money print charging.
56# Minor bugs corrected.
57# All tools now access to the storage as priviledged users, repykota excepted.
58#
59# Revision 1.22  2003/04/10 21:47:20  jalet
60# Job history added. Upgrade script neutralized for now !
61#
62# Revision 1.21  2003/04/08 20:38:08  jalet
63# The last job Id is saved now for each printer, this will probably
64# allow other accounting methods in the future.
65#
66# Revision 1.20  2003/03/29 13:45:27  jalet
67# GPL paragraphs were incorrectly (from memory) copied into the sources.
68# Two README files were added.
69# Upgrade script for PostgreSQL pre 1.01 schema was added.
70#
71# Revision 1.19  2003/02/27 08:41:49  jalet
72# DATETIME is not supported anymore in PostgreSQL 7.3 it seems, but
73# TIMESTAMP is.
74#
75# Revision 1.18  2003/02/10 12:07:31  jalet
76# Now repykota should output the recorded total page number for each printer too.
77#
78# Revision 1.17  2003/02/10 08:41:36  jalet
79# edpykota's --reset command line option resets the limit date too.
80#
81# Revision 1.16  2003/02/08 22:39:46  jalet
82# --reset command line option added
83#
84# Revision 1.15  2003/02/08 22:12:09  jalet
85# Life time counter for users and groups added.
86#
87# Revision 1.14  2003/02/07 22:13:13  jalet
88# Perhaps edpykota is now able to add printers !!! Oh, stupid me !
89#
90# Revision 1.13  2003/02/07 00:08:52  jalet
91# Typos
92#
93# Revision 1.12  2003/02/06 23:20:03  jalet
94# warnpykota doesn't need any user/group name argument, mimicing the
95# warnquota disk quota tool.
96#
97# Revision 1.11  2003/02/06 15:05:13  jalet
98# self was forgotten
99#
100# Revision 1.10  2003/02/06 15:03:11  jalet
101# added a method to set the limit date
102#
103# Revision 1.9  2003/02/06 14:52:35  jalet
104# Forgotten import
105#
106# Revision 1.8  2003/02/06 14:49:04  jalet
107# edpykota should be ok now
108#
109# Revision 1.7  2003/02/06 14:28:59  jalet
110# edpykota should be ok, minus some typos
111#
112# Revision 1.6  2003/02/06 09:19:02  jalet
113# More robust behavior (hopefully) when the user or printer is not managed
114# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
115# printer and/or user not 'yet?' in storage.
116#
117# Revision 1.5  2003/02/05 23:26:22  jalet
118# Incorrect handling of grace delay
119#
120# Revision 1.4  2003/02/05 23:02:10  jalet
121# Typo
122#
123# Revision 1.3  2003/02/05 23:00:12  jalet
124# Forgotten import
125# Bad datetime conversion
126#
127# Revision 1.2  2003/02/05 22:28:38  jalet
128# More robust storage
129#
130# Revision 1.1  2003/02/05 21:28:17  jalet
131# Initial import into CVS
132#
133#
134#
135
136import fnmatch
137
138class SQLStorage :   
139    def getMatchingPrinters(self, printerpattern) :
140        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
141        printerslist = []
142        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
143        # but we don't because other storages semantics may be different, so every
144        # storage should use fnmatch to match patterns and be storage agnostic
145        result = self.doQuery("SELECT id, printername FROM printers")
146        result = self.doParseResult(result)
147        if result is not None :
148            for printer in result :
149                if fnmatch.fnmatchcase(printer["printername"], printerpattern) :
150                    printerslist.append((printer["id"], printer["printername"]))
151        return printerslist       
152           
153    def getPrinterId(self, printername) :       
154        """Returns a printerid given a printername."""
155        result = self.doQuery("SELECT id FROM printers WHERE printername=%s" % self.doQuote(printername))
156        try :
157            return self.doParseResult(result)[0]["id"]
158        except TypeError :      # Not found   
159            return
160           
161    def getPrinterPrices(self, printerid) :       
162        """Returns a printer prices per page and per job given a printerid."""
163        result = self.doQuery("SELECT priceperpage, priceperjob FROM printers WHERE id=%s" % self.doQuote(printerid))
164        try :
165            printerprices = self.doParseResult(result)[0]
166            return (printerprices["priceperpage"], printerprices["priceperjob"])
167        except TypeError :      # Not found   
168            return
169           
170    def setPrinterPrices(self, printerid, perpage, perjob) :
171        """Sets prices per job and per page for a given printer."""
172        self.doQuery("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(perpage), self.doQuote(perjob), self.doQuote(printerid)))
173   
174    def getUserId(self, username) :
175        """Returns a userid given a username."""
176        result = self.doQuery("SELECT id FROM users WHERE username=%s" % self.doQuote(username))
177        try :
178            return self.doParseResult(result)[0]["id"]
179        except TypeError :      # Not found
180            return
181           
182    def getGroupId(self, groupname) :
183        """Returns a groupid given a grupname."""
184        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
185        try :
186            return self.doParseResult(result)[0]["id"]
187        except TypeError :      # Not found
188            return
189           
190    def getJobHistoryId(self, jobid, userid, printerid) :       
191        """Returns the history line's id given a (jobid, userid, printerid)."""
192        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)))
193        try :
194            return self.doParseResult(result)[0]["id"]
195        except TypeError :      # Not found   
196            return
197           
198    def getPrinterUsers(self, printerid) :       
199        """Returns the list of userids and usernames which uses a given printer."""
200        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))
201        result = self.doParseResult(result)
202        if result is None :
203            return []
204        else :   
205            return [(record["id"], record["username"]) for record in result]
206       
207    def getPrinterGroups(self, printerid) :       
208        """Returns the list of groups which uses a given printer."""
209        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s)" % self.doQuote(printerid))
210        result = self.doParseResult(result)
211        if result is None :
212            return []
213        else :   
214            return [(record["id"], record["groupname"]) for record in result]
215       
216    def getGroupMembersNames(self, groupname) :       
217        """Returns the list of user's names which are member of this group."""
218        groupid = self.getGroupId(groupname)
219        if groupid is None :
220            return []
221        else :
222            result = self.doQuery("SELECT DISTINCT username FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
223            return [record["username"] for record in (self.doParseResult(result) or [])]
224       
225    def getUserGroupsNames(self, userid) :       
226        """Returns the list of groups' names the user is a member of."""
227        result = self.doQuery("SELECT DISTINCT groupname FROM groups WHERE id IN (SELECT groupid FROM groupsmembers WHERE userid=%s)" % self.doQuote(userid))
228        return [record["groupname"] for record in (self.doParseResult(result) or [])]
229       
230    def addPrinter(self, printername) :       
231        """Adds a printer to the quota storage, returns its id."""
232        self.doQuery("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
233        return self.getPrinterId(printername)
234       
235    def addUser(self, username) :       
236        """Adds a user to the quota storage, returns its id."""
237        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
238        return self.getUserId(username)
239       
240    def addGroup(self, groupname) :       
241        """Adds a group to the quota storage, returns its id."""
242        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
243        return self.getGroupId(groupname)
244       
245    def addUserPQuota(self, username, printerid) :
246        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
247        userid = self.getUserId(username)     
248        if userid is None :   
249            userid = self.addUser(username)
250        uqexists = (self.getUserPQuota(userid, printerid) is not None)   
251        if not uqexists : 
252            self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
253        return (userid, printerid)
254       
255    def addGroupPQuota(self, groupname, printerid) :
256        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
257        groupid = self.getGroupId(groupname)     
258        if groupid is None :   
259            groupid = self.addGroup(groupname)
260        gqexists = (self.getGroupPQuota(groupid, printerid) is not None)   
261        if not gqexists : 
262            self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(printerid)))
263        return (groupid, printerid)
264       
265    def increaseUserBalance(self, userid, amount) :   
266        """Increases (or decreases) an user's account balance by a given amount."""
267        self.doQuery("UPDATE users SET balance=balance+(%s), lifetimepaid=lifetimepaid+(%s) WHERE id=%s" % (self.doQuote(amount), self.doQuote(amount), self.doQuote(userid)))
268       
269    def getUserBalance(self, userid) :   
270        """Returns the current account balance for a given user."""
271        result = self.doQuery("SELECT balance, lifetimepaid FROM users WHERE id=%s" % self.doQuote(userid))
272        try :
273            result = self.doParseResult(result)[0]
274        except TypeError :      # Not found   
275            return
276        else :   
277            return (result["balance"], result["lifetimepaid"])
278       
279    def getGroupBalance(self, groupid) :   
280        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
281        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))
282        try :
283            result = self.doParseResult(result)[0]
284        except TypeError :      # Not found   
285            return
286        else :   
287            return (result["balance"], result["lifetimepaid"])
288       
289    def getUserLimitBy(self, userid) :   
290        """Returns the way in which user printing is limited."""
291        result = self.doQuery("SELECT limitby FROM users WHERE id=%s" % self.doQuote(userid))
292        try :
293            return self.doParseResult(result)[0]["limitby"]
294        except TypeError :      # Not found   
295            return
296       
297    def getGroupLimitBy(self, groupid) :   
298        """Returns the way in which group printing is limited."""
299        result = self.doQuery("SELECT limitby FROM groups WHERE id=%s" % self.doQuote(groupid))
300        try :
301            return self.doParseResult(result)[0]["limitby"]
302        except TypeError :      # Not found   
303            return
304       
305    def setUserBalance(self, userid, balance) :   
306        """Sets the account balance for a given user to a fixed value."""
307        (current, lifetimepaid) = self.getUserBalance(userid)
308        difference = balance - current
309        self.increaseUserBalance(userid, difference)
310       
311    def limitUserBy(self, userid, limitby) :   
312        """Limits a given user based either on print quota or on account balance."""
313        self.doQuery("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(userid)))
314       
315    def limitGroupBy(self, groupid, limitby) :   
316        """Limits a given group based either on print quota or on sum of its users' account balances."""
317        self.doQuery("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(groupid)))
318       
319    def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
320        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
321        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)))
322       
323    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
324        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
325        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)))
326       
327    def resetUserPQuota(self, userid, printerid) :   
328        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
329        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
330       
331    def resetGroupPQuota(self, groupid, printerid) :   
332        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
333        self.doQuery("UPDATE grouppquota SET pagecounter=0, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
334       
335    def updateUserPQuota(self, userid, printerid, pagecount) :
336        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
337        jobprice = self.computePrinterJobPrice(printerid, pagecount)
338        queries = []   
339        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)))
340        queries.append("UPDATE users SET balance=balance-(%s) WHERE id=%s" % (self.doQuote(jobprice), self.doQuote(userid)))
341        self.doQuery(queries)
342       
343    def getUserPQuota(self, userid, printerid) :
344        """Returns the Print Quota information for a given (userid, printerid)."""
345        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
346        try :
347            return self.doParseResult(result)[0]
348        except TypeError :      # Not found   
349            return
350       
351    def getGroupPQuota(self, groupid, printerid) :
352        """Returns the Print Quota information for a given (groupid, printerid)."""
353        result = self.doQuery("SELECT softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
354        try :
355            grouppquota = self.doParseResult(result)[0]
356        except TypeError :   
357            return
358        else :   
359            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)))
360            try :
361                result = self.doParseResult(result)[0]
362            except TypeError :      # Not found   
363                return
364            else :   
365                grouppquota.update({"lifepagecounter": result["lifepagecounter"], "pagecounter": result["pagecounter"]})
366                return grouppquota
367       
368    def setUserDateLimit(self, userid, printerid, datelimit) :
369        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
370        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)))
371       
372    def setGroupDateLimit(self, groupid, printerid, datelimit) :
373        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
374        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)))
375       
376    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
377        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
378        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)))
379        return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
380   
381    def updateJobSizeInHistory(self, historyid, jobsize) :
382        """Updates a job size in the history given the history line's id."""
383        self.doQuery("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(historyid)))
384   
385    def getPrinterPageCounter(self, printerid) :
386        """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
387        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))
388        try :
389            return self.doParseResult(result)[0]
390        except TypeError :      # Not found
391            return
392       
393    def addUserToGroup(self, userid, groupid) :   
394        """Adds an user to a group."""
395        result = self.doQuery("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(groupid), self.doQuote(userid)))
396        try :
397            mexists = self.doParseResult(result)[0]["mexists"]
398        except TypeError :   
399            mexists = 0
400        if not mexists :   
401            self.doQuery("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(userid)))
402       
403    def deleteUser(self, userid) :   
404        """Completely deletes an user from the Quota Storage."""
405        queries = []
406        queries.append("DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(userid))
407        queries.append("DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(userid))
408        queries.append("DELETE FROM userpquota WHERE userid=%s" % self.doQuote(userid))
409        queries.append("DELETE FROM users WHERE id=%s" % self.doQuote(userid))
410        # TODO : What should we do if we delete the last person who used a given printer ?
411        self.doQuery(queries)
412       
413    def deleteGroup(self, groupid) :   
414        """Completely deletes an user from the Quota Storage."""
415        queries = []
416        queries.append("DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(groupid))
417        queries.append("DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(groupid))
418        queries.append("DELETE FROM groups WHERE id=%s" % self.doQuote(groupid))
419        self.doQuery(queries)
420       
421    def computePrinterJobPrice(self, printerid, jobsize) :   
422        """Returns the price for a job on a given printer."""
423        # TODO : create a base class with things like this
424        prices = self.getPrinterPrices(printerid)
425        if prices is None :
426            perpage = perjob = 0.0
427        else :   
428            (perpage, perjob) = prices
429        return perjob + (perpage * jobsize)
Note: See TracBrowser for help on using the browser.