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

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

LDAP storage backend's skeleton added. DOESN'T WORK.

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