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

Revision 1084, 21.9 kB (checked in by jalet, 21 years ago)

Wrong documentation strings

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