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

Revision 1777, 33.6 kB (checked in by jalet, 20 years ago)

Restore compatibility with Python 2.1

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