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

Revision 1770, 33.4 kB (checked in by jalet, 20 years ago)

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