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

Revision 921, 15.6 kB (checked in by jalet, 21 years ago)

edpykota now accepts a --delete option.
Preparation to allow edpykota to accept much more command line options
(WARNING : docstring is OK, but code isn't !)

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