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

Revision 2830, 55.4 kB (checked in by jerome, 18 years ago)

Improved the code's quality a bit with pylint.

  • 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, 2005, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25from pykota.storage import StorageUser, StorageGroup, StoragePrinter, \
26                           StorageJob, StorageLastJob, StorageUserPQuota, \
27                           StorageGroupPQuota, StorageBillingCode
28
29class SQLStorage :
30    def createFilter(self, only) :   
31        """Returns the appropriate SQL filter."""
32        if only :
33            expressions = []
34            for (k, v) in only.items() :
35                expressions.append("%s=%s" % (k, self.doQuote(self.userCharsetToDatabase(v))))
36            return " AND ".join(expressions)     
37        return ""       
38       
39    def extractPrinters(self, extractonly={}) :
40        """Extracts all printer records."""
41        thefilter = self.createFilter(extractonly)
42        if thefilter :
43            thefilter = "WHERE %s" % thefilter
44        result = self.doRawSearch("SELECT * FROM printers %s ORDER BY id ASC" % thefilter)
45        return self.prepareRawResult(result)
46       
47    def extractUsers(self, extractonly={}) :
48        """Extracts all user records."""
49        thefilter = self.createFilter(extractonly)
50        if thefilter :
51            thefilter = "WHERE %s" % thefilter
52        result = self.doRawSearch("SELECT * FROM users %s ORDER BY id ASC" % thefilter)
53        return self.prepareRawResult(result)
54       
55    def extractBillingcodes(self, extractonly={}) :
56        """Extracts all billing codes records."""
57        thefilter = self.createFilter(extractonly)
58        if thefilter :
59            thefilter = "WHERE %s" % thefilter
60        result = self.doRawSearch("SELECT * FROM billingcodes %s ORDER BY id ASC" % thefilter)
61        return self.prepareRawResult(result)
62       
63    def extractGroups(self, extractonly={}) :
64        """Extracts all group records."""
65        thefilter = self.createFilter(extractonly)
66        if thefilter :
67            thefilter = "WHERE %s" % thefilter
68        result = self.doRawSearch("SELECT groups.*,COALESCE(SUM(balance), 0) AS balance, COALESCE(SUM(lifetimepaid), 0) as lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) %s GROUP BY groups.id,groups.groupname,groups.limitby,groups.description ORDER BY groups.id ASC" % thefilter)
69        return self.prepareRawResult(result)
70       
71    def extractPayments(self, extractonly={}) :
72        """Extracts all payment records."""
73        thefilter = self.createFilter(extractonly)
74        if thefilter :
75            thefilter = "AND %s" % thefilter
76        result = self.doRawSearch("SELECT username,payments.* FROM users,payments WHERE users.id=payments.userid %s ORDER BY payments.id ASC" % thefilter)
77        return self.prepareRawResult(result)
78       
79    def extractUpquotas(self, extractonly={}) :
80        """Extracts all userpquota records."""
81        thefilter = self.createFilter(extractonly)
82        if thefilter :
83            thefilter = "AND %s" % thefilter
84        result = self.doRawSearch("SELECT users.username,printers.printername,userpquota.* FROM users,printers,userpquota WHERE users.id=userpquota.userid AND printers.id=userpquota.printerid %s ORDER BY userpquota.id ASC" % thefilter)
85        return self.prepareRawResult(result)
86       
87    def extractGpquotas(self, extractonly={}) :
88        """Extracts all grouppquota records."""
89        thefilter = self.createFilter(extractonly)
90        if thefilter :
91            thefilter = "AND %s" % thefilter
92        result = self.doRawSearch("SELECT groups.groupname,printers.printername,grouppquota.*,coalesce(sum(pagecounter), 0) AS pagecounter,coalesce(sum(lifepagecounter), 0) AS lifepagecounter FROM groups,printers,grouppquota,userpquota WHERE groups.id=grouppquota.groupid AND printers.id=grouppquota.printerid AND userpquota.printerid=grouppquota.printerid AND userpquota.userid IN (SELECT userid FROM groupsmembers WHERE groupsmembers.groupid=grouppquota.groupid) %s GROUP BY grouppquota.id,grouppquota.groupid,grouppquota.printerid,grouppquota.softlimit,grouppquota.hardlimit,grouppquota.datelimit,grouppquota.maxjobsize,groups.groupname,printers.printername ORDER BY grouppquota.id" % thefilter)
93        return self.prepareRawResult(result)
94       
95    def extractUmembers(self, extractonly={}) :
96        """Extracts all user groups members."""
97        thefilter = self.createFilter(extractonly)
98        if thefilter :
99            thefilter = "AND %s" % thefilter
100        result = self.doRawSearch("SELECT groups.groupname, users.username, groupsmembers.* FROM groups,users,groupsmembers WHERE users.id=groupsmembers.userid AND groups.id=groupsmembers.groupid %s ORDER BY groupsmembers.groupid, groupsmembers.userid ASC" % thefilter)
101        return self.prepareRawResult(result)
102       
103    def extractPmembers(self, extractonly={}) :
104        """Extracts all printer groups members."""
105        for (k, v) in extractonly.items() :
106            if k == "pgroupname" :
107                del extractonly[k]
108                extractonly["p1.printername"] = v
109            elif k == "printername" :
110                del extractonly[k]
111                extractonly["p2.printername"] = v
112        thefilter = self.createFilter(extractonly)
113        if thefilter :
114            thefilter = "AND %s" % thefilter
115        result = self.doRawSearch("SELECT p1.printername as pgroupname, p2.printername as printername, printergroupsmembers.* FROM printers p1, printers p2, printergroupsmembers WHERE p1.id=printergroupsmembers.groupid AND p2.id=printergroupsmembers.printerid %s ORDER BY printergroupsmembers.groupid, printergroupsmembers.printerid ASC" % thefilter)
116        return self.prepareRawResult(result)
117       
118    def extractHistory(self, extractonly={}) :
119        """Extracts all jobhistory records."""
120        startdate = extractonly.get("start")
121        enddate = extractonly.get("end")
122        for limit in ("start", "end") :
123            try :
124                del extractonly[limit]
125            except KeyError :   
126                pass
127        thefilter = self.createFilter(extractonly)
128        if thefilter :
129            thefilter = "AND %s" % thefilter
130        (startdate, enddate) = self.cleanDates(startdate, enddate)
131        if startdate : 
132            thefilter = "%s AND jobdate>=%s" % (thefilter, self.doQuote(startdate))
133        if enddate : 
134            thefilter = "%s AND jobdate<=%s" % (thefilter, self.doQuote(enddate))
135        result = self.doRawSearch("SELECT users.username,printers.printername,jobhistory.* FROM users,printers,jobhistory WHERE users.id=jobhistory.userid AND printers.id=jobhistory.printerid %s ORDER BY jobhistory.id ASC" % thefilter)
136        return self.prepareRawResult(result)
137           
138    def filterNames(self, records, attribute, patterns=None) :
139        """Returns a list of 'attribute' from a list of records.
140       
141           Logs any missing attribute.
142        """   
143        result = []
144        for record in records :
145            attrval = record.get(attribute, [None])
146            if attrval is None :
147                self.tool.printInfo("Object %s has no %s attribute !" % (repr(record), attribute), "error")
148            else :
149                attrval = self.databaseToUserCharset(attrval)
150                if patterns :
151                    if (not isinstance(patterns, type([]))) and (not isinstance(patterns, type(()))) :
152                        patterns = [ patterns ]
153                    if self.tool.matchString(attrval, patterns) :
154                        result.append(attrval)
155                else :   
156                    result.append(attrval)
157        return result   
158               
159    def getAllBillingCodes(self, billingcode=None) :   
160        """Extracts all billing codes or only the billing codes matching the optional parameter."""
161        result = self.doSearch("SELECT billingcode FROM billingcodes")
162        if result :
163            return self.filterNames(result, "billingcode", billingcode)
164        else :   
165            return []
166       
167    def getAllPrintersNames(self, printername=None) :   
168        """Extracts all printer names or only the printers' names matching the optional parameter."""
169        result = self.doSearch("SELECT printername FROM printers")
170        if result :
171            return self.filterNames(result, "printername", printername)
172        else :   
173            return []
174   
175    def getAllUsersNames(self, username=None) :   
176        """Extracts all user names."""
177        result = self.doSearch("SELECT username FROM users")
178        if result :
179            return self.filterNames(result, "username", username)
180        else :   
181            return []
182       
183    def getAllGroupsNames(self, groupname=None) :   
184        """Extracts all group names."""
185        result = self.doSearch("SELECT groupname FROM groups")
186        if result :
187            return self.filterNames(result, "groupname", groupname)
188        else :
189            return []
190       
191    def getUserNbJobsFromHistory(self, user) :
192        """Returns the number of jobs the user has in history."""
193        result = self.doSearch("SELECT COUNT(*) FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident))
194        if result :
195            return result[0]["count"]
196        return 0
197       
198    def getUserFromBackend(self, username) :   
199        """Extracts user information given its name."""
200        user = StorageUser(self, username)
201        username = self.userCharsetToDatabase(username)
202        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
203        if result :
204            fields = result[0]
205            user.ident = fields.get("id")
206            user.LimitBy = fields.get("limitby") or "quota"
207            user.AccountBalance = fields.get("balance")
208            user.LifeTimePaid = fields.get("lifetimepaid")
209            user.Email = fields.get("email")
210            user.Description = self.databaseToUserCharset(fields.get("description"))
211            user.OverCharge = fields.get("overcharge", 1.0)
212            user.Exists = 1
213        return user
214       
215    def getGroupFromBackend(self, groupname) :   
216        """Extracts group information given its name."""
217        group = StorageGroup(self, groupname)
218        groupname = self.userCharsetToDatabase(groupname)
219        result = self.doSearch("SELECT groups.*,COALESCE(SUM(balance), 0.0) AS balance, COALESCE(SUM(lifetimepaid), 0.0) AS lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) WHERE groupname=%s GROUP BY groups.id,groups.groupname,groups.limitby,groups.description LIMIT 1" % self.doQuote(groupname))
220        if result :
221            fields = result[0]
222            group.ident = fields.get("id")
223            group.LimitBy = fields.get("limitby") or "quota"
224            group.AccountBalance = fields.get("balance")
225            group.LifeTimePaid = fields.get("lifetimepaid")
226            group.Description = self.databaseToUserCharset(fields.get("description"))
227            group.Exists = 1
228        return group
229       
230    def getPrinterFromBackend(self, printername) :       
231        """Extracts printer information given its name."""
232        printer = StoragePrinter(self, printername)
233        printername = self.userCharsetToDatabase(printername)
234        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
235        if result :
236            fields = result[0]
237            printer.ident = fields.get("id")
238            printer.PricePerJob = fields.get("priceperjob") or 0.0
239            printer.PricePerPage = fields.get("priceperpage") or 0.0
240            printer.MaxJobSize = fields.get("maxjobsize") or 0
241            printer.PassThrough = fields.get("passthrough") or 0
242            if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
243                printer.PassThrough = 1
244            else :
245                printer.PassThrough = 0
246            printer.Description = self.databaseToUserCharset(fields.get("description") or "")
247            printer.Exists = 1
248        return printer   
249       
250    def getBillingCodeFromBackend(self, label) :       
251        """Extracts a billing code information given its name."""
252        code = StorageBillingCode(self, label)
253        result = self.doSearch("SELECT * FROM billingcodes WHERE billingcode=%s LIMIT 1" % self.doQuote(self.userCharsetToDatabase(label)))
254        if result :
255            fields = result[0]
256            code.ident = fields.get("id")
257            code.Description = self.databaseToUserCharset(fields.get("description") or "")
258            code.Balance = fields.get("balance") or 0.0
259            code.PageCounter = fields.get("pagecounter") or 0
260            code.Exists = 1
261        return code   
262       
263    def getUserPQuotaFromBackend(self, user, printer) :       
264        """Extracts a user print quota."""
265        userpquota = StorageUserPQuota(self, user, printer)
266        if printer.Exists and user.Exists :
267            result = self.doSearch("SELECT * FROM userpquota WHERE userid=%s AND printerid=%s;" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
268            if result :
269                fields = result[0]
270                userpquota.ident = fields.get("id")
271                userpquota.PageCounter = fields.get("pagecounter")
272                userpquota.LifePageCounter = fields.get("lifepagecounter")
273                userpquota.SoftLimit = fields.get("softlimit")
274                userpquota.HardLimit = fields.get("hardlimit")
275                userpquota.DateLimit = fields.get("datelimit")
276                userpquota.WarnCount = fields.get("warncount")
277                userpquota.Exists = 1
278        return userpquota
279       
280    def getGroupPQuotaFromBackend(self, group, printer) :       
281        """Extracts a group print quota."""
282        grouppquota = StorageGroupPQuota(self, group, printer)
283        if group.Exists :
284            result = self.doSearch("SELECT * FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
285            if result :
286                fields = result[0]
287                grouppquota.ident = fields.get("id")
288                grouppquota.SoftLimit = fields.get("softlimit")
289                grouppquota.HardLimit = fields.get("hardlimit")
290                grouppquota.DateLimit = fields.get("datelimit")
291                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)))
292                if result :
293                    fields = result[0]
294                    grouppquota.PageCounter = fields.get("pagecounter") or 0
295                    grouppquota.LifePageCounter = fields.get("lifepagecounter") or 0
296                grouppquota.Exists = 1
297        return grouppquota
298       
299    def getPrinterLastJobFromBackend(self, printer) :       
300        """Extracts a printer's last job information."""
301        lastjob = StorageLastJob(self, printer)
302        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, hostname, jobdate, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
303        if result :
304            fields = result[0]
305            lastjob.ident = fields.get("id")
306            lastjob.JobId = fields.get("jobid")
307            lastjob.UserName = self.databaseToUserCharset(fields.get("username"))
308            lastjob.PrinterPageCounter = fields.get("pagecounter")
309            lastjob.JobSize = fields.get("jobsize")
310            lastjob.JobPrice = fields.get("jobprice")
311            lastjob.JobAction = fields.get("action")
312            lastjob.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
313            lastjob.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
314            lastjob.JobCopies = fields.get("copies")
315            lastjob.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
316            lastjob.JobDate = fields.get("jobdate")
317            lastjob.JobHostName = fields.get("hostname")
318            lastjob.JobSizeBytes = fields.get("jobsizebytes")
319            lastjob.JobMD5Sum = fields.get("md5sum")
320            lastjob.JobPages = fields.get("pages")
321            lastjob.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode"))
322            lastjob.PrecomputedJobSize = fields.get("precomputedjobsize")
323            lastjob.PrecomputedJobPrice = fields.get("precomputedjobprice")
324            if lastjob.JobTitle == lastjob.JobFileName == lastjob.JobOptions == "hidden" :
325                (lastjob.JobTitle, lastjob.JobFileName, lastjob.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
326            lastjob.Exists = 1
327        return lastjob
328           
329    def getGroupMembersFromBackend(self, group) :       
330        """Returns the group's members list."""
331        groupmembers = []
332        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
333        if result :
334            for record in result :
335                user = StorageUser(self, self.databaseToUserCharset(record.get("username")))
336                user.ident = record.get("userid")
337                user.LimitBy = record.get("limitby") or "quota"
338                user.AccountBalance = record.get("balance")
339                user.LifeTimePaid = record.get("lifetimepaid")
340                user.Email = record.get("email")
341                user.OverCharge = record.get("overcharge")
342                user.Exists = 1
343                groupmembers.append(user)
344                self.cacheEntry("USERS", user.Name, user)
345        return groupmembers       
346       
347    def getUserGroupsFromBackend(self, user) :       
348        """Returns the user's groups list."""
349        groups = []
350        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
351        if result :
352            for record in result :
353                groups.append(self.getGroup(self.databaseToUserCharset(record.get("groupname"))))
354        return groups       
355       
356    def getParentPrintersFromBackend(self, printer) :   
357        """Get all the printer groups this printer is a member of."""
358        pgroups = []
359        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
360        if result :
361            for record in result :
362                if record["groupid"] != printer.ident : # in case of integrity violation
363                    parentprinter = self.getPrinter(self.databaseToUserCharset(record.get("printername")))
364                    if parentprinter.Exists :
365                        pgroups.append(parentprinter)
366        return pgroups
367       
368    def getMatchingPrinters(self, printerpattern) :
369        """Returns the list of all printers for which name matches a certain pattern."""
370        printers = []
371        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
372        # but we don't because other storages semantics may be different, so every
373        # storage should use fnmatch to match patterns and be storage agnostic
374        result = self.doSearch("SELECT * FROM printers")
375        if result :
376            patterns = printerpattern.split(",")
377            try :
378                patdict = {}.fromkeys(patterns)
379            except AttributeError :   
380                # Python v2.2 or earlier
381                patdict = {}
382                for p in patterns :
383                    patdict[p] = None
384            for record in result :
385                pname = self.databaseToUserCharset(record["printername"])
386                if patdict.has_key(pname) or self.tool.matchString(pname, patterns) :
387                    printer = StoragePrinter(self, pname)
388                    printer.ident = record.get("id")
389                    printer.PricePerJob = record.get("priceperjob") or 0.0
390                    printer.PricePerPage = record.get("priceperpage") or 0.0
391                    printer.Description = self.databaseToUserCharset(record.get("description") or "") 
392                    printer.MaxJobSize = record.get("maxjobsize") or 0
393                    printer.PassThrough = record.get("passthrough") or 0
394                    if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
395                        printer.PassThrough = 1
396                    else :
397                        printer.PassThrough = 0
398                    printer.Exists = 1
399                    printers.append(printer)
400                    self.cacheEntry("PRINTERS", printer.Name, printer)
401        return printers       
402       
403    def getMatchingUsers(self, userpattern) :
404        """Returns the list of all users for which name matches a certain pattern."""
405        users = []
406        # We 'could' do a SELECT username FROM users WHERE username LIKE ...
407        # but we don't because other storages semantics may be different, so every
408        # storage should use fnmatch to match patterns and be storage agnostic
409        result = self.doSearch("SELECT * FROM users")
410        if result :
411            patterns = userpattern.split(",")
412            try :
413                patdict = {}.fromkeys(patterns)
414            except AttributeError :   
415                # Python v2.2 or earlier
416                patdict = {}
417                for p in patterns :
418                    patdict[p] = None
419            for record in result :
420                uname = self.databaseToUserCharset(record["username"])
421                if patdict.has_key(uname) or self.tool.matchString(uname, patterns) :
422                    user = StorageUser(self, uname)
423                    user.ident = record.get("id")
424                    user.LimitBy = record.get("limitby") or "quota"
425                    user.AccountBalance = record.get("balance")
426                    user.LifeTimePaid = record.get("lifetimepaid")
427                    user.Email = record.get("email")
428                    user.Description = self.databaseToUserCharset(record.get("description"))
429                    user.OverCharge = record.get("overcharge", 1.0)
430                    user.Exists = 1
431                    users.append(user)
432                    self.cacheEntry("USERS", user.Name, user)
433        return users       
434       
435    def getMatchingGroups(self, grouppattern) :
436        """Returns the list of all groups for which name matches a certain pattern."""
437        groups = []
438        # We 'could' do a SELECT groupname FROM groups WHERE groupname LIKE ...
439        # but we don't because other storages semantics may be different, so every
440        # storage should use fnmatch to match patterns and be storage agnostic
441        result = self.doSearch("SELECT groups.*,COALESCE(SUM(balance), 0.0) AS balance, COALESCE(SUM(lifetimepaid), 0.0) AS lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) GROUP BY groups.id,groups.groupname,groups.limitby,groups.description")
442        if result :
443            patterns = grouppattern.split(",")
444            try :
445                patdict = {}.fromkeys(patterns)
446            except AttributeError :   
447                # Python v2.2 or earlier
448                patdict = {}
449                for p in patterns :
450                    patdict[p] = None
451            for record in result :
452                gname = self.databaseToUserCharset(record["groupname"])
453                if patdict.has_key(gname) or self.tool.matchString(gname, patterns) :
454                    group = StorageGroup(self, gname)
455                    group.ident = record.get("id")
456                    group.LimitBy = record.get("limitby") or "quota"
457                    group.AccountBalance = record.get("balance")
458                    group.LifeTimePaid = record.get("lifetimepaid")
459                    group.Description = self.databaseToUserCharset(record.get("description"))
460                    group.Exists = 1
461                    groups.append(group)
462                    self.cacheEntry("GROUPS", group.Name, group)
463        return groups       
464       
465    def getMatchingBillingCodes(self, billingcodepattern) :
466        """Returns the list of all billing codes for which the label matches a certain pattern."""
467        codes = []
468        result = self.doSearch("SELECT * FROM billingcodes")
469        if result :
470            patterns = billingcodepattern.split(",")
471            try :
472                patdict = {}.fromkeys(patterns)
473            except AttributeError :   
474                # Python v2.2 or earlier
475                patdict = {}
476                for p in patterns :
477                    patdict[p] = None
478            for record in result :
479                codename = self.databaseToUserCharset(record["billingcode"])
480                if patdict.has_key(codename) or self.tool.matchString(codename, patterns) :
481                    code = StorageBillingCode(self, codename)
482                    code.ident = record.get("id")
483                    code.Balance = record.get("balance") or 0.0
484                    code.PageCounter = record.get("pagecounter") or 0
485                    code.Description = self.databaseToUserCharset(record.get("description") or "") 
486                    code.Exists = 1
487                    codes.append(code)
488                    self.cacheEntry("BILLINGCODES", code.BillingCode, code)
489        return codes       
490       
491    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
492        """Returns the list of users who uses a given printer, along with their quotas."""
493        usersandquotas = []
494        result = self.doSearch("SELECT users.id as uid,username,description,balance,lifetimepaid,limitby,email,overcharge,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit,warncount FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
495        if result :
496            for record in result :
497                uname = self.databaseToUserCharset(record.get("username"))
498                if self.tool.matchString(uname, names) :
499                    user = StorageUser(self, uname)
500                    user.ident = record.get("uid")
501                    user.LimitBy = record.get("limitby") or "quota"
502                    user.AccountBalance = record.get("balance")
503                    user.LifeTimePaid = record.get("lifetimepaid")
504                    user.Email = record.get("email") 
505                    user.OverCharge = record.get("overcharge")
506                    user.Description = self.databaseToUserCharset(record.get("description"))
507                    user.Exists = 1
508                    userpquota = StorageUserPQuota(self, user, printer)
509                    userpquota.ident = record.get("id")
510                    userpquota.PageCounter = record.get("pagecounter")
511                    userpquota.LifePageCounter = record.get("lifepagecounter")
512                    userpquota.SoftLimit = record.get("softlimit")
513                    userpquota.HardLimit = record.get("hardlimit")
514                    userpquota.DateLimit = record.get("datelimit")
515                    userpquota.WarnCount = record.get("warncount")
516                    userpquota.Exists = 1
517                    usersandquotas.append((user, userpquota))
518                    self.cacheEntry("USERS", user.Name, user)
519                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
520        return usersandquotas
521               
522    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
523        """Returns the list of groups which uses a given printer, along with their quotas."""
524        groupsandquotas = []
525        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))
526        if result :
527            for record in result :
528                gname = self.databaseToUserCharset(record.get("groupname"))
529                if self.tool.matchString(gname, names) :
530                    group = self.getGroup(gname)
531                    grouppquota = self.getGroupPQuota(group, printer)
532                    groupsandquotas.append((group, grouppquota))
533        return groupsandquotas
534       
535    def addPrinter(self, printer) :       
536        """Adds a printer to the quota storage, returns the old value if it already exists."""
537        oldentry = self.getPrinter(printer.Name)
538        if oldentry.Exists :
539            return oldentry
540        self.doModify("INSERT INTO printers (printername, passthrough, maxjobsize, description, priceperpage, priceperjob) VALUES (%s, %s, %s, %s, %s, %s)" \
541                          % (self.doQuote(self.userCharsetToDatabase(printer.Name)), \
542                             self.doQuote((printer.PassThrough and "t") or "f"), \
543                             self.doQuote(printer.MaxJobSize or 0), \
544                             self.doQuote(self.userCharsetToDatabase(printer.Description)), \
545                             self.doQuote(printer.PricePerPage or 0.0), \
546                             self.doQuote(printer.PricePerJob or 0.0)))
547        printer.isDirty = False
548        return None # the entry created doesn't need further modification
549       
550    def addBillingCode(self, bcode) :
551        """Adds a billing code to the quota storage, returns the old value if it already exists."""
552        oldentry = self.getBillingCode(bcode.BillingCode)
553        if oldentry.Exists :
554            return oldentry
555        self.doModify("INSERT INTO billingcodes (billingcode, balance, pagecounter, description) VALUES (%s, %s, %s, %s)" \
556                           % (self.doQuote(self.userCharsetToDatabase(bcode.BillingCode)), 
557                              self.doQuote(bcode.Balance or 0.0), \
558                              self.doQuote(bcode.PageCounter or 0), \
559                              self.doQuote(self.userCharsetToDatabase(bcode.Description))))
560        bcode.isDirty = False
561        return None # the entry created doesn't need further modification
562       
563    def addUser(self, user) :       
564        """Adds a user to the quota storage, returns the old value if it already exists."""
565        oldentry = self.getUser(user.Name)
566        if oldentry.Exists :
567            return oldentry
568        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email, overcharge, description) VALUES (%s, %s, %s, %s, %s, %s, %s)" % \
569                                     (self.doQuote(self.userCharsetToDatabase(user.Name)), \
570                                      self.doQuote(user.LimitBy or 'quota'), \
571                                      self.doQuote(user.AccountBalance or 0.0), \
572                                      self.doQuote(user.LifeTimePaid or 0.0), \
573                                      self.doQuote(user.Email), \
574                                      self.doQuote(user.OverCharge), \
575                                      self.doQuote(self.userCharsetToDatabase(user.Description))))
576        if user.PaymentsBacklog :
577            for (value, comment) in user.PaymentsBacklog :
578                self.writeNewPayment(user, value, comment)
579            user.PaymentsBacklog = []
580        user.isDirty = False
581        return None # the entry created doesn't need further modification
582       
583    def addGroup(self, group) :       
584        """Adds a group to the quota storage, returns the old value if it already exists."""
585        oldentry = self.getGroup(group.Name)
586        if oldentry.Exists :
587            return oldentry
588        self.doModify("INSERT INTO groups (groupname, limitby, description) VALUES (%s, %s, %s)" % \
589                              (self.doQuote(self.userCharsetToDatabase(group.Name)), \
590                               self.doQuote(group.LimitBy or "quota"), \
591                               self.doQuote(self.userCharsetToDatabase(group.Description))))
592        group.isDirty = False
593        return None # the entry created doesn't need further modification
594
595    def addUserToGroup(self, user, group) :   
596        """Adds an user to a group."""
597        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
598        try :
599            mexists = int(result[0].get("mexists"))
600        except (IndexError, TypeError) :   
601            mexists = 0
602        if not mexists :   
603            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
604           
605    def delUserFromGroup(self, user, group) :   
606        """Removes an user from a group."""
607        self.doModify("DELETE FROM groupsmembers WHERE groupid=%s AND userid=%s" % \
608                       (self.doQuote(group.ident), self.doQuote(user.ident)))
609           
610    def addUserPQuota(self, upq) :
611        """Initializes a user print quota on a printer."""
612        oldentry = self.getUserPQuota(upq.User, upq.Printer)
613        if oldentry.Exists :
614            return oldentry
615        self.doModify("INSERT INTO userpquota (userid, printerid, softlimit, hardlimit, warncount, datelimit, pagecounter, lifepagecounter, maxjobsize) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)" \
616                          % (self.doQuote(upq.User.ident), \
617                             self.doQuote(upq.Printer.ident), \
618                             self.doQuote(upq.SoftLimit), \
619                             self.doQuote(upq.HardLimit), \
620                             self.doQuote(upq.WarnCount), \
621                             self.doQuote(upq.DateLimit), \
622                             self.doQuote(upq.PageCounter or 0), \
623                             self.doQuote(upq.LifePageCounter or 0), \
624                             self.doQuote(upq.MaxJobSize)))
625        upq.isDirty = False
626        return None # the entry created doesn't need further modification
627       
628    def addGroupPQuota(self, gpq) :
629        """Initializes a group print quota on a printer."""
630        oldentry = self.getGroupPQuota(gpq.Group, gpq.Printer)
631        if oldentry.Exists :
632            return oldentry
633        self.doModify("INSERT INTO grouppquota (groupid, printerid, softlimit, hardlimit, datelimit, maxjobsize) VALUES (%s, %s, %s, %s, %s, %s)" \
634                          % (self.doQuote(gpq.Group.ident), \
635                             self.doQuote(gpq.Printer.ident), \
636                             self.doQuote(gpq.SoftLimit), \
637                             self.doQuote(gpq.HardLimit), \
638                             self.doQuote(gpq.DateLimit), \
639                             self.doQuote(gpq.MaxJobSize)))
640        gpq.isDirty = False
641        return None # the entry created doesn't need further modification
642       
643    def savePrinter(self, printer) :   
644        """Saves the printer to the database in a single operation."""
645        self.doModify("UPDATE printers SET passthrough=%s, maxjobsize=%s, description=%s, priceperpage=%s, priceperjob=%s WHERE id=%s" \
646                              % (self.doQuote((printer.PassThrough and "t") or "f"), \
647                                 self.doQuote(printer.MaxJobSize or 0), \
648                                 self.doQuote(self.userCharsetToDatabase(printer.Description)), \
649                                 self.doQuote(printer.PricePerPage or 0.0), \
650                                 self.doQuote(printer.PricePerJob or 0.0), \
651                                 self.doQuote(printer.ident)))
652                                 
653    def saveUser(self, user) :       
654        """Saves the user to the database in a single operation."""
655        self.doModify("UPDATE users SET limitby=%s, balance=%s, lifetimepaid=%s, email=%s, overcharge=%s, description=%s WHERE id=%s" \
656                               % (self.doQuote(user.LimitBy or 'quota'), \
657                                  self.doQuote(user.AccountBalance or 0.0), \
658                                  self.doQuote(user.LifeTimePaid or 0.0), \
659                                  self.doQuote(user.Email), \
660                                  self.doQuote(user.OverCharge), \
661                                  self.doQuote(self.userCharsetToDatabase(user.Description)), \
662                                  self.doQuote(user.ident)))
663                                 
664    def saveGroup(self, group) :       
665        """Saves the group to the database in a single operation."""
666        self.doModify("UPDATE groups SET limitby=%s, description=%s WHERE id=%s" \
667                               % (self.doQuote(group.LimitBy or 'quota'), \
668                                  self.doQuote(self.userCharsetToDatabase(group.Description)), \
669                                  self.doQuote(group.ident)))
670       
671    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
672        """Sets the date limit permanently for a user print quota."""
673        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
674           
675    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
676        """Sets the date limit permanently for a group print quota."""
677        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
678       
679    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
680        """Increase page counters for a user print quota."""
681        self.doModify("UPDATE userpquota SET pagecounter=pagecounter + %s,lifepagecounter=lifepagecounter + %s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
682       
683    def saveBillingCode(self, bcode) :   
684        """Saves the billing code to the database."""
685        self.doModify("UPDATE billingcodes SET balance=%s, pagecounter=%s, description=%s WHERE id=%s" \
686                            % (self.doQuote(bcode.Balance or 0.0), \
687                               self.doQuote(bcode.PageCounter or 0), \
688                               self.doQuote(self.userCharsetToDatabase(bcode.Description)), \
689                               self.doQuote(bcode.ident)))
690       
691    def consumeBillingCode(self, bcode, pagecounter, balance) :
692        """Consumes from a billing code."""
693        self.doModify("UPDATE billingcodes SET balance=balance + %s, pagecounter=pagecounter + %s WHERE id=%s" % (self.doQuote(balance), self.doQuote(pagecounter), self.doQuote(bcode.ident)))
694       
695    def decreaseUserAccountBalance(self, user, amount) :   
696        """Decreases user's account balance from an amount."""
697        self.doModify("UPDATE users SET balance=balance - %s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
698       
699    def writeNewPayment(self, user, amount, comment="") :
700        """Adds a new payment to the payments history."""
701        if user.ident is not None :
702            self.doModify("INSERT INTO payments (userid, amount, description) VALUES (%s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment))))
703        else :   
704            self.doModify("INSERT INTO payments (userid, amount, description) VALUES ((SELECT id FROM users WHERE username=%s), %s, %s)" % (self.doQuote(self.userCharsetToDatabase(user.Name)), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment))))
705       
706    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
707        """Sets the last job's size permanently."""
708        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
709       
710    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) :
711        """Adds a job in a printer's history."""
712        if self.privacy :   
713            # For legal reasons, we want to hide the title, filename and options
714            title = filename = options = "hidden"
715        filename = self.userCharsetToDatabase(filename)
716        title = self.userCharsetToDatabase(title)
717        options = self.userCharsetToDatabase(options)
718        jobbilling = self.userCharsetToDatabase(jobbilling)
719        if (not self.disablehistory) or (not printer.LastJob.Exists) :
720            if jobsize is not None :
721                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, hostname, jobsizebytes, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice) VALUES (%s, %s, %s, %s, %s, %s, %s, %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), self.doQuote(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice)))
722            else :   
723                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options, hostname, jobsizebytes, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice) VALUES (%s, %s, %s, %s, %s, %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(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice)))
724        else :       
725            # here we explicitly want to reset jobsize to NULL if needed
726            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, hostname=%s, jobsizebytes=%s, md5sum=%s, pages=%s, billingcode=%s, precomputedjobsize=%s, precomputedjobprice=%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(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice), self.doQuote(printer.LastJob.ident)))
727           
728    def saveUserPQuota(self, userpquota) :
729        """Saves an user print quota entry."""
730        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, warncount=%s, datelimit=%s, pagecounter=%s, lifepagecounter=%s, maxjobsize=%s WHERE id=%s" \
731                              % (self.doQuote(userpquota.SoftLimit), \
732                                 self.doQuote(userpquota.HardLimit), \
733                                 self.doQuote(userpquota.WarnCount), \
734                                 self.doQuote(userpquota.DateLimit), \
735                                 self.doQuote(userpquota.PageCounter or 0), \
736                                 self.doQuote(userpquota.LifePageCounter or 0), \
737                                 self.doQuote(userpquota.MaxJobSize), \
738                                 self.doQuote(userpquota.ident)))
739       
740    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
741        """Sets the warn counter value for a user quota."""
742        self.doModify("UPDATE userpquota SET warncount=%s WHERE id=%s" % (self.doQuote(warncount), self.doQuote(userpquota.ident)))
743       
744    def increaseUserPQuotaWarnCount(self, userpquota) :
745        """Increases the warn counter value for a user quota."""
746        self.doModify("UPDATE userpquota SET warncount=warncount+1 WHERE id=%s" % self.doQuote(userpquota.ident))
747       
748    def saveGroupPQuota(self, grouppquota) :
749        """Saves a group print quota entry."""
750        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=%s WHERE id=%s" \
751                              % (self.doQuote(grouppquota.SoftLimit), \
752                                 self.doQuote(grouppquota.HardLimit), \
753                                 self.doQuote(grouppquota.DateLimit), \
754                                 self.doQuote(grouppquota.ident)))
755
756    def writePrinterToGroup(self, pgroup, printer) :
757        """Puts a printer into a printer group."""
758        children = []
759        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
760        if result :
761            for record in result :
762                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
763        if printer.ident not in children :       
764            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
765       
766    def removePrinterFromGroup(self, pgroup, printer) :
767        """Removes a printer from a printer group."""
768        self.doModify("DELETE FROM printergroupsmembers WHERE groupid=%s AND printerid=%s" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
769       
770    def retrieveHistory(self, user=None, printer=None, hostname=None, billingcode=None, limit=100, start=None, end=None) :
771        """Retrieves all print jobs for user on printer (or all) between start and end date, limited to first 100 results."""
772        query = "SELECT jobhistory.*,username,printername FROM jobhistory,users,printers WHERE users.id=userid AND printers.id=printerid"
773        where = []
774        if user is not None : # user.ident is None anyway if user doesn't exist
775            where.append("userid=%s" % self.doQuote(user.ident))
776        if printer is not None : # printer.ident is None anyway if printer doesn't exist
777            where.append("printerid=%s" % self.doQuote(printer.ident))
778        if hostname is not None :   
779            where.append("hostname=%s" % self.doQuote(hostname))
780        if billingcode is not None :   
781            where.append("billingcode=%s" % self.doQuote(self.userCharsetToDatabase(billingcode)))
782        if start is not None :   
783            where.append("jobdate>=%s" % self.doQuote(start))
784        if end is not None :   
785            where.append("jobdate<=%s" % self.doQuote(end))
786        if where :   
787            query += " AND %s" % " AND ".join(where)
788        query += " ORDER BY jobhistory.id DESC"
789        if limit :
790            query += " LIMIT %s" % self.doQuote(int(limit))
791        jobs = []   
792        result = self.doSearch(query)   
793        if result :
794            for fields in result :
795                job = StorageJob(self)
796                job.ident = fields.get("id")
797                job.JobId = fields.get("jobid")
798                job.PrinterPageCounter = fields.get("pagecounter")
799                job.JobSize = fields.get("jobsize")
800                job.JobPrice = fields.get("jobprice")
801                job.JobAction = fields.get("action")
802                job.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
803                job.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
804                job.JobCopies = fields.get("copies")
805                job.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
806                job.JobDate = fields.get("jobdate")
807                job.JobHostName = fields.get("hostname")
808                job.JobSizeBytes = fields.get("jobsizebytes")
809                job.JobMD5Sum = fields.get("md5sum")
810                job.JobPages = fields.get("pages")
811                job.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode") or "")
812                job.PrecomputedJobSize = fields.get("precomputedjobsize")
813                job.PrecomputedJobPrice = fields.get("precomputedjobprice")
814                job.UserName = self.databaseToUserCharset(fields.get("username"))
815                job.PrinterName = self.databaseToUserCharset(fields.get("printername"))
816                if job.JobTitle == job.JobFileName == job.JobOptions == "hidden" :
817                    (job.JobTitle, job.JobFileName, job.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
818                job.Exists = 1
819                jobs.append(job)
820        return jobs
821       
822    def deleteUser(self, user) :   
823        """Completely deletes an user from the database."""
824        # TODO : What should we do if we delete the last person who used a given printer ?
825        # TODO : we can't reassign the last job to the previous one, because next user would be
826        # TODO : incorrectly charged (overcharged).
827        for q in [ 
828                    "DELETE FROM payments WHERE userid=%s" % self.doQuote(user.ident),
829                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
830                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
831                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
832                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
833                  ] :
834            self.doModify(q)
835           
836    def multipleQueriesInTransaction(self, queries) :       
837        """Does many modifications in a single transaction."""
838        self.beginTransaction()
839        try :
840            for q in queries :
841                self.doModify(q)
842        except :   
843            self.rollbackTransaction()
844            raise
845        else :   
846            self.commitTransaction()
847           
848    def deleteManyBillingCodes(self, billingcodes) :       
849        """Deletes many billing codes."""
850        codeids = ", ".join(["%s" % self.doQuote(b.ident) for b in billingcodes])
851        self.multipleQueriesInTransaction([ 
852                    "DELETE FROM billingcodes WHERE id IN (%s)" % codeids,])
853           
854    def deleteManyUsers(self, users) :       
855        """Deletes many users."""
856        userids = ", ".join(["%s" % self.doQuote(u.ident) for u in users])
857        self.multipleQueriesInTransaction([ 
858                    "DELETE FROM payments WHERE userid IN (%s)" % userids,
859                    "DELETE FROM groupsmembers WHERE userid IN (%s)" % userids,
860                    "DELETE FROM jobhistory WHERE userid IN (%s)" % userids,
861                    "DELETE FROM userpquota WHERE userid IN (%s)" % userids,
862                    "DELETE FROM users WHERE id IN (%s)" % userids,])
863                   
864    def deleteManyGroups(self, groups) :       
865        """Deletes many groups."""
866        groupids = ", ".join(["%s" % self.doQuote(g.ident) for g in groups])
867        self.multipleQueriesInTransaction([ 
868                    "DELETE FROM groupsmembers WHERE groupid IN (%s)" % groupids,
869                    "DELETE FROM grouppquota WHERE groupid IN (%s)" % groupids,
870                    "DELETE FROM groups WHERE id IN (%s)" % groupids,])
871       
872    def deleteManyPrinters(self, printers) :
873        """Deletes many printers."""
874        printerids = ", ".join(["%s" % self.doQuote(p.ident) for p in printers])
875        self.multipleQueriesInTransaction([ 
876                    "DELETE FROM printergroupsmembers WHERE groupid IN (%s) OR printerid IN (%s)" % (printerids, printerids),
877                    "DELETE FROM jobhistory WHERE printerid IN (%s)" % printerids,
878                    "DELETE FROM grouppquota WHERE printerid IN (%s)" % printerids,
879                    "DELETE FROM userpquota WHERE printerid IN (%s)" % printerids,
880                    "DELETE FROM printers WHERE id IN (%s)" % printerids,])
881       
882    def deleteManyUserPQuotas(self, printers, users) :       
883        """Deletes many user print quota entries."""
884        printerids = ", ".join(["%s" % self.doQuote(p.ident) for p in printers])
885        userids = ", ".join(["%s" % self.doQuote(u.ident) for u in users])
886        self.multipleQueriesInTransaction([ 
887                    "DELETE FROM jobhistory WHERE userid IN (%s) AND printerid IN (%s)" \
888                                 % (userids, printerids),
889                    "DELETE FROM userpquota WHERE userid IN (%s) AND printerid IN (%s)" \
890                                 % (userids, printerids),])
891           
892    def deleteManyGroupPQuotas(self, printers, groups) :
893        """Deletes many group print quota entries."""
894        printerids = ", ".join(["%s" % self.doQuote(p.ident) for p in printers])
895        groupids = ", ".join(["%s" % self.doQuote(g.ident) for g in groups])
896        self.multipleQueriesInTransaction([ 
897                    "DELETE FROM grouppquota WHERE groupid IN (%s) AND printerid IN (%s)" \
898                                 % (groupids, printerids),])
899       
900    def deleteUserPQuota(self, upquota) :   
901        """Completely deletes an user print quota entry from the database."""
902        for q in [ 
903                    "DELETE FROM jobhistory WHERE userid=%s AND printerid=%s" \
904                                 % (self.doQuote(upquota.User.ident), self.doQuote(upquota.Printer.ident)),
905                    "DELETE FROM userpquota WHERE id=%s" % self.doQuote(upquota.ident),
906                  ] :
907            self.doModify(q)
908       
909    def deleteGroupPQuota(self, gpquota) :   
910        """Completely deletes a group print quota entry from the database."""
911        for q in [ 
912                    "DELETE FROM grouppquota WHERE id=%s" % self.doQuote(gpquota.ident),
913                  ] :
914            self.doModify(q)
915       
916    def deleteGroup(self, group) :   
917        """Completely deletes a group from the database."""
918        for q in [
919                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
920                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
921                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
922                 ] : 
923            self.doModify(q)
924           
925    def deletePrinter(self, printer) :   
926        """Completely deletes a printer from the database."""
927        for q in [ 
928                    "DELETE FROM printergroupsmembers WHERE groupid=%s OR printerid=%s" % (self.doQuote(printer.ident), self.doQuote(printer.ident)),
929                    "DELETE FROM jobhistory WHERE printerid=%s" % self.doQuote(printer.ident),
930                    "DELETE FROM grouppquota WHERE printerid=%s" % self.doQuote(printer.ident),
931                    "DELETE FROM userpquota WHERE printerid=%s" % self.doQuote(printer.ident),
932                    "DELETE FROM printers WHERE id=%s" % self.doQuote(printer.ident),
933                  ] :
934            self.doModify(q)
935           
936    def deleteBillingCode(self, code) :   
937        """Completely deletes a billing code from the database."""
938        for q in [
939                   "DELETE FROM billingcodes WHERE id=%s" % self.doQuote(code.ident),
940                 ] : 
941            self.doModify(q)
942       
Note: See TracBrowser for help on using the browser.