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

Revision 1068, 21.8 kB (checked in by jalet, 21 years ago)

Lots of small fixes with the help of PyChecker?

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