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

Revision 1717, 29.6 kB (checked in by jalet, 20 years ago)

First version of dumpykota. Works fine but only with PostgreSQL backend
for now.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.45  2004/09/14 22:29:13  jalet
25# First version of dumpykota. Works fine but only with PostgreSQL backend
26# for now.
27#
28# Revision 1.44  2004/09/10 21:32:54  jalet
29# Small fixes for incomplete entry intialization
30#
31# Revision 1.43  2004/07/01 17:45:49  jalet
32# Added code to handle the description field for printers
33#
34# Revision 1.42  2004/06/08 17:44:43  jalet
35# Payment now gets deleted when the user is deleted
36#
37# Revision 1.41  2004/06/05 22:03:50  jalet
38# Payments history is now stored in database
39#
40# Revision 1.40  2004/06/03 23:14:11  jalet
41# Now stores the job's size in bytes in the database.
42# Preliminary work on payments storage : database schemas are OK now,
43# but no code to store payments yet.
44# Removed schema picture, not relevant anymore.
45#
46# Revision 1.39  2004/05/26 14:50:12  jalet
47# First try at saving the job-originating-hostname in the database
48#
49# Revision 1.38  2004/05/06 12:37:47  jalet
50# pkpgcounter : comments
51# pkprinters : when --add is used, existing printers are now skipped.
52#
53# Revision 1.37  2004/02/23 22:53:21  jalet
54# Don't retrieve data when it's not needed, to avoid database queries
55#
56# Revision 1.36  2004/02/04 13:24:41  jalet
57# pkprinters can now remove printers from printers groups.
58#
59# Revision 1.35  2004/02/04 11:17:00  jalet
60# pkprinters command line tool added.
61#
62# Revision 1.34  2004/02/02 22:44:16  jalet
63# Preliminary work on Relationnal Database Independance via DB-API 2.0
64#
65#
66#
67
68from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
69
70class SQLStorage :
71    def prepareRawResult(self, result) :
72        """Prepares a raw result by including the headers."""
73        if result.ntuples() > 0 :
74            entries = [result.listfields()]
75            entries.extend(result.getresult())
76            return entries
77       
78    def extractPrinters(self) :
79        """Extracts all printer records."""
80        result = self.doRawSearch("SELECT * FROM printers")
81        return self.prepareRawResult(result)
82       
83    def extractUsers(self) :
84        """Extracts all user records."""
85        result = self.doRawSearch("SELECT * FROM users")
86        return self.prepareRawResult(result)
87       
88    def extractGroups(self) :
89        """Extracts all group records."""
90        result = self.doRawSearch("SELECT * FROM groups")
91        return self.prepareRawResult(result)
92       
93    def extractPayments(self) :
94        """Extracts all payment records."""
95        result = self.doRawSearch("SELECT username,payments.* FROM users,payments WHERE users.id=payments.userid")
96        return self.prepareRawResult(result)
97       
98    def extractUpquotas(self) :
99        """Extracts all userpquota records."""
100        result = self.doRawSearch("SELECT users.username,printers.printername,userpquota.* FROM users,printers,userpquota WHERE users.id=userpquota.userid AND printers.id=userpquota.printerid")
101        return self.prepareRawResult(result)
102       
103    def extractGpquotas(self) :
104        """Extracts all grouppquota records."""
105        result = self.doRawSearch("SELECT groups.groupname,printers.printername,grouppquota.* FROM groups,printers,grouppquota WHERE groups.id=grouppquota.groupid AND printers.id=grouppquota.printerid")
106        return self.prepareRawResult(result)
107       
108    def extractHistory(self) :
109        """Extracts all jobhistory records."""
110        result = self.doRawSearch("SELECT users.username,printers.printername,jobhistory.* FROM users,printers,jobhistory WHERE users.id=jobhistory.userid AND printers.id=jobhistory.printerid")
111        return self.prepareRawResult(result)
112       
113    def getAllUsersNames(self) :   
114        """Extracts all user names."""
115        usernames = []
116        result = self.doSearch("SELECT username FROM users")
117        if result :
118            usernames = [record["username"] for record in result]
119        return usernames
120       
121    def getAllGroupsNames(self) :   
122        """Extracts all group names."""
123        groupnames = []
124        result = self.doSearch("SELECT groupname FROM groups")
125        if result :
126            groupnames = [record["groupname"] for record in result]
127        return groupnames
128       
129    def getUserFromBackend(self, username) :   
130        """Extracts user information given its name."""
131        user = StorageUser(self, username)
132        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
133        if result :
134            fields = result[0]
135            user.ident = fields.get("id")
136            user.Name = fields.get("username", username)
137            user.LimitBy = fields.get("limitby")
138            user.AccountBalance = fields.get("balance")
139            user.LifeTimePaid = fields.get("lifetimepaid")
140            user.Email = fields.get("email")
141            user.Exists = 1
142        return user
143       
144    def getGroupFromBackend(self, groupname) :   
145        """Extracts group information given its name."""
146        group = StorageGroup(self, groupname)
147        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
148        if result :
149            fields = result[0]
150            group.ident = fields.get("id")
151            group.Name = fields.get("groupname", groupname)
152            group.LimitBy = fields.get("limitby")
153            result = self.doSearch("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(group.ident))
154            if result :
155                fields = result[0]
156                group.AccountBalance = fields.get("balance")
157                group.LifeTimePaid = fields.get("lifetimepaid")
158            group.Exists = 1
159        return group
160       
161    def getPrinterFromBackend(self, printername) :       
162        """Extracts printer information given its name."""
163        printer = StoragePrinter(self, printername)
164        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
165        if result :
166            fields = result[0]
167            printer.ident = fields.get("id")
168            printer.Name = fields.get("printername", printername)
169            printer.PricePerJob = fields.get("priceperjob") or 0.0
170            printer.PricePerPage = fields.get("priceperpage") or 0.0
171            printer.Description = fields.get("description") or ""
172            printer.Exists = 1
173        return printer   
174       
175    def getUserPQuotaFromBackend(self, user, printer) :       
176        """Extracts a user print quota."""
177        userpquota = StorageUserPQuota(self, user, printer)
178        if printer.Exists and user.Exists :
179            result = self.doSearch("SELECT id, lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
180            if result :
181                fields = result[0]
182                userpquota.ident = fields.get("id")
183                userpquota.PageCounter = fields.get("pagecounter")
184                userpquota.LifePageCounter = fields.get("lifepagecounter")
185                userpquota.SoftLimit = fields.get("softlimit")
186                userpquota.HardLimit = fields.get("hardlimit")
187                userpquota.DateLimit = fields.get("datelimit")
188                userpquota.Exists = 1
189        return userpquota
190       
191    def getGroupPQuotaFromBackend(self, group, printer) :       
192        """Extracts a group print quota."""
193        grouppquota = StorageGroupPQuota(self, group, printer)
194        if group.Exists :
195            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
196            if result :
197                fields = result[0]
198                grouppquota.ident = fields.get("id")
199                grouppquota.SoftLimit = fields.get("softlimit")
200                grouppquota.HardLimit = fields.get("hardlimit")
201                grouppquota.DateLimit = fields.get("datelimit")
202                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)))
203                if result :
204                    fields = result[0]
205                    grouppquota.PageCounter = fields.get("pagecounter")
206                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
207                grouppquota.Exists = 1
208        return grouppquota
209       
210    def getPrinterLastJobFromBackend(self, printer) :       
211        """Extracts a printer's last job information."""
212        lastjob = StorageLastJob(self, printer)
213        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, hostname, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
214        if result :
215            fields = result[0]
216            lastjob.ident = fields.get("id")
217            lastjob.JobId = fields.get("jobid")
218            lastjob.UserName = fields.get("username")
219            lastjob.PrinterPageCounter = fields.get("pagecounter")
220            lastjob.JobSize = fields.get("jobsize")
221            lastjob.JobPrice = fields.get("jobprice")
222            lastjob.JobAction = fields.get("action")
223            lastjob.JobFileName = fields.get("filename")
224            lastjob.JobTitle = fields.get("title")
225            lastjob.JobCopies = fields.get("copies")
226            lastjob.JobOptions = fields.get("options")
227            lastjob.JobDate = fields.get("jobdate")
228            lastjob.JobHostName = fields.get("hostname")
229            lastjob.JobSizeBytes = fields.get("jobsizebytes")
230            lastjob.Exists = 1
231        return lastjob
232           
233    def getGroupMembersFromBackend(self, group) :       
234        """Returns the group's members list."""
235        groupmembers = []
236        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
237        if result :
238            for record in result :
239                user = StorageUser(self, record.get("username"))
240                user.ident = record.get("userid")
241                user.LimitBy = record.get("limitby")
242                user.AccountBalance = record.get("balance")
243                user.LifeTimePaid = record.get("lifetimepaid")
244                user.Email = record.get("email")
245                user.Exists = 1
246                groupmembers.append(user)
247                self.cacheEntry("USERS", user.Name, user)
248        return groupmembers       
249       
250    def getUserGroupsFromBackend(self, user) :       
251        """Returns the user's groups list."""
252        groups = []
253        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
254        if result :
255            for record in result :
256                groups.append(self.getGroup(record.get("groupname")))
257        return groups       
258       
259    def getParentPrintersFromBackend(self, printer) :   
260        """Get all the printer groups this printer is a member of."""
261        pgroups = []
262        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
263        if result :
264            for record in result :
265                if record["groupid"] != printer.ident : # in case of integrity violation
266                    parentprinter = self.getPrinter(record.get("printername"))
267                    if parentprinter.Exists :
268                        pgroups.append(parentprinter)
269        return pgroups
270       
271    def getMatchingPrinters(self, printerpattern) :
272        """Returns the list of all printers for which name matches a certain pattern."""
273        printers = []
274        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
275        # but we don't because other storages semantics may be different, so every
276        # storage should use fnmatch to match patterns and be storage agnostic
277        result = self.doSearch("SELECT * FROM printers")
278        if result :
279            for record in result :
280                if self.tool.matchString(record["printername"], printerpattern.split(",")) :
281                    printer = StoragePrinter(self, record["printername"])
282                    printer.ident = record.get("id")
283                    printer.PricePerJob = record.get("priceperjob") or 0.0
284                    printer.PricePerPage = record.get("priceperpage") or 0.0
285                    printer.Description = record.get("description") or ""
286                    printer.Exists = 1
287                    printers.append(printer)
288                    self.cacheEntry("PRINTERS", printer.Name, printer)
289        return printers       
290       
291    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
292        """Returns the list of users who uses a given printer, along with their quotas."""
293        usersandquotas = []
294        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,email,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
295        if result :
296            for record in result :
297                if self.tool.matchString(record.get("username"), names) :
298                    user = StorageUser(self, record.get("username"))
299                    user.ident = record.get("uid")
300                    user.LimitBy = record.get("limitby")
301                    user.AccountBalance = record.get("balance")
302                    user.LifeTimePaid = record.get("lifetimepaid")
303                    user.Email = record.get("email") 
304                    user.Exists = 1
305                    userpquota = StorageUserPQuota(self, user, printer)
306                    userpquota.ident = record.get("id")
307                    userpquota.PageCounter = record.get("pagecounter")
308                    userpquota.LifePageCounter = record.get("lifepagecounter")
309                    userpquota.SoftLimit = record.get("softlimit")
310                    userpquota.HardLimit = record.get("hardlimit")
311                    userpquota.DateLimit = record.get("datelimit")
312                    userpquota.Exists = 1
313                    usersandquotas.append((user, userpquota))
314                    self.cacheEntry("USERS", user.Name, user)
315                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
316        return usersandquotas
317               
318    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
319        """Returns the list of groups which uses a given printer, along with their quotas."""
320        groupsandquotas = []
321        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))
322        if result :
323            for record in result :
324                if self.tool.matchString(record.get("groupname"), names) :
325                    group = self.getGroup(record.get("groupname"))
326                    grouppquota = self.getGroupPQuota(group, printer)
327                    groupsandquotas.append((group, grouppquota))
328        return groupsandquotas
329       
330    def addPrinter(self, printername) :       
331        """Adds a printer to the quota storage, returns it."""
332        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
333        return self.getPrinter(printername)
334       
335    def addUser(self, user) :       
336        """Adds a user to the quota storage, returns its id."""
337        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy or 'quota'), self.doQuote(user.AccountBalance or 0.0), self.doQuote(user.LifeTimePaid or 0.0), self.doQuote(user.Email)))
338        return self.getUser(user.Name)
339       
340    def addGroup(self, group) :       
341        """Adds a group to the quota storage, returns its id."""
342        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy or "quota")))
343        return self.getGroup(group.Name)
344
345    def addUserToGroup(self, user, group) :   
346        """Adds an user to a group."""
347        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
348        try :
349            mexists = int(result[0].get("mexists"))
350        except (IndexError, TypeError) :   
351            mexists = 0
352        if not mexists :   
353            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
354           
355    def addUserPQuota(self, user, printer) :
356        """Initializes a user print quota on a printer."""
357        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
358        return self.getUserPQuota(user, printer)
359       
360    def addGroupPQuota(self, group, printer) :
361        """Initializes a group print quota on a printer."""
362        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
363        return self.getGroupPQuota(group, printer)
364       
365    def writePrinterPrices(self, printer) :   
366        """Write the printer's prices back into the storage."""
367        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
368       
369    def writePrinterDescription(self, printer) :   
370        """Write the printer's description back into the storage."""
371        self.doModify("UPDATE printers SET description=%s WHERE id=%s" % (self.doQuote(printer.Description), self.doQuote(printer.ident)))
372       
373    def writeUserLimitBy(self, user, limitby) :   
374        """Sets the user's limiting factor."""
375        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
376       
377    def writeGroupLimitBy(self, group, limitby) :   
378        """Sets the group's limiting factor."""
379        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
380       
381    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
382        """Sets the date limit permanently for a user print quota."""
383        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
384           
385    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
386        """Sets the date limit permanently for a group print quota."""
387        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
388       
389    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
390        """Increase page counters for a user print quota."""
391        self.doModify("UPDATE userpquota SET pagecounter=pagecounter+%s,lifepagecounter=lifepagecounter+%s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
392       
393    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
394        """Sets the new page counters permanently for a user print quota."""
395        self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
396       
397    def decreaseUserAccountBalance(self, user, amount) :   
398        """Decreases user's account balance from an amount."""
399        self.doModify("UPDATE users SET balance=balance-%s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
400       
401    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
402        """Sets the new account balance and eventually new lifetime paid."""
403        if newlifetimepaid is not None :
404            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
405        else :   
406            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
407           
408    def writeNewPayment(self, user, amount) :       
409        """Adds a new payment to the payments history."""
410        self.doModify("INSERT INTO payments (userid, amount) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(amount)))
411       
412    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
413        """Sets the last job's size permanently."""
414        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
415       
416    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) :   
417        """Adds a job in a printer's history."""
418        if (not self.disablehistory) or (not printer.LastJob.Exists) :
419            if jobsize is not None :
420                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, hostname, jobsizebytes) VALUES (%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)))
421            else :   
422                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options, hostname, jobsizebytes) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(clienthost), self.doQuote(jobsizebytes)))
423        else :       
424            # here we explicitly want to reset jobsize to NULL if needed
425            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, 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(printer.LastJob.ident)))
426           
427    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
428        """Sets soft and hard limits for a user quota."""
429        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
430       
431    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
432        """Sets soft and hard limits for a group quota on a specific printer."""
433        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
434
435    def writePrinterToGroup(self, pgroup, printer) :
436        """Puts a printer into a printer group."""
437        children = []
438        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
439        if result :
440            for record in result :
441                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
442        if printer.ident not in children :       
443            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
444       
445    def removePrinterFromGroup(self, pgroup, printer) :
446        """Removes a printer from a printer group."""
447        self.doModify("DELETE FROM printergroupsmembers WHERE groupid=%s AND printerid=%s" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
448       
449    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
450        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
451        query = "SELECT jobhistory.*,username,printername FROM jobhistory,users,printers WHERE users.id=userid AND printers.id=printerid"
452        where = []
453        if (user is not None) and user.Exists :
454            where.append("userid=%s" % self.doQuote(user.ident))
455        if (printer is not None) and printer.Exists :
456            where.append("printerid=%s" % self.doQuote(printer.ident))
457        if hostname is not None :   
458            where.append("hostname=%s" % self.doQuote(hostname))
459        if datelimit is not None :   
460            where.append("jobdate<=%s" % self.doQuote(datelimit))
461        if where :   
462            query += " AND %s" % " AND ".join(where)
463        query += " ORDER BY id DESC"
464        if limit :
465            query += " LIMIT %s" % self.doQuote(int(limit))
466        jobs = []   
467        result = self.doSearch(query)   
468        if result :
469            for fields in result :
470                job = StorageJob(self)
471                job.ident = fields.get("id")
472                job.JobId = fields.get("jobid")
473                job.PrinterPageCounter = fields.get("pagecounter")
474                job.JobSize = fields.get("jobsize")
475                job.JobPrice = fields.get("jobprice")
476                job.JobAction = fields.get("action")
477                job.JobFileName = fields.get("filename")
478                job.JobTitle = fields.get("title")
479                job.JobCopies = fields.get("copies")
480                job.JobOptions = fields.get("options")
481                job.JobDate = fields.get("jobdate")
482                job.JobHostName = fields.get("hostname")
483                job.JobSizeBytes = fields.get("jobsizebytes")
484                job.UserName = fields.get("username")
485                job.PrinterName = fields.get("printername")
486                job.Exists = 1
487                jobs.append(job)
488        return jobs
489       
490    def deleteUser(self, user) :   
491        """Completely deletes an user from the Quota Storage."""
492        # TODO : What should we do if we delete the last person who used a given printer ?
493        # TODO : we can't reassign the last job to the previous one, because next user would be
494        # TODO : incorrectly charged (overcharged).
495        for q in [ 
496                    "DELETE FROM payments WHERE userid=%s" % self.doQuote(user.ident),
497                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
498                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
499                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
500                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
501                  ] :
502            self.doModify(q)
503       
504    def deleteGroup(self, group) :   
505        """Completely deletes a group from the Quota Storage."""
506        for q in [
507                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
508                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
509                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
510                 ] : 
511            self.doModify(q)
512           
513    def deletePrinter(self, printer) :   
514        """Completely deletes a printer from the Quota Storage."""
515        for q in [ 
516                    "DELETE FROM printergroupsmembers WHERE groupid=%s OR printerid=%s" % (self.doQuote(printer.ident), self.doQuote(printer.ident)),
517                    "DELETE FROM jobhistory WHERE printerid=%s" % self.doQuote(printer.ident),
518                    "DELETE FROM grouppquota WHERE printerid=%s" % self.doQuote(printer.ident),
519                    "DELETE FROM userpquota WHERE printerid=%s" % self.doQuote(printer.ident),
520                    "DELETE FROM printers WHERE id=%s" % self.doQuote(printer.ident),
521                  ] :
522            self.doModify(q)
523       
Note: See TracBrowser for help on using the browser.