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

Revision 1718, 30.4 kB (checked in by jalet, 20 years ago)

User groups membership and printer groups membership can now be dumped too

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