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

Revision 976, 21.6 kB (checked in by jalet, 21 years ago)

Stupid accounting method was added.

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