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

Revision 927, 20.9 kB (checked in by jalet, 21 years ago)

Groups quota work now !

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