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

Revision 1762, 32.7 kB (checked in by jalet, 20 years ago)

Some work done of user's charset handling in database dumps.

  • 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.49  2004/10/02 13:33:13  jalet
25# Some work done of user's charset handling in database dumps.
26#
27# Revision 1.48  2004/10/02 05:48:56  jalet
28# Should now correctly deal with charsets both when storing into databases and when
29# retrieving datas. Works with both PostgreSQL and LDAP.
30#
31# Revision 1.47  2004/09/15 07:26:20  jalet
32# Data dumps are now ordered by entry creation date if applicable.
33# Now dumpykota exits with a message when there's a broken pipe like
34# in dumpykota --data history | head -3
35#
36# Revision 1.46  2004/09/15 06:58:25  jalet
37# User groups membership and printer groups membership can now be dumped too
38#
39# Revision 1.45  2004/09/14 22:29:13  jalet
40# First version of dumpykota. Works fine but only with PostgreSQL backend
41# for now.
42#
43# Revision 1.44  2004/09/10 21:32:54  jalet
44# Small fixes for incomplete entry intialization
45#
46# Revision 1.43  2004/07/01 17:45:49  jalet
47# Added code to handle the description field for printers
48#
49# Revision 1.42  2004/06/08 17:44:43  jalet
50# Payment now gets deleted when the user is deleted
51#
52# Revision 1.41  2004/06/05 22:03:50  jalet
53# Payments history is now stored in database
54#
55# Revision 1.40  2004/06/03 23:14:11  jalet
56# Now stores the job's size in bytes in the database.
57# Preliminary work on payments storage : database schemas are OK now,
58# but no code to store payments yet.
59# Removed schema picture, not relevant anymore.
60#
61# Revision 1.39  2004/05/26 14:50:12  jalet
62# First try at saving the job-originating-hostname in the database
63#
64# Revision 1.38  2004/05/06 12:37:47  jalet
65# pkpgcounter : comments
66# pkprinters : when --add is used, existing printers are now skipped.
67#
68# Revision 1.37  2004/02/23 22:53:21  jalet
69# Don't retrieve data when it's not needed, to avoid database queries
70#
71# Revision 1.36  2004/02/04 13:24:41  jalet
72# pkprinters can now remove printers from printers groups.
73#
74# Revision 1.35  2004/02/04 11:17:00  jalet
75# pkprinters command line tool added.
76#
77# Revision 1.34  2004/02/02 22:44:16  jalet
78# Preliminary work on Relationnal Database Independance via DB-API 2.0
79#
80#
81#
82
83from types import StringType
84from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
85
86class SQLStorage :
87    def prepareRawResult(self, result) :
88        """Prepares a raw result by including the headers."""
89        if result.ntuples() > 0 :
90            entries = [result.listfields()]
91            entries.extend(result.getresult())
92            #nbfields = len(entries[0])
93            #for i in range(1, len(entries)) :
94            #    fields = list(entries[i])
95            #    for j in range(nbfields) :
96            #        field = fields[j]
97            #        if type(field) == StringType :
98            #            try :
99            #                fields[j] = field.decode("UTF-8").encode(self.tool.getCharset())
100            #            except UnicodeEncodeError : # takes care of old jobs in history not stored as UTF-8   
101            #                pass
102            #    entries[i] = tuple(fields)   
103            return entries
104       
105    def extractPrinters(self) :
106        """Extracts all printer records."""
107        result = self.doRawSearch("SELECT * FROM printers ORDER BY id ASC")
108        return self.prepareRawResult(result)
109       
110    def extractUsers(self) :
111        """Extracts all user records."""
112        result = self.doRawSearch("SELECT * FROM users ORDER BY id ASC")
113        return self.prepareRawResult(result)
114       
115    def extractGroups(self) :
116        """Extracts all group records."""
117        result = self.doRawSearch("SELECT * FROM groups ORDER BY id ASC")
118        return self.prepareRawResult(result)
119       
120    def extractPayments(self) :
121        """Extracts all payment records."""
122        result = self.doRawSearch("SELECT username,payments.* FROM users,payments WHERE users.id=payments.userid ORDER BY payments.id ASC")
123        return self.prepareRawResult(result)
124       
125    def extractUpquotas(self) :
126        """Extracts all userpquota records."""
127        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")
128        return self.prepareRawResult(result)
129       
130    def extractGpquotas(self) :
131        """Extracts all grouppquota records."""
132        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")
133        return self.prepareRawResult(result)
134       
135    def extractUmembers(self) :
136        """Extracts all user groups members."""
137        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")
138        return self.prepareRawResult(result)
139       
140    def extractPmembers(self) :
141        """Extracts all printer groups members."""
142        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")
143        return self.prepareRawResult(result)
144       
145    def extractHistory(self) :
146        """Extracts all jobhistory records."""
147        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")
148        return self.prepareRawResult(result)
149       
150    def getAllUsersNames(self) :   
151        """Extracts all user names."""
152        usernames = []
153        result = self.doSearch("SELECT username FROM users")
154        if result :
155            usernames = [record["username"] for record in result]
156        return usernames
157       
158    def getAllGroupsNames(self) :   
159        """Extracts all group names."""
160        groupnames = []
161        result = self.doSearch("SELECT groupname FROM groups")
162        if result :
163            groupnames = [record["groupname"] for record in result]
164        return groupnames
165       
166    def getUserFromBackend(self, username) :   
167        """Extracts user information given its name."""
168        user = StorageUser(self, username)
169        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
170        if result :
171            fields = result[0]
172            user.ident = fields.get("id")
173            user.Name = fields.get("username", username)
174            user.LimitBy = fields.get("limitby")
175            user.AccountBalance = fields.get("balance")
176            user.LifeTimePaid = fields.get("lifetimepaid")
177            user.Email = fields.get("email")
178            user.Exists = 1
179        return user
180       
181    def getGroupFromBackend(self, groupname) :   
182        """Extracts group information given its name."""
183        group = StorageGroup(self, groupname)
184        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
185        if result :
186            fields = result[0]
187            group.ident = fields.get("id")
188            group.Name = fields.get("groupname", groupname)
189            group.LimitBy = fields.get("limitby")
190            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))
191            if result :
192                fields = result[0]
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 id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.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                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)))
240                if result :
241                    fields = result[0]
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.