root / pykota / trunk / pykota / storages / pgstorage.py @ 1021

Revision 1021, 21.4 kB (checked in by jalet, 21 years ago)

Deletion of the second user which is not needed anymore.
Added a debug configuration field in /etc/pykota.conf
All queries can now be sent to the logger in debug mode, this will
greatly help improve performance when time for this will come.

  • 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.1  2003/06/10 16:37:54  jalet
24# Deletion of the second user which is not needed anymore.
25# Added a debug configuration field in /etc/pykota.conf
26# All queries can now be sent to the logger in debug mode, this will
27# greatly help improve performance when time for this will come.
28#
29#
30#
31#
32
33import fnmatch
34
35from pykota.storage import PyKotaStorageError
36
37try :
38    import pg
39except ImportError :   
40    import sys
41    # TODO : to translate or not to translate ?
42    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
43
44class Storage :
45    def __init__(self, pykotatool, host, dbname, user, passwd) :
46        """Opens the PostgreSQL database connection."""
47        self.tool = pykotatool
48        self.debug = pykotatool.config.getDebug()
49        self.closed = 1
50        try :
51            (host, port) = host.split(":")
52            port = int(port)
53        except ValueError :   
54            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
55       
56        try :
57            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
58            self.closed = 0
59        except pg.error, msg :
60            raise PyKotaStorageError, msg
61        else :   
62            if self.debug :
63                self.tool.logger.log_message("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user), "debug")
64           
65    def __del__(self) :       
66        """Closes the database connection."""
67        if not self.closed :
68            self.database.close()
69            self.closed = 1
70            if self.debug :
71                self.tool.logger.log_message("Database closed.", "debug")
72       
73    def doQuery(self, query) :
74        """Does a query."""
75        if type(query) in (type([]), type(())) :
76            query = ";".join(query)
77        query = query.strip()   
78        if not query.endswith(';') :   
79            query += ';'
80        self.database.query("BEGIN;")
81        if self.debug :
82            self.tool.logger.log_message("Transaction began.", "debug")
83        try :
84            if self.debug :
85                self.tool.logger.log_message("QUERY : %s" % query, "debug")
86            result = self.database.query(query)
87        except pg.error, msg :   
88            self.database.query("ROLLBACK;")
89            if self.debug :
90                self.tool.logger.log_message("Transaction aborted.", "debug")
91            raise PyKotaStorageError, msg
92        else :   
93            self.database.query("COMMIT;")
94            if self.debug :
95                self.tool.logger.log_message("Transaction committed.", "debug")
96            return result
97       
98    def doQuote(self, field) :
99        """Quotes a field for use as a string in SQL queries."""
100        if type(field) == type(0.0) : 
101            typ = "decimal"
102        elif type(field) == type(0) :   
103            typ = "int"
104        else :   
105            typ = "text"
106        return pg._quote(field, typ)
107       
108    def doParseResult(self, result) :
109        """Returns the result as a list of Python mappings."""
110        if (result is not None) and (result.ntuples() > 0) :
111            return result.dictresult()
112           
113    def getMatchingPrinters(self, printerpattern) :
114        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
115        printerslist = []
116        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
117        # but we don't because other storages semantics may be different, so every
118        # storage should use fnmatch to match patterns and be storage agnostic
119        result = self.doQuery("SELECT id, printername FROM printers")
120        result = self.doParseResult(result)
121        if result is not None :
122            for printer in result :
123                if fnmatch.fnmatchcase(printer["printername"], printerpattern) :
124                    printerslist.append((printer["id"], printer["printername"]))
125        return printerslist       
126           
127    def getPrinterId(self, printername) :       
128        """Returns a printerid given a printername."""
129        result = self.doQuery("SELECT id FROM printers WHERE printername=%s" % self.doQuote(printername))
130        try :
131            return self.doParseResult(result)[0]["id"]
132        except TypeError :      # Not found   
133            return
134           
135    def getPrinterPrices(self, printerid) :       
136        """Returns a printer prices per page and per job given a printerid."""
137        result = self.doQuery("SELECT priceperpage, priceperjob FROM printers WHERE id=%s" % self.doQuote(printerid))
138        try :
139            printerprices = self.doParseResult(result)[0]
140            return (printerprices["priceperpage"], printerprices["priceperjob"])
141        except TypeError :      # Not found   
142            return
143           
144    def setPrinterPrices(self, printerid, perpage, perjob) :
145        """Sets prices per job and per page for a given printer."""
146        self.doQuery("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(perpage), self.doQuote(perjob), self.doQuote(printerid)))
147   
148    def getUserId(self, username) :
149        """Returns a userid given a username."""
150        result = self.doQuery("SELECT id FROM users WHERE username=%s" % self.doQuote(username))
151        try :
152            return self.doParseResult(result)[0]["id"]
153        except TypeError :      # Not found
154            return
155           
156    def getGroupId(self, groupname) :
157        """Returns a groupid given a grupname."""
158        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
159        try :
160            return self.doParseResult(result)[0]["id"]
161        except TypeError :      # Not found
162            return
163           
164    def getJobHistoryId(self, jobid, userid, printerid) :       
165        """Returns the history line's id given a (jobid, userid, printerid)."""
166        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)))
167        try :
168            return self.doParseResult(result)[0]["id"]
169        except TypeError :      # Not found   
170            return
171           
172    def getPrinterUsers(self, printerid) :       
173        """Returns the list of userids and usernames which uses a given printer."""
174        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))
175        result = self.doParseResult(result)
176        if result is None :
177            return []
178        else :   
179            return [(record["id"], record["username"]) for record in result]
180       
181    def getPrinterGroups(self, printerid) :       
182        """Returns the list of groups which uses a given printer."""
183        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s)" % self.doQuote(printerid))
184        result = self.doParseResult(result)
185        if result is None :
186            return []
187        else :   
188            return [(record["id"], record["groupname"]) for record in result]
189       
190    def getGroupMembersNames(self, groupname) :       
191        """Returns the list of user's names which are member of this group."""
192        groupid = self.getGroupId(groupname)
193        if groupid is None :
194            return []
195        else :
196            result = self.doQuery("SELECT DISTINCT username FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
197            return [record["username"] for record in (self.doParseResult(result) or [])]
198       
199    def getUserGroupsNames(self, userid) :       
200        """Returns the list of groups' names the user is a member of."""
201        result = self.doQuery("SELECT DISTINCT groupname FROM groups WHERE id IN (SELECT groupid FROM groupsmembers WHERE userid=%s)" % self.doQuote(userid))
202        return [record["groupname"] for record in (self.doParseResult(result) or [])]
203       
204    def addPrinter(self, printername) :       
205        """Adds a printer to the quota storage, returns its id."""
206        self.doQuery("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
207        return self.getPrinterId(printername)
208       
209    def addUser(self, username) :       
210        """Adds a user to the quota storage, returns its id."""
211        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
212        return self.getUserId(username)
213       
214    def addGroup(self, groupname) :       
215        """Adds a group to the quota storage, returns its id."""
216        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
217        return self.getGroupId(groupname)
218       
219    def addUserPQuota(self, username, printerid) :
220        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
221        userid = self.getUserId(username)     
222        if userid is None :   
223            userid = self.addUser(username)
224        uqexists = (self.getUserPQuota(userid, printerid) is not None)   
225        if not uqexists : 
226            self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
227        return (userid, printerid)
228       
229    def addGroupPQuota(self, groupname, printerid) :
230        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
231        groupid = self.getGroupId(groupname)     
232        if groupid is None :   
233            groupid = self.addGroup(groupname)
234        gqexists = (self.getGroupPQuota(groupid, printerid) is not None)   
235        if not gqexists : 
236            self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(printerid)))
237        return (groupid, printerid)
238       
239    def increaseUserBalance(self, userid, amount) :   
240        """Increases (or decreases) an user's account balance by a given amount."""
241        self.doQuery("UPDATE users SET balance=balance+(%s), lifetimepaid=lifetimepaid+(%s) WHERE id=%s" % (self.doQuote(amount), self.doQuote(amount), self.doQuote(userid)))
242       
243    def getUserBalance(self, userid) :   
244        """Returns the current account balance for a given user."""
245        result = self.doQuery("SELECT balance, lifetimepaid FROM users WHERE id=%s" % self.doQuote(userid))
246        try :
247            result = self.doParseResult(result)[0]
248        except TypeError :      # Not found   
249            return
250        else :   
251            return (result["balance"], result["lifetimepaid"])
252       
253    def getGroupBalance(self, groupid) :   
254        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
255        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))
256        try :
257            result = self.doParseResult(result)[0]
258        except TypeError :      # Not found   
259            return
260        else :   
261            return (result["balance"], result["lifetimepaid"])
262       
263    def getUserLimitBy(self, userid) :   
264        """Returns the way in which user printing is limited."""
265        result = self.doQuery("SELECT limitby FROM users WHERE id=%s" % self.doQuote(userid))
266        try :
267            return self.doParseResult(result)[0]["limitby"]
268        except TypeError :      # Not found   
269            return
270       
271    def getGroupLimitBy(self, groupid) :   
272        """Returns the way in which group printing is limited."""
273        result = self.doQuery("SELECT limitby FROM groups WHERE id=%s" % self.doQuote(groupid))
274        try :
275            return self.doParseResult(result)[0]["limitby"]
276        except TypeError :      # Not found   
277            return
278       
279    def setUserBalance(self, userid, balance) :   
280        """Sets the account balance for a given user to a fixed value."""
281        (current, lifetimepaid) = self.getUserBalance(userid)
282        difference = balance - current
283        self.increaseUserBalance(userid, difference)
284       
285    def limitUserBy(self, userid, limitby) :   
286        """Limits a given user based either on print quota or on account balance."""
287        self.doQuery("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(userid)))
288       
289    def limitGroupBy(self, groupid, limitby) :   
290        """Limits a given group based either on print quota or on sum of its users' account balances."""
291        self.doQuery("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(groupid)))
292       
293    def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
294        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
295        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)))
296       
297    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
298        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
299        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)))
300       
301    def resetUserPQuota(self, userid, printerid) :   
302        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
303        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
304       
305    def resetGroupPQuota(self, groupid, printerid) :   
306        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
307        self.doQuery("UPDATE grouppquota SET pagecounter=0, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
308       
309    def updateUserPQuota(self, userid, printerid, pagecount) :
310        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
311        jobprice = self.computePrinterJobPrice(printerid, pagecount)
312        queries = []   
313        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)))
314        queries.append("UPDATE users SET balance=balance-(%s) WHERE id=%s" % (self.doQuote(jobprice), self.doQuote(userid)))
315        self.doQuery(queries)
316       
317    def getUserPQuota(self, userid, printerid) :
318        """Returns the Print Quota information for a given (userid, printerid)."""
319        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
320        try :
321            return self.doParseResult(result)[0]
322        except TypeError :      # Not found   
323            return
324       
325    def getGroupPQuota(self, groupid, printerid) :
326        """Returns the Print Quota information for a given (groupid, printerid)."""
327        result = self.doQuery("SELECT softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
328        try :
329            grouppquota = self.doParseResult(result)[0]
330        except TypeError :   
331            return
332        else :   
333            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)))
334            try :
335                result = self.doParseResult(result)[0]
336            except TypeError :      # Not found   
337                return
338            else :   
339                grouppquota.update({"lifepagecounter": result["lifepagecounter"], "pagecounter": result["pagecounter"]})
340                return grouppquota
341       
342    def setUserDateLimit(self, userid, printerid, datelimit) :
343        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
344        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)))
345       
346    def setGroupDateLimit(self, groupid, printerid, datelimit) :
347        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
348        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)))
349       
350    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
351        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
352        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)))
353        return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
354   
355    def updateJobSizeInHistory(self, historyid, jobsize) :
356        """Updates a job size in the history given the history line's id."""
357        self.doQuery("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(historyid)))
358   
359    def getPrinterPageCounter(self, printerid) :
360        """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
361        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))
362        try :
363            return self.doParseResult(result)[0]
364        except TypeError :      # Not found
365            return
366       
367    def addUserToGroup(self, userid, groupid) :   
368        """Adds an user to a group."""
369        result = self.doQuery("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(groupid), self.doQuote(userid)))
370        try :
371            mexists = self.doParseResult(result)[0]["mexists"]
372        except TypeError :   
373            mexists = 0
374        if not mexists :   
375            self.doQuery("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(userid)))
376       
377    def deleteUser(self, userid) :   
378        """Completely deletes an user from the Quota Storage."""
379        queries = []
380        queries.append("DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(userid))
381        queries.append("DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(userid))
382        queries.append("DELETE FROM userpquota WHERE userid=%s" % self.doQuote(userid))
383        queries.append("DELETE FROM users WHERE id=%s" % self.doQuote(userid))
384        # TODO : What should we do if we delete the last person who used a given printer ?
385        self.doQuery(queries)
386       
387    def deleteGroup(self, groupid) :   
388        """Completely deletes an user from the Quota Storage."""
389        queries = []
390        queries.append("DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(groupid))
391        queries.append("DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(groupid))
392        queries.append("DELETE FROM groups WHERE id=%s" % self.doQuote(groupid))
393        self.doQuery(queries)
394       
395    def computePrinterJobPrice(self, printerid, jobsize) :   
396        """Returns the price for a job on a given printer."""
397        # TODO : create a base class with things like this
398        prices = self.getPrinterPrices(printerid)
399        if prices is None :
400            perpage = perjob = 0.0
401        else :   
402            (perpage, perjob) = prices
403        return perjob + (perpage * jobsize)
404       
Note: See TracBrowser for help on using the browser.