Index: pykota/trunk/pykota/storages/pgstorage.py
===================================================================
--- pykota/trunk/pykota/storages/pgstorage.py (revision 1024)
+++ pykota/trunk/pykota/storages/pgstorage.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.3  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.2  2003/06/12 21:09:57  jalet
 # wrongly placed code.
@@ -34,7 +37,6 @@
 #
 
-import fnmatch
-
 from pykota.storage import PyKotaStorageError
+from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
 
 try :
@@ -74,14 +76,27 @@
                 self.tool.logger.log_message("Database closed.", "debug")
         
-    def doQuery(self, query) :
-        """Does a query."""
-        if type(query) in (type([]), type(())) :
-            query = ";".join(query)
+    def beginTransaction(self) :    
+        """Starts a transaction."""
+        self.database.query("BEGIN;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction begins...", "debug")
+        
+    def commitTransaction(self) :    
+        """Commits a transaction."""
+        self.database.query("COMMIT;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction committed.", "debug")
+        
+    def rollbackTransaction(self) :     
+        """Rollbacks a transaction."""
+        self.database.query("ROLLBACK;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction aborted.", "debug")
+        
+    def doSearch(self, query) :
+        """Does a search query."""
         query = query.strip()    
         if not query.endswith(';') :    
             query += ';'
-        self.database.query("BEGIN;")
-        if self.debug :
-            self.tool.logger.log_message("Transaction began.", "debug")
         try :
             if self.debug :
@@ -89,14 +104,21 @@
             result = self.database.query(query)
         except pg.error, msg :    
-            self.database.query("ROLLBACK;")
-            if self.debug :
-                self.tool.logger.log_message("Transaction aborted.", "debug")
             raise PyKotaStorageError, msg
         else :    
-            self.database.query("COMMIT;")
+            if (result is not None) and (result.ntuples() > 0) : 
+                return result.dictresult()
+            
+    def doModify(self, query) :
+        """Does a (possibly multiple) modify query."""
+        query = query.strip()    
+        if not query.endswith(';') :    
+            query += ';'
+        try :
             if self.debug :
-                self.tool.logger.log_message("Transaction committed.", "debug")
-            return result
-        
+                self.tool.logger.log_message("QUERY : %s" % query, "debug")
+            result = self.database.query(query)
+        except pg.error, msg :    
+            raise PyKotaStorageError, msg
+            
     def doQuote(self, field) :
         """Quotes a field for use as a string in SQL queries."""
@@ -109,266 +131,194 @@
         return pg._quote(field, typ)
         
-    def doParseResult(self, result) :
-        """Returns the result as a list of Python mappings."""
-        if (result is not None) and (result.ntuples() > 0) :
-            return result.dictresult()
-            
+    def getUser(self, username) :    
+        """Extracts user information given its name."""
+        user = StorageUser(self, username)
+        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
+        if result :
+            fields = result[0]
+            user.ident = fields.get("id")
+            user.LimitBy = fields.get("limitby")
+            user.AccountBalance = fields.get("balance")
+            user.LifeTimePaid = fields.get("lifetimepaid")
+            user.Exists = 1
+        return user
+       
+    def getGroup(self, groupname) :    
+        """Extracts group information given its name."""
+        group = StorageGroup(self, groupname)
+        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
+        if result :
+            fields = result[0]
+            group.ident = fields.get("id")
+            group.LimitBy = fields.get("limitby")
+            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))
+            if result :
+                fields = result[0]
+                group.AccountBalance = fields.get("balance")
+                group.LifeTimePaid = fields.get("lifetimepaid")
+            group.Exists = 1
+        return group
+       
+    def getPrinter(self, printername) :        
+        """Extracts printer information given its name."""
+        printer = StoragePrinter(self, printername)
+        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
+        if result :
+            fields = result[0]
+            printer.ident = fields.get("id")
+            printer.PricePerJob = fields.get("priceperjob")
+            printer.PricePerPage = fields.get("priceperpage")
+            printer.LastJob = self.getPrinterLastJob(printer)
+            printer.Exists = 1
+        return printer    
+            
+    def getUserGroups(self, user) :        
+        """Returns the user's groups list."""
+        groups = []
+        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
+        if result :
+            for record in result :
+                groups.append(self.getGroup(record.get("groupname")))
+        return groups        
+        
+    def getGroupMembers(self, group) :        
+        """Returns the group's members list."""
+        groupmembers = []
+        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
+        if result :
+            for record in result :
+                user = StorageUser(self, record.get("username"))
+                user.ident = record.get("userid")
+                user.LimitBy = record.get("limitby")
+                user.AccountBalance = record.get("balance")
+                user.LifeTimePaid = record.get("lifetimepaid")
+                user.Exists = 1
+                groupmembers.append(user)
+        return groupmembers        
+        
+    def getUserPQuota(self, user, printer) :        
+        """Extracts a user print quota."""
+        userpquota = StorageUserPQuota(self, user, printer)
+        if user.Exists :
+            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)))
+            if result :
+                fields = result[0]
+                userpquota.ident = fields.get("id")
+                userpquota.PageCounter = fields.get("pagecounter")
+                userpquota.LifePageCounter = fields.get("lifepagecounter")
+                userpquota.SoftLimit = fields.get("softlimit")
+                userpquota.HardLimit = fields.get("hardlimit")
+                userpquota.DateLimit = fields.get("datelimit")
+                userpquota.Exists = 1
+        return userpquota
+        
+    def getGroupPQuota(self, group, printer) :        
+        """Extracts a group print quota."""
+        grouppquota = StorageGroupPQuota(self, group, printer)
+        if group.Exists :
+            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
+            if result :
+                fields = result[0]
+                grouppquota.ident = fields.get("id")
+                grouppquota.SoftLimit = fields.get("softlimit")
+                grouppquota.HardLimit = fields.get("hardlimit")
+                grouppquota.DateLimit = fields.get("datelimit")
+                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)))
+                if result :
+                    fields = result[0]
+                    grouppquota.PageCounter = fields.get("pagecounter")
+                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
+                grouppquota.Exists = 1
+        return grouppquota
+        
+    def getPrinterLastJob(self, printer) :        
+        """Extracts a printer's last job information."""
+        lastjob = StorageLastJob(self, printer)
+        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))
+        if result :
+            fields = result[0]
+            lastjob.ident = fields.get("id")
+            lastjob.JobId = fields.get("jobid")
+            lastjob.User = self.getUser(fields.get("username"))
+            lastjob.PrinterPageCounter = fields.get("pagecounter")
+            lastjob.JobSize = fields.get("jobsize")
+            lastjob.JobAction = fields.get("action")
+            lastjob.JobDate = fields.get("jobdate")
+            lastjob.Exists = 1
+        return lastjob
+        
     def getMatchingPrinters(self, printerpattern) :
-        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
-        printerslist = []
+        """Returns the list of all printers for which name matches a certain pattern."""
+        printers = []
         # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
         # but we don't because other storages semantics may be different, so every
         # storage should use fnmatch to match patterns and be storage agnostic
-        result = self.doQuery("SELECT id, printername FROM printers")
-        result = self.doParseResult(result)
-        if result is not None :
-            for printer in result :
-                if fnmatch.fnmatchcase(printer["printername"], printerpattern) :
-                    printerslist.append((printer["id"], printer["printername"]))
-        return printerslist        
-            
-    def getPrinterId(self, printername) :        
-        """Returns a printerid given a printername."""
-        result = self.doQuery("SELECT id FROM printers WHERE printername=%s" % self.doQuote(printername))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found    
-            return
-            
-    def getPrinterPrices(self, printerid) :        
-        """Returns a printer prices per page and per job given a printerid."""
-        result = self.doQuery("SELECT priceperpage, priceperjob FROM printers WHERE id=%s" % self.doQuote(printerid))
-        try :
-            printerprices = self.doParseResult(result)[0]
-            return (printerprices["priceperpage"], printerprices["priceperjob"])
-        except TypeError :      # Not found    
-            return
-            
-    def setPrinterPrices(self, printerid, perpage, perjob) :
-        """Sets prices per job and per page for a given printer."""
-        self.doQuery("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(perpage), self.doQuote(perjob), self.doQuote(printerid)))
-    
-    def getUserId(self, username) :
-        """Returns a userid given a username."""
-        result = self.doQuery("SELECT id FROM users WHERE username=%s" % self.doQuote(username))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found
-            return
-            
-    def getGroupId(self, groupname) :
-        """Returns a groupid given a grupname."""
-        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found
-            return
-            
-    def getJobHistoryId(self, jobid, userid, printerid) :        
-        """Returns the history line's id given a (jobid, userid, printerid)."""
-        result = self.doQuery("SELECT id FROM jobhistory WHERE jobid=%s AND userid=%s AND printerid=%s" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid)))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found    
-            return
-            
-    def getPrinterUsers(self, printerid) :        
-        """Returns the list of userids and usernames which uses a given printer."""
-        result = self.doQuery("SELECT DISTINCT id, username FROM users WHERE id IN (SELECT userid FROM userpquota WHERE printerid=%s) ORDER BY username" % self.doQuote(printerid))
-        result = self.doParseResult(result)
-        if result is None :
-            return []
-        else :    
-            return [(record["id"], record["username"]) for record in result]
-        
-    def getPrinterGroups(self, printerid) :        
-        """Returns the list of groups which uses a given printer."""
-        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s)" % self.doQuote(printerid))
-        result = self.doParseResult(result)
-        if result is None :
-            return []
-        else :    
-            return [(record["id"], record["groupname"]) for record in result]
-        
-    def getGroupMembersNames(self, groupname) :        
-        """Returns the list of user's names which are member of this group."""
-        groupid = self.getGroupId(groupname)
-        if groupid is None :
-            return []
-        else :
-            result = self.doQuery("SELECT DISTINCT username FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
-            return [record["username"] for record in (self.doParseResult(result) or [])]
-        
-    def getUserGroupsNames(self, userid) :        
-        """Returns the list of groups' names the user is a member of."""
-        result = self.doQuery("SELECT DISTINCT groupname FROM groups WHERE id IN (SELECT groupid FROM groupsmembers WHERE userid=%s)" % self.doQuote(userid))
-        return [record["groupname"] for record in (self.doParseResult(result) or [])]
+        result = self.doSearch("SELECT * FROM printers")
+        if result :
+            for record in result :
+                if self.tool.matchString(record["printername"], [ printerpattern ]) :
+                    printer = StoragePrinter(self, record["printername"])
+                    printer.ident = record.get("id")
+                    printer.PricePerJob = record.get("priceperjob")
+                    printer.PricePerPage = record.get("priceperpage")
+                    printer.LastJob = self.getPrinterLastJob(printer)
+                    printer.Exists = 1
+                    printers.append(printer)
+        return printers        
+        
+    def getPrinterUsersAndQuotas(self, printer, names=None) :        
+        """Returns the list of users who uses a given printer, along with their quotas."""
+        usersandquotas = []
+        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))
+        if result :
+            for record in result :
+                user = StorageUser(self, record.get("username"))
+                if (names is None) or self.tool.matchString(user.Name, names) :
+                    user.ident = record.get("uid")
+                    user.LimitBy = record.get("limitby")
+                    user.AccountBalance = record.get("balance")
+                    user.LifeTimePaid = record.get("lifetimepaid")
+                    user.Exists = 1
+                    userpquota = StorageUserPQuota(self, user, printer)
+                    userpquota.ident = record.get("id")
+                    userpquota.PageCounter = record.get("pagecounter")
+                    userpquota.LifePageCounter = record.get("lifepagecounter")
+                    userpquota.SoftLimit = record.get("softlimit")
+                    userpquota.HardLimit = record.get("hardlimit")
+                    userpquota.DateLimit = record.get("datelimit")
+                    userpquota.Exists = 1
+                    usersandquotas.append((user, userpquota))
+        return usersandquotas
+                
+    def getPrinterGroupsAndQuotas(self, printer, names=None) :        
+        """Returns the list of groups which uses a given printer, along with their quotas."""
+        groupsandquotas = []
+        result = self.doSearch("SELECT groupname FROM groups JOIN grouppquota ON groups.id=grouppquota.groupid AND printerid=%s" % self.doQuote(printer.ident))
+        if result :
+            for record in result :
+                group = self.getGroup(record.get("groupname"))
+                if (names is None) or self.tool.matchString(group.Name, names) :
+                    grouppquota = self.getGroupPQuota(group, printer)
+                    groupsandquotas.append((group, grouppquota))
+        return groupsandquotas
         
     def addPrinter(self, printername) :        
-        """Adds a printer to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
-        return self.getPrinterId(printername)
-        
-    def addUser(self, username) :        
+        """Adds a printer to the quota storage, returns it."""
+        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
+        return self.getPrinter(printername)
+        
+    def addUser(self, user) :        
         """Adds a user to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
-        return self.getUserId(username)
-        
-    def addGroup(self, groupname) :        
+        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)))
+        return self.getUser(user.Name)
+        
+    def addGroup(self, group) :        
         """Adds a group to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
-        return self.getGroupId(groupname)
-        
-    def addUserPQuota(self, username, printerid) :
-        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
-        userid = self.getUserId(username)     
-        if userid is None :    
-            userid = self.addUser(username)
-        uqexists = (self.getUserPQuota(userid, printerid) is not None)    
-        if not uqexists : 
-            self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
-        return (userid, printerid)
-        
-    def addGroupPQuota(self, groupname, printerid) :
-        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
-        groupid = self.getGroupId(groupname)     
-        if groupid is None :    
-            groupid = self.addGroup(groupname)
-        gqexists = (self.getGroupPQuota(groupid, printerid) is not None)    
-        if not gqexists : 
-            self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(printerid)))
-        return (groupid, printerid)
-        
-    def increaseUserBalance(self, userid, amount) :    
-        """Increases (or decreases) an user's account balance by a given amount."""
-        self.doQuery("UPDATE users SET balance=balance+(%s), lifetimepaid=lifetimepaid+(%s) WHERE id=%s" % (self.doQuote(amount), self.doQuote(amount), self.doQuote(userid)))
-        
-    def getUserBalance(self, userid) :    
-        """Returns the current account balance for a given user."""
-        result = self.doQuery("SELECT balance, lifetimepaid FROM users WHERE id=%s" % self.doQuote(userid))
-        try :
-            result = self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        else :    
-            return (result["balance"], result["lifetimepaid"])
-        
-    def getGroupBalance(self, groupid) :    
-        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
-        result = self.doQuery("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id in (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
-        try :
-            result = self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        else :    
-            return (result["balance"], result["lifetimepaid"])
-        
-    def getUserLimitBy(self, userid) :    
-        """Returns the way in which user printing is limited."""
-        result = self.doQuery("SELECT limitby FROM users WHERE id=%s" % self.doQuote(userid))
-        try :
-            return self.doParseResult(result)[0]["limitby"]
-        except TypeError :      # Not found    
-            return
-        
-    def getGroupLimitBy(self, groupid) :    
-        """Returns the way in which group printing is limited."""
-        result = self.doQuery("SELECT limitby FROM groups WHERE id=%s" % self.doQuote(groupid))
-        try :
-            return self.doParseResult(result)[0]["limitby"]
-        except TypeError :      # Not found    
-            return
-        
-    def setUserBalance(self, userid, balance) :    
-        """Sets the account balance for a given user to a fixed value."""
-        (current, lifetimepaid) = self.getUserBalance(userid)
-        difference = balance - current
-        self.increaseUserBalance(userid, difference)
-        
-    def limitUserBy(self, userid, limitby) :    
-        """Limits a given user based either on print quota or on account balance."""
-        self.doQuery("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(userid)))
-        
-    def limitGroupBy(self, groupid, limitby) :    
-        """Limits a given group based either on print quota or on sum of its users' account balances."""
-        self.doQuery("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(groupid)))
-        
-    def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
-        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
-        self.doQuery("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userid), self.doQuote(printerid)))
-        
-    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
-        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
-        self.doQuery("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(groupid), self.doQuote(printerid)))
-        
-    def resetUserPQuota(self, userid, printerid) :    
-        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
-        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
-        
-    def resetGroupPQuota(self, groupid, printerid) :    
-        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
-        self.doQuery("UPDATE grouppquota SET pagecounter=0, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
-        
-    def updateUserPQuota(self, userid, printerid, pagecount) :
-        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
-        jobprice = self.computePrinterJobPrice(printerid, pagecount)
-        queries = []    
-        queries.append("UPDATE userpquota SET lifepagecounter=lifepagecounter+(%s), pagecounter=pagecounter+(%s) WHERE userid=%s AND printerid=%s" % (self.doQuote(pagecount), self.doQuote(pagecount), self.doQuote(userid), self.doQuote(printerid)))
-        queries.append("UPDATE users SET balance=balance-(%s) WHERE id=%s" % (self.doQuote(jobprice), self.doQuote(userid)))
-        self.doQuery(queries)
-        
-    def getUserPQuota(self, userid, printerid) :
-        """Returns the Print Quota information for a given (userid, printerid)."""
-        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
-        try :
-            return self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        
-    def getGroupPQuota(self, groupid, printerid) :
-        """Returns the Print Quota information for a given (groupid, printerid)."""
-        result = self.doQuery("SELECT softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
-        try :
-            grouppquota = self.doParseResult(result)[0]
-        except TypeError :    
-            return
-        else :    
-            result = self.doQuery("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(printerid), self.doQuote(groupid)))
-            try :
-                result = self.doParseResult(result)[0]
-            except TypeError :      # Not found    
-                return
-            else :    
-                grouppquota.update({"lifepagecounter": result["lifepagecounter"], "pagecounter": result["pagecounter"]})
-                return grouppquota
-        
-    def setUserDateLimit(self, userid, printerid, datelimit) :
-        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
-        self.doQuery("UPDATE userpquota SET datelimit=%s::TIMESTAMP WHERE userid=%s AND printerid=%s" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(userid), self.doQuote(printerid)))
-        
-    def setGroupDateLimit(self, groupid, printerid, datelimit) :
-        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
-        self.doQuery("UPDATE grouppquota SET datelimit=%s::TIMESTAMP WHERE groupid=%s AND printerid=%s" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(groupid), self.doQuote(printerid)))
-        
-    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
-        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
-        self.doQuery("INSERT INTO jobhistory (jobid, userid, printerid, pagecounter, action, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
-        return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
-    
-    def updateJobSizeInHistory(self, historyid, jobsize) :
-        """Updates a job size in the history given the history line's id."""
-        self.doQuery("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(historyid)))
-    
-    def getPrinterPageCounter(self, printerid) :
-        """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
-        result = self.doQuery("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printerid))
-        try :
-            return self.doParseResult(result)[0]
-        except TypeError :      # Not found
-            return
-        
-    def addUserToGroup(self, userid, groupid) :    
+        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
+        return self.getGroup(group.Name)
+
+    def addUserToGroup(self, user, group) :    
         """Adds an user to a group."""
-        result = self.doQuery("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(groupid), self.doQuote(userid)))
+        result = self.doModify("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
         try :
             mexists = self.doParseResult(result)[0]["mexists"]
@@ -376,32 +326,86 @@
             mexists = 0
         if not mexists :    
-            self.doQuery("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(userid)))
-        
-    def deleteUser(self, userid) :    
+            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
+            
+    def addUserPQuota(self, user, printer) :
+        """Initializes a user print quota on a printer."""
+        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
+        return self.getUserPQuota(user, printer)
+        
+    def addGroupPQuota(self, group, printer) :
+        """Initializes a group print quota on a printer."""
+        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
+        return self.getGroupPQuota(group, printer)
+        
+    def writePrinterPrices(self, printer) :    
+        """Write the printer's prices back into the storage."""
+        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE printerid=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
+        
+    def writeUserLimitBy(self, user, limitby) :    
+        """Sets the user's limiting factor."""
+        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
+        
+    def writeGroupLimitBy(self, group, limitby) :    
+        """Sets the group's limiting factor."""
+        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
+        
+    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :    
+        """Sets the date limit permanently for a user print quota."""
+        self.doModify("UPDATE userpquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
+            
+    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :    
+        """Sets the date limit permanently for a group print quota."""
+        self.doModify("UPDATE grouppquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
+        
+    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :    
+       """Sets the new page counters permanently for a user print quota."""
+       self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
+       
+    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :    
+       """Sets the new account balance and eventually new lifetime paid."""
+       if newlifetimepaid is not None :
+           self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
+       else :    
+           self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
+            
+    def writeLastJobSize(self, lastjob, jobsize) :        
+        """Sets the last job's size permanently."""
+        self.doModify("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(lastjob.ident)))
+        
+    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :    
+        """Adds a job in a printer's history."""
+        if jobsize is not None :
+            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)))
+        else :    
+            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)))
+            
+    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a user quota."""
+        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
+        
+    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
+        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
+
+    def deleteUser(self, user) :    
         """Completely deletes an user from the Quota Storage."""
-        queries = []
-        queries.append("DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM userpquota WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM users WHERE id=%s" % self.doQuote(userid))
         # TODO : What should we do if we delete the last person who used a given printer ?
-        self.doQuery(queries)
-        
-    def deleteGroup(self, groupid) :    
-        """Completely deletes an user from the Quota Storage."""
-        queries = []
-        queries.append("DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(groupid))
-        queries.append("DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(groupid))
-        queries.append("DELETE FROM groups WHERE id=%s" % self.doQuote(groupid))
-        self.doQuery(queries)
-        
-    def computePrinterJobPrice(self, printerid, jobsize) :    
-        """Returns the price for a job on a given printer."""
-        # TODO : create a base class with things like this
-        prices = self.getPrinterPrices(printerid)
-        if prices is None :
-            perpage = perjob = 0.0
-        else :    
-            (perpage, perjob) = prices
-        return perjob + (perpage * jobsize)
-        
+        # TODO : we can't reassign the last job to the previous one, because next user would be
+        # TODO : incorrectly charged (overcharged).
+        for q in [ 
+                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
+                  ] :
+            self.doModify(q)
+        
+    def deleteGroup(self, group) :    
+        """Completely deletes a group from the Quota Storage."""
+        for q in [
+                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
+                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
+                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
+                 ] :  
+            self.doModify(q)
+        
