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

Revision 1769, 32.9 kB (checked in by jalet, 20 years ago)

More complete dumps for groups and groups quotas

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