root / pykota / trunk / pykota / storages / pgstorage.py @ 1115

Revision 1115, 22.4 kB (checked in by jalet, 21 years ago)

Bug fix by Oleg Biteryakov

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.12  2003/08/17 14:20:25  jalet
24# Bug fix by Oleg Biteryakov
25#
26# Revision 1.11  2003/07/29 20:55:17  jalet
27# 1.14 is out !
28#
29# Revision 1.10  2003/07/16 21:53:08  jalet
30# Really big modifications wrt new configuration file's location and content.
31#
32# Revision 1.9  2003/07/14 17:20:15  jalet
33# Bug in postgresql storage when modifying the prices for a printer
34#
35# Revision 1.8  2003/07/14 14:18:17  jalet
36# Wrong documentation strings
37#
38# Revision 1.7  2003/07/09 20:17:07  jalet
39# Email field added to PostgreSQL schema
40#
41# Revision 1.6  2003/07/07 11:49:24  jalet
42# Lots of small fixes with the help of PyChecker
43#
44# Revision 1.5  2003/07/07 08:33:19  jalet
45# Bug fix due to a typo in LDAP code
46#
47# Revision 1.4  2003/06/30 13:54:21  jalet
48# Sorts by user / group name
49#
50# Revision 1.3  2003/06/25 14:10:01  jalet
51# Hey, it may work (edpykota --reset excepted) !
52#
53# Revision 1.2  2003/06/12 21:09:57  jalet
54# wrongly placed code.
55#
56# Revision 1.1  2003/06/10 16:37:54  jalet
57# Deletion of the second user which is not needed anymore.
58# Added a debug configuration field in /etc/pykota.conf
59# All queries can now be sent to the logger in debug mode, this will
60# greatly help improve performance when time for this will come.
61#
62#
63#
64#
65
66from pykota.storage import PyKotaStorageError
67from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
68
69try :
70    import pg
71except ImportError :   
72    import sys
73    # TODO : to translate or not to translate ?
74    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
75
76class Storage :
77    def __init__(self, pykotatool, host, dbname, user, passwd) :
78        """Opens the PostgreSQL database connection."""
79        self.tool = pykotatool
80        self.debug = pykotatool.config.getDebug()
81        self.closed = 1
82        try :
83            (host, port) = host.split(":")
84            port = int(port)
85        except ValueError :   
86            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
87       
88        try :
89            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
90        except pg.error, msg :
91            raise PyKotaStorageError, msg
92        else :   
93            self.closed = 0
94            if self.debug :
95                self.tool.logger.log_message("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user), "debug")
96           
97    def __del__(self) :       
98        """Ensures that the database connection is closed."""
99        self.close()
100       
101    def close(self) :   
102        """Closes the database connection."""
103        if not self.closed :
104            self.database.close()
105            self.closed = 1
106            if self.debug :
107                self.tool.logger.log_message("Database closed.", "debug")
108       
109    def beginTransaction(self) :   
110        """Starts a transaction."""
111        self.database.query("BEGIN;")
112        if self.debug :
113            self.tool.logger.log_message("Transaction begins...", "debug")
114       
115    def commitTransaction(self) :   
116        """Commits a transaction."""
117        self.database.query("COMMIT;")
118        if self.debug :
119            self.tool.logger.log_message("Transaction committed.", "debug")
120       
121    def rollbackTransaction(self) :     
122        """Rollbacks a transaction."""
123        self.database.query("ROLLBACK;")
124        if self.debug :
125            self.tool.logger.log_message("Transaction aborted.", "debug")
126       
127    def doSearch(self, query) :
128        """Does a search query."""
129        query = query.strip()   
130        if not query.endswith(';') :   
131            query += ';'
132        try :
133            if self.debug :
134                self.tool.logger.log_message("QUERY : %s" % query, "debug")
135            result = self.database.query(query)
136        except pg.error, msg :   
137            raise PyKotaStorageError, msg
138        else :   
139            if (result is not None) and (result.ntuples() > 0) : 
140                return result.dictresult()
141           
142    def doModify(self, query) :
143        """Does a (possibly multiple) modify query."""
144        query = query.strip()   
145        if not query.endswith(';') :   
146            query += ';'
147        try :
148            if self.debug :
149                self.tool.logger.log_message("QUERY : %s" % query, "debug")
150            result = self.database.query(query)
151        except pg.error, msg :   
152            raise PyKotaStorageError, msg
153        else :   
154            return result
155           
156    def doQuote(self, field) :
157        """Quotes a field for use as a string in SQL queries."""
158        if type(field) == type(0.0) : 
159            typ = "decimal"
160        elif type(field) == type(0) :   
161            typ = "int"
162        else :   
163            typ = "text"
164        return pg._quote(field, typ)
165       
166    def getUser(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.LimitBy = fields.get("limitby")
174            user.AccountBalance = fields.get("balance")
175            user.LifeTimePaid = fields.get("lifetimepaid")
176            user.Email = fields.get("email")
177            user.Exists = 1
178        return user
179       
180    def getGroup(self, groupname) :   
181        """Extracts group information given its name."""
182        group = StorageGroup(self, groupname)
183        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
184        if result :
185            fields = result[0]
186            group.ident = fields.get("id")
187            group.LimitBy = fields.get("limitby")
188            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))
189            if result :
190                fields = result[0]
191                group.AccountBalance = fields.get("balance")
192                group.LifeTimePaid = fields.get("lifetimepaid")
193            group.Exists = 1
194        return group
195       
196    def getPrinter(self, printername) :       
197        """Extracts printer information given its name."""
198        printer = StoragePrinter(self, printername)
199        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
200        if result :
201            fields = result[0]
202            printer.ident = fields.get("id")
203            printer.PricePerJob = fields.get("priceperjob")
204            printer.PricePerPage = fields.get("priceperpage")
205            printer.LastJob = self.getPrinterLastJob(printer)
206            printer.Exists = 1
207        return printer   
208           
209    def getUserGroups(self, user) :       
210        """Returns the user's groups list."""
211        groups = []
212        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
213        if result :
214            for record in result :
215                groups.append(self.getGroup(record.get("groupname")))
216        return groups       
217       
218    def getGroupMembers(self, group) :       
219        """Returns the group's members list."""
220        groupmembers = []
221        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
222        if result :
223            for record in result :
224                user = StorageUser(self, record.get("username"))
225                user.ident = record.get("userid")
226                user.LimitBy = record.get("limitby")
227                user.AccountBalance = record.get("balance")
228                user.LifeTimePaid = record.get("lifetimepaid")
229                user.Email = record.get("email")
230                user.Exists = 1
231                groupmembers.append(user)
232        return groupmembers       
233       
234    def getUserPQuota(self, user, printer) :       
235        """Extracts a user print quota."""
236        userpquota = StorageUserPQuota(self, user, printer)
237        if user.Exists :
238            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)))
239            if result :
240                fields = result[0]
241                userpquota.ident = fields.get("id")
242                userpquota.PageCounter = fields.get("pagecounter")
243                userpquota.LifePageCounter = fields.get("lifepagecounter")
244                userpquota.SoftLimit = fields.get("softlimit")
245                userpquota.HardLimit = fields.get("hardlimit")
246                userpquota.DateLimit = fields.get("datelimit")
247                userpquota.Exists = 1
248        return userpquota
249       
250    def getGroupPQuota(self, group, printer) :       
251        """Extracts a group print quota."""
252        grouppquota = StorageGroupPQuota(self, group, printer)
253        if group.Exists :
254            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
255            if result :
256                fields = result[0]
257                grouppquota.ident = fields.get("id")
258                grouppquota.SoftLimit = fields.get("softlimit")
259                grouppquota.HardLimit = fields.get("hardlimit")
260                grouppquota.DateLimit = fields.get("datelimit")
261                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)))
262                if result :
263                    fields = result[0]
264                    grouppquota.PageCounter = fields.get("pagecounter")
265                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
266                grouppquota.Exists = 1
267        return grouppquota
268       
269    def getPrinterLastJob(self, printer) :       
270        """Extracts a printer's last job information."""
271        lastjob = StorageLastJob(self, printer)
272        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
273        if result :
274            fields = result[0]
275            lastjob.ident = fields.get("id")
276            lastjob.JobId = fields.get("jobid")
277            lastjob.User = self.getUser(fields.get("username"))
278            lastjob.PrinterPageCounter = fields.get("pagecounter")
279            lastjob.JobSize = fields.get("jobsize")
280            lastjob.JobAction = fields.get("action")
281            lastjob.JobDate = fields.get("jobdate")
282            lastjob.Exists = 1
283        return lastjob
284       
285    def getMatchingPrinters(self, printerpattern) :
286        """Returns the list of all printers for which name matches a certain pattern."""
287        printers = []
288        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
289        # but we don't because other storages semantics may be different, so every
290        # storage should use fnmatch to match patterns and be storage agnostic
291        result = self.doSearch("SELECT * FROM printers")
292        if result :
293            for record in result :
294                if self.tool.matchString(record["printername"], [ printerpattern ]) :
295                    printer = StoragePrinter(self, record["printername"])
296                    printer.ident = record.get("id")
297                    printer.PricePerJob = record.get("priceperjob")
298                    printer.PricePerPage = record.get("priceperpage")
299                    printer.LastJob = self.getPrinterLastJob(printer)
300                    printer.Exists = 1
301                    printers.append(printer)
302        return printers       
303       
304    def getPrinterUsersAndQuotas(self, printer, names=None) :       
305        """Returns the list of users who uses a given printer, along with their quotas."""
306        usersandquotas = []
307        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))
308        if result :
309            for record in result :
310                user = StorageUser(self, record.get("username"))
311                if (names is None) or self.tool.matchString(user.Name, names) :
312                    user.ident = record.get("uid")
313                    user.LimitBy = record.get("limitby")
314                    user.AccountBalance = record.get("balance")
315                    user.LifeTimePaid = record.get("lifetimepaid")
316                    user.Email = record.get("email") 
317                    user.Exists = 1
318                    userpquota = StorageUserPQuota(self, user, printer)
319                    userpquota.ident = record.get("id")
320                    userpquota.PageCounter = record.get("pagecounter")
321                    userpquota.LifePageCounter = record.get("lifepagecounter")
322                    userpquota.SoftLimit = record.get("softlimit")
323                    userpquota.HardLimit = record.get("hardlimit")
324                    userpquota.DateLimit = record.get("datelimit")
325                    userpquota.Exists = 1
326                    usersandquotas.append((user, userpquota))
327        return usersandquotas
328               
329    def getPrinterGroupsAndQuotas(self, printer, names=None) :       
330        """Returns the list of groups which uses a given printer, along with their quotas."""
331        groupsandquotas = []
332        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))
333        if result :
334            for record in result :
335                group = self.getGroup(record.get("groupname"))
336                if (names is None) or self.tool.matchString(group.Name, names) :
337                    grouppquota = self.getGroupPQuota(group, printer)
338                    groupsandquotas.append((group, grouppquota))
339        return groupsandquotas
340       
341    def addPrinter(self, printername) :       
342        """Adds a printer to the quota storage, returns it."""
343        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
344        return self.getPrinter(printername)
345       
346    def addUser(self, user) :       
347        """Adds a user to the quota storage, returns its id."""
348        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid), self.doQuote(user.Email)))
349        return self.getUser(user.Name)
350       
351    def addGroup(self, group) :       
352        """Adds a group to the quota storage, returns its id."""
353        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
354        return self.getGroup(group.Name)
355
356    def addUserToGroup(self, user, group) :   
357        """Adds an user to a group."""
358        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
359        try :
360            mexists = int(result[0].get("mexists"))
361        except (IndexError, TypeError) :   
362            mexists = 0
363        if not mexists :   
364            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
365           
366    def addUserPQuota(self, user, printer) :
367        """Initializes a user print quota on a printer."""
368        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
369        return self.getUserPQuota(user, printer)
370       
371    def addGroupPQuota(self, group, printer) :
372        """Initializes a group print quota on a printer."""
373        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
374        return self.getGroupPQuota(group, printer)
375       
376    def writePrinterPrices(self, printer) :   
377        """Write the printer's prices back into the storage."""
378        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
379       
380    def writeUserLimitBy(self, user, limitby) :   
381        """Sets the user's limiting factor."""
382        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
383       
384    def writeGroupLimitBy(self, group, limitby) :   
385        """Sets the group's limiting factor."""
386        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
387       
388    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
389        """Sets the date limit permanently for a user print quota."""
390        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
391           
392    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
393        """Sets the date limit permanently for a group print quota."""
394        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
395       
396    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
397       """Sets the new page counters permanently for a user print quota."""
398       self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
399       
400    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
401       """Sets the new account balance and eventually new lifetime paid."""
402       if newlifetimepaid is not None :
403           self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
404       else :   
405           self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
406           
407    def writeLastJobSize(self, lastjob, jobsize) :       
408        """Sets the last job's size permanently."""
409        self.doModify("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(lastjob.ident)))
410       
411    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
412        """Adds a job in a printer's history."""
413        if jobsize is not None :
414            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize) VALUES (%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)))
415        else :   
416            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action)))
417           
418    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
419        """Sets soft and hard limits for a user quota."""
420        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
421       
422    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
423        """Sets soft and hard limits for a group quota on a specific printer."""
424        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
425
426    def deleteUser(self, user) :   
427        """Completely deletes an user from the Quota Storage."""
428        # TODO : What should we do if we delete the last person who used a given printer ?
429        # TODO : we can't reassign the last job to the previous one, because next user would be
430        # TODO : incorrectly charged (overcharged).
431        for q in [ 
432                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
433                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
434                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
435                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
436                  ] :
437            self.doModify(q)
438       
439    def deleteGroup(self, group) :   
440        """Completely deletes a group from the Quota Storage."""
441        for q in [
442                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
443                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
444                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
445                 ] : 
446            self.doModify(q)
447       
Note: See TracBrowser for help on using the browser.