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

Revision 1051, 21.4 kB (checked in by jalet, 21 years ago)

Sorts by user / group name

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