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

Revision 1269, 28.0 kB (checked in by jalet, 20 years ago)

Fixed potential accuracy problem if a user printed on several printers at
the very same time.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.31  2004/01/10 09:44:02  jalet
25# Fixed potential accuracy problem if a user printed on several printers at
26# the very same time.
27#
28# Revision 1.30  2004/01/08 16:33:27  jalet
29# Additionnal check to not create a circular printers group.
30#
31# Revision 1.29  2004/01/08 16:24:49  jalet
32# edpykota now supports adding printers to printer groups.
33#
34# Revision 1.28  2004/01/08 14:10:33  jalet
35# Copyright year changed.
36#
37# Revision 1.27  2004/01/06 14:24:59  jalet
38# Printer groups should be cached now, if caching is enabled.
39#
40# Revision 1.26  2003/12/29 14:12:48  uid67467
41# Tries to workaround possible integrity violations when retrieving printer groups
42#
43# Revision 1.25  2003/12/27 16:49:25  uid67467
44# Should be ok now.
45#
46# Revision 1.24  2003/11/29 22:02:14  jalet
47# Don't try to retrieve the user print quota information if current printer
48# doesn't exist.
49#
50# Revision 1.23  2003/11/23 19:01:37  jalet
51# Job price added to history
52#
53# Revision 1.22  2003/11/21 14:28:46  jalet
54# More complete job history.
55#
56# Revision 1.21  2003/11/12 13:06:38  jalet
57# Bug fix wrt no user/group name command line argument to edpykota
58#
59# Revision 1.20  2003/10/09 21:25:26  jalet
60# Multiple printer names or wildcards can be passed on the command line
61# separated with commas.
62# Beta phase.
63#
64# Revision 1.19  2003/10/08 07:01:20  jalet
65# Job history can be disabled.
66# Some typos in README.
67# More messages in setup script.
68#
69# Revision 1.18  2003/10/07 09:07:30  jalet
70# Character encoding added to please latest version of Python
71#
72# Revision 1.17  2003/10/06 13:12:28  jalet
73# More work on caching
74#
75# Revision 1.16  2003/10/03 18:01:49  jalet
76# Nothing interesting...
77#
78# Revision 1.15  2003/10/03 12:27:03  jalet
79# Several optimizations, especially with LDAP backend
80#
81# Revision 1.14  2003/10/03 08:57:55  jalet
82# Caching mechanism now caches all that's cacheable.
83#
84# Revision 1.13  2003/10/02 20:23:18  jalet
85# Storage caching mechanism added.
86#
87# Revision 1.12  2003/08/17 14:20:25  jalet
88# Bug fix by Oleg Biteryakov
89#
90# Revision 1.11  2003/07/29 20:55:17  jalet
91# 1.14 is out !
92#
93# Revision 1.10  2003/07/16 21:53:08  jalet
94# Really big modifications wrt new configuration file's location and content.
95#
96# Revision 1.9  2003/07/14 17:20:15  jalet
97# Bug in postgresql storage when modifying the prices for a printer
98#
99# Revision 1.8  2003/07/14 14:18:17  jalet
100# Wrong documentation strings
101#
102# Revision 1.7  2003/07/09 20:17:07  jalet
103# Email field added to PostgreSQL schema
104#
105# Revision 1.6  2003/07/07 11:49:24  jalet
106# Lots of small fixes with the help of PyChecker
107#
108# Revision 1.5  2003/07/07 08:33:19  jalet
109# Bug fix due to a typo in LDAP code
110#
111# Revision 1.4  2003/06/30 13:54:21  jalet
112# Sorts by user / group name
113#
114# Revision 1.3  2003/06/25 14:10:01  jalet
115# Hey, it may work (edpykota --reset excepted) !
116#
117# Revision 1.2  2003/06/12 21:09:57  jalet
118# wrongly placed code.
119#
120# Revision 1.1  2003/06/10 16:37:54  jalet
121# Deletion of the second user which is not needed anymore.
122# Added a debug configuration field in /etc/pykota.conf
123# All queries can now be sent to the logger in debug mode, this will
124# greatly help improve performance when time for this will come.
125#
126#
127#
128#
129
130from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
131
132try :
133    import pg
134except ImportError :   
135    import sys
136    # TODO : to translate or not to translate ?
137    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
138
139class Storage(BaseStorage) :
140    def __init__(self, pykotatool, host, dbname, user, passwd) :
141        """Opens the PostgreSQL database connection."""
142        BaseStorage.__init__(self, pykotatool)
143        try :
144            (host, port) = host.split(":")
145            port = int(port)
146        except ValueError :   
147            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
148       
149        try :
150            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
151        except pg.error, msg :
152            raise PyKotaStorageError, msg
153        else :   
154            self.closed = 0
155            self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
156           
157    def close(self) :   
158        """Closes the database connection."""
159        if not self.closed :
160            self.database.close()
161            self.closed = 1
162            self.tool.logdebug("Database closed.")
163       
164    def beginTransaction(self) :   
165        """Starts a transaction."""
166        self.database.query("BEGIN;")
167        self.tool.logdebug("Transaction begins...")
168       
169    def commitTransaction(self) :   
170        """Commits a transaction."""
171        self.database.query("COMMIT;")
172        self.tool.logdebug("Transaction committed.")
173       
174    def rollbackTransaction(self) :     
175        """Rollbacks a transaction."""
176        self.database.query("ROLLBACK;")
177        self.tool.logdebug("Transaction aborted.")
178       
179    def doSearch(self, query) :
180        """Does a search query."""
181        query = query.strip()   
182        if not query.endswith(';') :   
183            query += ';'
184        try :
185            self.tool.logdebug("QUERY : %s" % query)
186            result = self.database.query(query)
187        except pg.error, msg :   
188            raise PyKotaStorageError, msg
189        else :   
190            if (result is not None) and (result.ntuples() > 0) : 
191                return result.dictresult()
192           
193    def doModify(self, query) :
194        """Does a (possibly multiple) modify query."""
195        query = query.strip()   
196        if not query.endswith(';') :   
197            query += ';'
198        try :
199            self.tool.logdebug("QUERY : %s" % query)
200            result = self.database.query(query)
201        except pg.error, msg :   
202            raise PyKotaStorageError, msg
203        else :   
204            return result
205           
206    def doQuote(self, field) :
207        """Quotes a field for use as a string in SQL queries."""
208        if type(field) == type(0.0) : 
209            typ = "decimal"
210        elif type(field) == type(0) :   
211            typ = "int"
212        else :   
213            typ = "text"
214        return pg._quote(field, typ)
215       
216    def getAllUsersNames(self) :   
217        """Extracts all user names."""
218        usernames = []
219        result = self.doSearch("SELECT username FROM users")
220        if result :
221            usernames = [record["username"] for record in result]
222        return usernames
223       
224    def getAllGroupsNames(self) :   
225        """Extracts all group names."""
226        groupnames = []
227        result = self.doSearch("SELECT groupname FROM groups")
228        if result :
229            groupnames = [record["groupname"] for record in result]
230        return groupnames
231       
232    def getUserFromBackend(self, username) :   
233        """Extracts user information given its name."""
234        user = StorageUser(self, username)
235        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
236        if result :
237            fields = result[0]
238            user.ident = fields.get("id")
239            user.LimitBy = fields.get("limitby")
240            user.AccountBalance = fields.get("balance")
241            user.LifeTimePaid = fields.get("lifetimepaid")
242            user.Email = fields.get("email")
243            user.Exists = 1
244        return user
245       
246    def getGroupFromBackend(self, groupname) :   
247        """Extracts group information given its name."""
248        group = StorageGroup(self, groupname)
249        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
250        if result :
251            fields = result[0]
252            group.ident = fields.get("id")
253            group.LimitBy = fields.get("limitby")
254            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))
255            if result :
256                fields = result[0]
257                group.AccountBalance = fields.get("balance")
258                group.LifeTimePaid = fields.get("lifetimepaid")
259            group.Exists = 1
260        return group
261       
262    def getPrinterFromBackend(self, printername) :       
263        """Extracts printer information given its name."""
264        printer = StoragePrinter(self, printername)
265        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
266        if result :
267            fields = result[0]
268            printer.ident = fields.get("id")
269            printer.PricePerJob = fields.get("priceperjob")
270            printer.PricePerPage = fields.get("priceperpage")
271            printer.LastJob = self.getPrinterLastJob(printer)
272            printer.Exists = 1
273        return printer   
274       
275    def getUserPQuotaFromBackend(self, user, printer) :       
276        """Extracts a user print quota."""
277        userpquota = StorageUserPQuota(self, user, printer)
278        if printer.Exists and user.Exists :
279            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)))
280            if result :
281                fields = result[0]
282                userpquota.ident = fields.get("id")
283                userpquota.PageCounter = fields.get("pagecounter")
284                userpquota.LifePageCounter = fields.get("lifepagecounter")
285                userpquota.SoftLimit = fields.get("softlimit")
286                userpquota.HardLimit = fields.get("hardlimit")
287                userpquota.DateLimit = fields.get("datelimit")
288                userpquota.Exists = 1
289        return userpquota
290       
291    def getGroupPQuotaFromBackend(self, group, printer) :       
292        """Extracts a group print quota."""
293        grouppquota = StorageGroupPQuota(self, group, printer)
294        if group.Exists :
295            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
296            if result :
297                fields = result[0]
298                grouppquota.ident = fields.get("id")
299                grouppquota.SoftLimit = fields.get("softlimit")
300                grouppquota.HardLimit = fields.get("hardlimit")
301                grouppquota.DateLimit = fields.get("datelimit")
302                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)))
303                if result :
304                    fields = result[0]
305                    grouppquota.PageCounter = fields.get("pagecounter")
306                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
307                grouppquota.Exists = 1
308        return grouppquota
309       
310    def getPrinterLastJobFromBackend(self, printer) :       
311        """Extracts a printer's last job information."""
312        lastjob = StorageLastJob(self, printer)
313        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
314        if result :
315            fields = result[0]
316            lastjob.ident = fields.get("id")
317            lastjob.JobId = fields.get("jobid")
318            lastjob.User = self.getUser(fields.get("username"))
319            lastjob.PrinterPageCounter = fields.get("pagecounter")
320            lastjob.JobSize = fields.get("jobsize")
321            lastjob.JobPrice = fields.get("jobprice")
322            lastjob.JobAction = fields.get("action")
323            lastjob.JobFileName = fields.get("filename")
324            lastjob.JobTitle = fields.get("title")
325            lastjob.JobCopies = fields.get("copies")
326            lastjob.JobOptions = fields.get("options")
327            lastjob.JobDate = fields.get("jobdate")
328            lastjob.Exists = 1
329        return lastjob
330           
331    def getGroupMembersFromBackend(self, group) :       
332        """Returns the group's members list."""
333        groupmembers = []
334        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
335        if result :
336            for record in result :
337                user = StorageUser(self, record.get("username"))
338                user.ident = record.get("userid")
339                user.LimitBy = record.get("limitby")
340                user.AccountBalance = record.get("balance")
341                user.LifeTimePaid = record.get("lifetimepaid")
342                user.Email = record.get("email")
343                user.Exists = 1
344                groupmembers.append(user)
345                self.cacheEntry("USERS", user.Name, user)
346        return groupmembers       
347       
348    def getUserGroupsFromBackend(self, user) :       
349        """Returns the user's groups list."""
350        groups = []
351        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
352        if result :
353            for record in result :
354                groups.append(self.getGroup(record.get("groupname")))
355        return groups       
356       
357    def getParentPrintersFromBackend(self, printer) :   
358        """Get all the printer groups this printer is a member of."""
359        pgroups = []
360        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
361        if result :
362            for record in result :
363                if record["groupid"] != printer.ident : # in case of integrity violation
364                    parentprinter = self.getPrinter(record.get("printername"))
365                    if parentprinter.Exists :
366                        pgroups.append(parentprinter)
367        return pgroups
368       
369    def getMatchingPrinters(self, printerpattern) :
370        """Returns the list of all printers for which name matches a certain pattern."""
371        printers = []
372        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
373        # but we don't because other storages semantics may be different, so every
374        # storage should use fnmatch to match patterns and be storage agnostic
375        result = self.doSearch("SELECT * FROM printers")
376        if result :
377            for record in result :
378                if self.tool.matchString(record["printername"], printerpattern.split(",")) :
379                    printer = StoragePrinter(self, record["printername"])
380                    printer.ident = record.get("id")
381                    printer.PricePerJob = record.get("priceperjob")
382                    printer.PricePerPage = record.get("priceperpage")
383                    printer.LastJob = self.getPrinterLastJob(printer)
384                    printer.Exists = 1
385                    printers.append(printer)
386                    self.cacheEntry("PRINTERS", printer.Name, printer)
387        return printers       
388       
389    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
390        """Returns the list of users who uses a given printer, along with their quotas."""
391        usersandquotas = []
392        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))
393        if result :
394            for record in result :
395                if self.tool.matchString(record.get("username"), names) :
396                    user = StorageUser(self, record.get("username"))
397                    user.ident = record.get("uid")
398                    user.LimitBy = record.get("limitby")
399                    user.AccountBalance = record.get("balance")
400                    user.LifeTimePaid = record.get("lifetimepaid")
401                    user.Email = record.get("email") 
402                    user.Exists = 1
403                    userpquota = StorageUserPQuota(self, user, printer)
404                    userpquota.ident = record.get("id")
405                    userpquota.PageCounter = record.get("pagecounter")
406                    userpquota.LifePageCounter = record.get("lifepagecounter")
407                    userpquota.SoftLimit = record.get("softlimit")
408                    userpquota.HardLimit = record.get("hardlimit")
409                    userpquota.DateLimit = record.get("datelimit")
410                    userpquota.Exists = 1
411                    usersandquotas.append((user, userpquota))
412                    self.cacheEntry("USERS", user.Name, user)
413                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
414        return usersandquotas
415               
416    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
417        """Returns the list of groups which uses a given printer, along with their quotas."""
418        groupsandquotas = []
419        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))
420        if result :
421            for record in result :
422                if self.tool.matchString(record.get("groupname"), names) :
423                    group = self.getGroup(record.get("groupname"))
424                    grouppquota = self.getGroupPQuota(group, printer)
425                    groupsandquotas.append((group, grouppquota))
426        return groupsandquotas
427       
428    def addPrinter(self, printername) :       
429        """Adds a printer to the quota storage, returns it."""
430        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
431        return self.getPrinter(printername)
432       
433    def addUser(self, user) :       
434        """Adds a user to the quota storage, returns its id."""
435        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid), self.doQuote(user.Email)))
436        return self.getUser(user.Name)
437       
438    def addGroup(self, group) :       
439        """Adds a group to the quota storage, returns its id."""
440        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
441        return self.getGroup(group.Name)
442
443    def addUserToGroup(self, user, group) :   
444        """Adds an user to a group."""
445        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
446        try :
447            mexists = int(result[0].get("mexists"))
448        except (IndexError, TypeError) :   
449            mexists = 0
450        if not mexists :   
451            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
452           
453    def addUserPQuota(self, user, printer) :
454        """Initializes a user print quota on a printer."""
455        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
456        return self.getUserPQuota(user, printer)
457       
458    def addGroupPQuota(self, group, printer) :
459        """Initializes a group print quota on a printer."""
460        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
461        return self.getGroupPQuota(group, printer)
462       
463    def writePrinterPrices(self, printer) :   
464        """Write the printer's prices back into the storage."""
465        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
466       
467    def writeUserLimitBy(self, user, limitby) :   
468        """Sets the user's limiting factor."""
469        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
470       
471    def writeGroupLimitBy(self, group, limitby) :   
472        """Sets the group's limiting factor."""
473        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
474       
475    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
476        """Sets the date limit permanently for a user print quota."""
477        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
478           
479    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
480        """Sets the date limit permanently for a group print quota."""
481        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
482       
483    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
484        """Increase page counters for a user print quota."""
485        self.doModify("UPDATE userpquota SET pagecounter=pagecounter+%s,lifepagecounter=lifepagecounter+%s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
486       
487    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
488        """Sets the new page counters permanently for a user print quota."""
489        self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
490       
491    def decreaseUserAccountBalance(self, user, amount) :   
492        """Decreases user's account balance from an amount."""
493        self.doModify("UPDATE users SET balance=balance-%s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
494       
495    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
496        """Sets the new account balance and eventually new lifetime paid."""
497        if newlifetimepaid is not None :
498            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
499        else :   
500            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
501           
502    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
503        """Sets the last job's size permanently."""
504        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
505       
506    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :   
507        """Adds a job in a printer's history."""
508        if (not self.disablehistory) or (not printer.LastJob.Exists) :
509            if jobsize is not None :
510                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options) VALUES (%s, %s, %s, %s, %s, %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), self.doQuote(jobprice), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options)))
511            else :   
512                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options) VALUES (%s, %s, %s, %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(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options)))
513        else :       
514            # here we explicitly want to reset jobsize to NULL if needed
515            self.doModify("UPDATE jobhistory SET userid=%s, jobid=%s, pagecounter=%s, action=%s, jobsize=%s, jobprice=%s, filename=%s, title=%s, copies=%s, options=%s, jobdate=now() WHERE id=%s" % (self.doQuote(user.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(printer.LastJob.ident)))
516           
517    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
518        """Sets soft and hard limits for a user quota."""
519        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
520       
521    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
522        """Sets soft and hard limits for a group quota on a specific printer."""
523        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
524
525    def writePrinterToGroup(self, pgroup, printer) :
526        """Puts a printer into a printer group."""
527        children = []
528        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
529        if result :
530            for record in result :
531                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
532        if printer.ident not in children :       
533            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
534       
535    def deleteUser(self, user) :   
536        """Completely deletes an user from the Quota Storage."""
537        # TODO : What should we do if we delete the last person who used a given printer ?
538        # TODO : we can't reassign the last job to the previous one, because next user would be
539        # TODO : incorrectly charged (overcharged).
540        for q in [ 
541                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
542                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
543                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
544                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
545                  ] :
546            self.doModify(q)
547       
548    def deleteGroup(self, group) :   
549        """Completely deletes a group from the Quota Storage."""
550        for q in [
551                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
552                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
553                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
554                 ] : 
555            self.doModify(q)
556       
Note: See TracBrowser for help on using the browser.