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

Revision 1041, 21.2 kB (checked in by jalet, 21 years ago)

Hey, it may work (edpykota --reset excepted) !

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