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

Revision 1719, 30.9 kB (checked in by jalet, 20 years ago)

Data dumps are now ordered by entry creation date if applicable.
Now dumpykota exits with a message when there's a broken pipe like
in dumpykota --data history | head -3

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