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

Revision 1113, 22.3 kB (checked in by jalet, 21 years ago)

1.14 is out !

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