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

Revision 1085, 22.0 kB (checked in by jalet, 21 years ago)

Bug in postgresql storage when modifying the prices for a printer

  • 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.9  2003/07/14 17:20:15  jalet
24# Bug in postgresql storage when modifying the prices for a printer
25#
26# Revision 1.8  2003/07/14 14:18:17  jalet
27# Wrong documentation strings
28#
29# Revision 1.7  2003/07/09 20:17:07  jalet
30# Email field added to PostgreSQL schema
31#
32# Revision 1.6  2003/07/07 11:49:24  jalet
33# Lots of small fixes with the help of PyChecker
34#
35# Revision 1.5  2003/07/07 08:33:19  jalet
36# Bug fix due to a typo in LDAP code
37#
38# Revision 1.4  2003/06/30 13:54:21  jalet
39# Sorts by user / group name
40#
41# Revision 1.3  2003/06/25 14:10:01  jalet
42# Hey, it may work (edpykota --reset excepted) !
43#
44# Revision 1.2  2003/06/12 21:09:57  jalet
45# wrongly placed code.
46#
47# Revision 1.1  2003/06/10 16:37:54  jalet
48# Deletion of the second user which is not needed anymore.
49# Added a debug configuration field in /etc/pykota.conf
50# All queries can now be sent to the logger in debug mode, this will
51# greatly help improve performance when time for this will come.
52#
53#
54#
55#
56
57from pykota.storage import PyKotaStorageError
58from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
59
60try :
61    import pg
62except ImportError :   
63    import sys
64    # TODO : to translate or not to translate ?
65    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
66
67class Storage :
68    def __init__(self, pykotatool, host, dbname, user, passwd) :
69        """Opens the PostgreSQL database connection."""
70        self.tool = pykotatool
71        self.debug = pykotatool.config.getDebug()
72        self.closed = 1
73        try :
74            (host, port) = host.split(":")
75            port = int(port)
76        except ValueError :   
77            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
78       
79        try :
80            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
81        except pg.error, msg :
82            raise PyKotaStorageError, msg
83        else :   
84            self.closed = 0
85            if self.debug :
86                self.tool.logger.log_message("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user), "debug")
87           
88    def __del__(self) :       
89        """Closes the database connection."""
90        if not self.closed :
91            self.database.close()
92            self.closed = 1
93            if self.debug :
94                self.tool.logger.log_message("Database closed.", "debug")
95       
96    def beginTransaction(self) :   
97        """Starts a transaction."""
98        self.database.query("BEGIN;")
99        if self.debug :
100            self.tool.logger.log_message("Transaction begins...", "debug")
101       
102    def commitTransaction(self) :   
103        """Commits a transaction."""
104        self.database.query("COMMIT;")
105        if self.debug :
106            self.tool.logger.log_message("Transaction committed.", "debug")
107       
108    def rollbackTransaction(self) :     
109        """Rollbacks a transaction."""
110        self.database.query("ROLLBACK;")
111        if self.debug :
112            self.tool.logger.log_message("Transaction aborted.", "debug")
113       
114    def doSearch(self, query) :
115        """Does a search query."""
116        query = query.strip()   
117        if not query.endswith(';') :   
118            query += ';'
119        try :
120            if self.debug :
121                self.tool.logger.log_message("QUERY : %s" % query, "debug")
122            result = self.database.query(query)
123        except pg.error, msg :   
124            raise PyKotaStorageError, msg
125        else :   
126            if (result is not None) and (result.ntuples() > 0) : 
127                return result.dictresult()
128           
129    def doModify(self, query) :
130        """Does a (possibly multiple) modify query."""
131        query = query.strip()   
132        if not query.endswith(';') :   
133            query += ';'
134        try :
135            if self.debug :
136                self.tool.logger.log_message("QUERY : %s" % query, "debug")
137            result = self.database.query(query)
138        except pg.error, msg :   
139            raise PyKotaStorageError, msg
140        else :   
141            return result
142           
143    def doQuote(self, field) :
144        """Quotes a field for use as a string in SQL queries."""
145        if type(field) == type(0.0) : 
146            typ = "decimal"
147        elif type(field) == type(0) :   
148            typ = "int"
149        else :   
150            typ = "text"
151        return pg._quote(field, typ)
152       
153    def getUser(self, username) :   
154        """Extracts user information given its name."""
155        user = StorageUser(self, username)
156        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
157        if result :
158            fields = result[0]
159            user.ident = fields.get("id")
160            user.LimitBy = fields.get("limitby")
161            user.AccountBalance = fields.get("balance")
162            user.LifeTimePaid = fields.get("lifetimepaid")
163            user.Email = fields.get("email")
164            user.Exists = 1
165        return user
166       
167    def getGroup(self, groupname) :   
168        """Extracts group information given its name."""
169        group = StorageGroup(self, groupname)
170        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
171        if result :
172            fields = result[0]
173            group.ident = fields.get("id")
174            group.LimitBy = fields.get("limitby")
175            result = self.doSearch("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(group.ident))
176            if result :
177                fields = result[0]
178                group.AccountBalance = fields.get("balance")
179                group.LifeTimePaid = fields.get("lifetimepaid")
180            group.Exists = 1
181        return group
182       
183    def getPrinter(self, printername) :       
184        """Extracts printer information given its name."""
185        printer = StoragePrinter(self, printername)
186        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
187        if result :
188            fields = result[0]
189            printer.ident = fields.get("id")
190            printer.PricePerJob = fields.get("priceperjob")
191            printer.PricePerPage = fields.get("priceperpage")
192            printer.LastJob = self.getPrinterLastJob(printer)
193            printer.Exists = 1
194        return printer   
195           
196    def getUserGroups(self, user) :       
197        """Returns the user's groups list."""
198        groups = []
199        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
200        if result :
201            for record in result :
202                groups.append(self.getGroup(record.get("groupname")))
203        return groups       
204       
205    def getGroupMembers(self, group) :       
206        """Returns the group's members list."""
207        groupmembers = []
208        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
209        if result :
210            for record in result :
211                user = StorageUser(self, record.get("username"))
212                user.ident = record.get("userid")
213                user.LimitBy = record.get("limitby")
214                user.AccountBalance = record.get("balance")
215                user.LifeTimePaid = record.get("lifetimepaid")
216                user.Email = record.get("email")
217                user.Exists = 1
218                groupmembers.append(user)
219        return groupmembers       
220       
221    def getUserPQuota(self, user, printer) :       
222        """Extracts a user print quota."""
223        userpquota = StorageUserPQuota(self, user, printer)
224        if user.Exists :
225            result = self.doSearch("SELECT id, lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
226            if result :
227                fields = result[0]
228                userpquota.ident = fields.get("id")
229                userpquota.PageCounter = fields.get("pagecounter")
230                userpquota.LifePageCounter = fields.get("lifepagecounter")
231                userpquota.SoftLimit = fields.get("softlimit")
232                userpquota.HardLimit = fields.get("hardlimit")
233                userpquota.DateLimit = fields.get("datelimit")
234                userpquota.Exists = 1
235        return userpquota
236       
237    def getGroupPQuota(self, group, printer) :       
238        """Extracts a group print quota."""
239        grouppquota = StorageGroupPQuota(self, group, printer)
240        if group.Exists :
241            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
242            if result :
243                fields = result[0]
244                grouppquota.ident = fields.get("id")
245                grouppquota.SoftLimit = fields.get("softlimit")
246                grouppquota.HardLimit = fields.get("hardlimit")
247                grouppquota.DateLimit = fields.get("datelimit")
248                result = self.doSearch("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(printer.ident), self.doQuote(group.ident)))
249                if result :
250                    fields = result[0]
251                    grouppquota.PageCounter = fields.get("pagecounter")
252                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
253                grouppquota.Exists = 1
254        return grouppquota
255       
256    def getPrinterLastJob(self, printer) :       
257        """Extracts a printer's last job information."""
258        lastjob = StorageLastJob(self, printer)
259        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
260        if result :
261            fields = result[0]
262            lastjob.ident = fields.get("id")
263            lastjob.JobId = fields.get("jobid")
264            lastjob.User = self.getUser(fields.get("username"))
265            lastjob.PrinterPageCounter = fields.get("pagecounter")
266            lastjob.JobSize = fields.get("jobsize")
267            lastjob.JobAction = fields.get("action")
268            lastjob.JobDate = fields.get("jobdate")
269            lastjob.Exists = 1
270        return lastjob
271       
272    def getMatchingPrinters(self, printerpattern) :
273        """Returns the list of all printers for which name matches a certain pattern."""
274        printers = []
275        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
276        # but we don't because other storages semantics may be different, so every
277        # storage should use fnmatch to match patterns and be storage agnostic
278        result = self.doSearch("SELECT * FROM printers")
279        if result :
280            for record in result :
281                if self.tool.matchString(record["printername"], [ printerpattern ]) :
282                    printer = StoragePrinter(self, record["printername"])
283                    printer.ident = record.get("id")
284                    printer.PricePerJob = record.get("priceperjob")
285                    printer.PricePerPage = record.get("priceperpage")
286                    printer.LastJob = self.getPrinterLastJob(printer)
287                    printer.Exists = 1
288                    printers.append(printer)
289        return printers       
290       
291    def getPrinterUsersAndQuotas(self, printer, names=None) :       
292        """Returns the list of users who uses a given printer, along with their quotas."""
293        usersandquotas = []
294        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,email,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
295        if result :
296            for record in result :
297                user = StorageUser(self, record.get("username"))
298                if (names is None) or self.tool.matchString(user.Name, names) :
299                    user.ident = record.get("uid")
300                    user.LimitBy = record.get("limitby")
301                    user.AccountBalance = record.get("balance")
302                    user.LifeTimePaid = record.get("lifetimepaid")
303                    user.Email = record.get("email") 
304                    user.Exists = 1
305                    userpquota = StorageUserPQuota(self, user, printer)
306                    userpquota.ident = record.get("id")
307                    userpquota.PageCounter = record.get("pagecounter")
308                    userpquota.LifePageCounter = record.get("lifepagecounter")
309                    userpquota.SoftLimit = record.get("softlimit")
310                    userpquota.HardLimit = record.get("hardlimit")
311                    userpquota.DateLimit = record.get("datelimit")
312                    userpquota.Exists = 1
313                    usersandquotas.append((user, userpquota))
314        return usersandquotas
315               
316    def getPrinterGroupsAndQuotas(self, printer, names=None) :       
317        """Returns the list of groups which uses a given printer, along with their quotas."""
318        groupsandquotas = []
319        result = self.doSearch("SELECT groupname FROM groups JOIN grouppquota ON groups.id=grouppquota.groupid AND printerid=%s ORDER BY groupname ASC" % self.doQuote(printer.ident))
320        if result :
321            for record in result :
322                group = self.getGroup(record.get("groupname"))
323                if (names is None) or self.tool.matchString(group.Name, names) :
324                    grouppquota = self.getGroupPQuota(group, printer)
325                    groupsandquotas.append((group, grouppquota))
326        return groupsandquotas
327       
328    def addPrinter(self, printername) :       
329        """Adds a printer to the quota storage, returns it."""
330        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
331        return self.getPrinter(printername)
332       
333    def addUser(self, user) :       
334        """Adds a user to the quota storage, returns its id."""
335        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid) VALUES (%s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid)))
336        return self.getUser(user.Name)
337       
338    def addGroup(self, group) :       
339        """Adds a group to the quota storage, returns its id."""
340        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
341        return self.getGroup(group.Name)
342
343    def addUserToGroup(self, user, group) :   
344        """Adds an user to a group."""
345        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
346        try :
347            mexists = int(result[0].get("mexists"))
348        except (IndexError, TypeError) :   
349            mexists = 0
350        if not mexists :   
351            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
352           
353    def addUserPQuota(self, user, printer) :
354        """Initializes a user print quota on a printer."""
355        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
356        return self.getUserPQuota(user, printer)
357       
358    def addGroupPQuota(self, group, printer) :
359        """Initializes a group print quota on a printer."""
360        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
361        return self.getGroupPQuota(group, printer)
362       
363    def writePrinterPrices(self, printer) :   
364        """Write the printer's prices back into the storage."""
365        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
366       
367    def writeUserLimitBy(self, user, limitby) :   
368        """Sets the user's limiting factor."""
369        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
370       
371    def writeGroupLimitBy(self, group, limitby) :   
372        """Sets the group's limiting factor."""
373        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
374       
375    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
376        """Sets the date limit permanently for a user print quota."""
377        self.doModify("UPDATE userpquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
378           
379    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
380        """Sets the date limit permanently for a group print quota."""
381        self.doModify("UPDATE grouppquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
382       
383    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
384       """Sets the new page counters permanently for a user print quota."""
385       self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
386       
387    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
388       """Sets the new account balance and eventually new lifetime paid."""
389       if newlifetimepaid is not None :
390           self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
391       else :   
392           self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
393           
394    def writeLastJobSize(self, lastjob, jobsize) :       
395        """Sets the last job's size permanently."""
396        self.doModify("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(lastjob.ident)))
397       
398    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
399        """Adds a job in a printer's history."""
400        if jobsize is not None :
401            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
402        else :   
403            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action)))
404           
405    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
406        """Sets soft and hard limits for a user quota."""
407        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
408       
409    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
410        """Sets soft and hard limits for a group quota on a specific printer."""
411        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
412
413    def deleteUser(self, user) :   
414        """Completely deletes an user from the Quota Storage."""
415        # TODO : What should we do if we delete the last person who used a given printer ?
416        # TODO : we can't reassign the last job to the previous one, because next user would be
417        # TODO : incorrectly charged (overcharged).
418        for q in [ 
419                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
420                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
421                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
422                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
423                  ] :
424            self.doModify(q)
425       
426    def deleteGroup(self, group) :   
427        """Completely deletes a group from the Quota Storage."""
428        for q in [
429                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
430                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
431                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
432                 ] : 
433            self.doModify(q)
434       
Note: See TracBrowser for help on using the browser.