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

Revision 2775, 56.7 kB (checked in by jerome, 18 years ago)

Fixed billing code extraction : it didn't have the speed improvements
that was added to printers, users and groups.

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