Index: pykota/trunk/initscripts/README.postgresql
===================================================================
--- pykota/trunk/initscripts/README.postgresql (revision 900)
+++ pykota/trunk/initscripts/README.postgresql (revision 942)
@@ -69,5 +69,5 @@
         - Executes the pykota-upgrade-postgresql.sql script :  
         
-            pykota=# \i pykota-upgrade-postgresql.sql
+            pykota=# \i VERYOLDpykota-upgrade-postgresql.sql
             
         - Quit the psql frontend :    
@@ -76,5 +76,7 @@
             
         - Your PostgreSQL PyKota storage is now ready
-          for use.
+          for use for the next step, i.e. upgrade the
+          database schema to version 1.03. PLEASE
+          TAKE ANY STEPS DESCRIBED IN THE NEXT SECTION.
   
   If you already run PyKota v1.01 or above, you don't need
@@ -91,6 +93,6 @@
   
 * If you are already running PyKota 1.01 or 1.02 and want to upgrade to 
-  1.03, YOU HAVE TO RUN the upgrade-1.01-to-1.03.sh shell script.
+  1.03, YOU HAVE TO RUN the upgrade-from-before-1.03.py shell script.
   NOT LAUNCHING THIS SCRIPT WILL CAUSE PYKOTA TO STOP WORKING !
-  Please don't run this script if your existing version of PyKota is 
-  already 1.03 or higher.
+  PLEASE NEVER RUN THIS SCRIPT IF YOUR EXISTING VERSION OF PYKOTA IS 
+  ALREADY 1.03 OD HIGHER.
Index: pykota/trunk/initscripts/VERYOLDpykota-upgrade-postgresql.sql
===================================================================
--- pykota/trunk/initscripts/VERYOLDpykota-upgrade-postgresql.sql (revision 942)
+++ pykota/trunk/initscripts/VERYOLDpykota-upgrade-postgresql.sql (revision 942)
@@ -0,0 +1,56 @@
+--
+-- PyKota - Print Quotas for CUPS
+--
+-- (c) 2003 Jerome Alet <alet@librelogiciel.com>
+-- This program is free software; you can redistribute it and/or modify
+-- it under the terms of the GNU General Public License as published by
+-- the Free Software Foundation; either version 2 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+-- 
+-- You should have received a copy of the GNU General Public License
+-- along with this program; if not, write to the Free Software
+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+--
+-- $Id$
+--
+-- $Log$
+-- Revision 1.1  2003/04/17 21:33:16  jalet
+-- Version 1.03 is out.
+--
+--
+--
+--
+-- This script has to be used if you already
+-- have a pre-1.01 version of PyKota to upgrade
+-- your database schema. Don't use it if
+-- you've just installed PyKota, just use
+-- the normal script instead.
+--
+                        
+--                         
+-- WARNING : YOU NEED A RECENT VERSION OF POSTGRESQL FOR THE DROP COLUMN STATEMENT TO WORK !
+--
+
+--                         
+-- Modify the old database schema
+--
+ALTER TABLE grouppquota DROP COLUMN lifepagecounter;
+ALTER TABLE grouppquota DROP COLUMN pagecounter;
+
+--                         
+-- Create the groups/members relationship
+--
+CREATE TABLE groupsmembers(groupid INT4 REFERENCES groups(id),
+                           userid INT4 REFERENCES users(id),
+                           PRIMARY KEY (groupid, userid));
+                           
+--                        
+-- Set some ACLs                        
+--
+REVOKE ALL ON groupsmembers FROM public;                        
+GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON groupsmembers TO pykotaadmin;
Index: pykota/trunk/initscripts/README
===================================================================
--- pykota/trunk/initscripts/README (revision 889)
+++ pykota/trunk/initscripts/README (revision 942)
@@ -34,11 +34,11 @@
     if you want to use PostgreSQL as the Quota Storage Backend.
     
-  * pykota-upgrade-postgresql.sql :
+  * VERYOLDpykota-upgrade-postgresql.sql :
   
     This file upgrades the PostgreSQL Quota Storage Database schema
     from versions before 1.01 to version 1.01.
-    Don't use it if you already run a post-1.01 PyKota version.
+    DON'T USE IT IF YOU ALREADY RUN A POST-1.01 PyKota VERSION.
     
-  * upgrade-1.01-to-1.03.sh :
+  * upgrade-from-before-1.03.py :
   
     This shell script upgrades the PostgreSQL Quota Storage Database schema
@@ -49,3 +49,9 @@
     Server), without prompting for a password. Please read this script and 
     adapt it to your own configuration before running it. THIS IS IMPORTANT.
+    
+    THIS SCRIPT MAKES ANY REASONABLE CHECK TO ENSURE THAT YOUR DATAS WON'T 
+    BE LOST, AND ALSO DUMPS YOUR OLD DATABASE TO A TEXT FILE BEFORE DOING
+    ANYTHING. IT WAS TESTED SEVERAL TIMES AND SHOULDN'T PRODUCE ANY ERROR
+    EXCEPT ABOUT THE pykotaadmin and pykotauser POSTGRESQL USERS WHO 
+    ALREADY EXIST WHEN THE DATABASE SCHEMA IS UPGRADED. THIS IS NORMAL !
   
Index: pykota/trunk/initscripts/upgrade-from-before-1.03.py
===================================================================
--- pykota/trunk/initscripts/upgrade-from-before-1.03.py (revision 942)
+++ pykota/trunk/initscripts/upgrade-from-before-1.03.py (revision 942)
@@ -0,0 +1,171 @@
+#! /usr/bin/env python
+
+# PyKota Print Quota Warning sender
+#
+# PyKota - Print Quotas for CUPS
+#
+# (c) 2003 Jerome Alet <alet@librelogiciel.com>
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
+# THIS IS AN UPGRADE SCRIPT FOR OLD PYKOTA DATABASES TO THE 1.03 VERSION
+#
+
+import sys
+import os
+try :
+    import pg
+except ImportError :    
+    sys.stderr.write("The PyGreSQL Python module doesn't seem to be available. ABORTED.\n")
+    sys.exit(-1)
+
+def dump_old_database() :
+    """Dumps the existing PyKota database to a file, to avoir loosing data.
+    
+       Returns 1 if dump is successfull, 0 if it isn't.
+    """   
+    pipeinput = os.popen("pg_dump -C -D -N -U postgres -f pykota-dump.sql pykota")
+    dummy = pipeinput.read()
+    return (pipeinput.close() is None) or 0
+
+def create_new_database() :
+    """Creates the empty database."""
+    pipeinput = os.popen("psql -U postgres template1 <pykota-postgresql.sql")
+    dummy = pipeinput.read()
+    return (pipeinput.close() is None) or 0
+    
+def restore_original_database() :
+    """Creates the empty database."""
+    pipeinput = os.popen("psql -U postgres template1 <pykota-dump.sql")
+    dummy = pipeinput.read()
+    return (pipeinput.close() is None) or 0
+    
+def open_database(dbname="pykota") :
+    """Returns the database object or None if we can't connect to it."""
+    try :
+        pykotadb = pg.connect(dbname, user="postgres")
+    except pg.error, msg :     
+        sys.stderr.write("%s\n" % msg)
+        return 
+    else :    
+        return pykotadb
+        
+        
+def doQuote(field) :
+    """Quotes a field for use as a string in SQL queries."""
+    if type(field) == type(0) : # TODO : do something safer
+        typ = "decimal"
+    else :    
+        typ = "text"
+    return pg._quote(field, typ)
+        
+def main() :
+    """Does the work."""
+    
+    # First we make a dump of the old database
+    print "Dumping old database for safety...",
+    if not dump_old_database() :
+        sys.stderr.write("Error while dumping old database. ABORTED.\n")
+        return -1
+    print "Done."
+        
+    # Second we try to connect to it    
+    print "Extracting datas from old database...", 
+    db = open_database()
+    if db is None :
+        sys.stderr.write("Impossible to connect to old PyKota database. ABORTED.\nAre you sure you are upgrading an existing installation ?\n")
+        return -1
+    
+    # Third we extract datas
+    oldprinters = db.query("SELECT * FROM printers ORDER BY id;")
+    oldusers = db.query("SELECT * FROM users ORDER BY id;")
+    oldquotas = db.query("SELECT * FROM userpquota ORDER BY printerid, userid;")
+    
+    # Fourth close the database
+    db.close()
+    print "Done."
+    
+    # Fifth we delete the old database !
+    answer = raw_input("The old database will be deleted for the upgrade to take place.\nAre you sure you want to continue (y/N) ? ")
+    if answer[0:1].upper() != 'Y' :
+        sys.stderr.write("User wants to stop now ! ABORTED.\n")
+        return -1
+    db = open_database("template1")
+    if db is None :
+        sys.stderr.write("Impossible to connect to database template1. ABORTED.\nPlease report to your Database administrator.\n")
+        return -1
+    try :
+        db.query("DROP DATABASE pykota;")
+    except pg.error, msg :
+        sys.stderr.write("Impossible to delete old database. ABORTED.\n%s\n" % msg)
+        db.close()
+        return -1
+    else :    
+        db.close()
+        
+    # Sixth we create the new database
+    print "Creating the new database...",
+    if not create_new_database() :
+        sys.stderr.write("impossible to create new database ! ABORTED.\n")
+        return -1
+    print "Done."
+    
+    # Seventh we restore old data
+    print "Restoring old datas..."
+    db = open_database()
+    if db is None :
+        sys.stderr.write("Impossible to connect to new PyKota database. ABORTED.\nOld database will be restored if possible.")
+        print "An error occured, I'll try to restore the original database..."
+        if not restore_original_database() :
+            sys.stderr.write("Shit ! A double-error occured !!!\nPlease report problem to your database administrator.\n")
+            sys.stderr.write("And file a bug report to alet@librelogiciel.com\n")
+        else :    
+            print "Done."
+        return -1
+    db.query("BEGIN;")    
+    try :
+        newprinters = {}
+        for oldprinter in oldprinters.dictresult() :
+            db.query("INSERT INTO printers (printername) VALUES (%s);" % doQuote(oldprinter["printername"]))
+            newid = db.query("SELECT id FROM printers WHERE printername='%s';" % oldprinter["printername"]).dictresult()[0]["id"]
+            newprinters[oldprinter["id"]] = newid
+        newusers = {}    
+        for olduser in oldusers.dictresult() :    
+            db.query("INSERT INTO users (username) VALUES (%s);" % doQuote(olduser["username"]))
+            newid = db.query("SELECT id FROM users WHERE username='%s';" % olduser["username"]).dictresult()[0]["id"]
+            newusers[olduser["id"]] = newid
+        for oldquota in oldquotas.dictresult() :   
+            db.query("INSERT INTO userpquota (userid, printerid, pagecounter, lifepagecounter, softlimit, hardlimit, datelimit) VALUES (%s, %s, %s, %s, %s, %s, %s);" % 
+                                              (doQuote(newusers[oldquota["userid"]]) , doQuote(newprinters[oldquota["printerid"]]), doQuote(oldquota["pagecounter"]), doQuote(oldquota["lifepagecounter"]), doQuote(oldquota["softlimit"]), doQuote(oldquota["hardlimit"]), doQuote(oldquota["datelimit"])))
+    except pg.error, msg :    
+        sys.stderr.write("ERROR : %s\nABORTED.\n" % msg)
+        db.query("ROLLBACK;")
+        db.close()    
+        return -1
+    except :    
+        sys.stderr.write("Unknown error ! ABORTED.\n")
+        db.query("ROLLBACK;")
+        db.close()    
+        return -1
+    else :    
+        db.query("COMMIT;")
+        db.close()
+    print "Done."
+    print "NB : Last job on each printer was lost. This is normal !"
+    return 0
+    
+if __name__ == "__main__" :
+    sys.exit(main())
Index: pykota/trunk/initscripts/pykota-upgrade-postgresql.sql
===================================================================
--- pykota/trunk/initscripts/pykota-upgrade-postgresql.sql (revision 874)
+++  (revision )
@@ -1,55 +1,0 @@
---
--- PyKota - Print Quotas for CUPS
---
--- (c) 2003 Jerome Alet <alet@librelogiciel.com>
--- This program is free software; you can redistribute it and/or modify
--- it under the terms of the GNU General Public License as published by
--- the Free Software Foundation; either version 2 of the License, or
--- (at your option) any later version.
---
--- This program is distributed in the hope that it will be useful,
--- but WITHOUT ANY WARRANTY; without even the implied warranty of
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--- GNU General Public License for more details.
--- 
--- You should have received a copy of the GNU General Public License
--- along with this program; if not, write to the Free Software
--- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
---
--- $Id$
---
--- $Log$
--- Revision 1.1  2003/03/29 13:58:58  jalet
--- PostgreSQL upgrade script included now
---
---
---
--- This script has to be used if you already
--- have a pre-1.01 version of PyKota to upgrade
--- your database schema. Don't use it if
--- you've just installed PyKota, just use
--- the normal script instead.
---
-                        
---                         
--- WARNING : YOU NEED A RECENT VERSION OF POSTGRESQL FOR THE DROP COLUMN STATEMENT TO WORK !
---
-
---                         
--- Modify the old database schema
---
-ALTER TABLE grouppquota DROP COLUMN lifepagecounter;
-ALTER TABLE grouppquota DROP COLUMN pagecounter;
-
---                         
--- Create the groups/members relationship
---
-CREATE TABLE groupsmembers(groupid INT4 REFERENCES groups(id),
-                           userid INT4 REFERENCES users(id),
-                           PRIMARY KEY (groupid, userid));
-                           
---                        
--- Set some ACLs                        
---
-REVOKE ALL ON groupsmembers FROM public;                        
-GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON groupsmembers TO pykotaadmin;
Index: pykota/trunk/initscripts/upgrade-1.01-to-1.03.sh
===================================================================
--- pykota/trunk/initscripts/upgrade-1.01-to-1.03.sh (revision 900)
+++  (revision )
@@ -1,26 +1,0 @@
-#! /bin/sh
-# $Id$
-echo WARNING : This is dangerous !
-echo WARNING : You may loose your PyKota Quota Storage contents.
-echo WARNING : If unsure press Ctrl+C NOW TO STOP, else press ENTER TO PROCEED
-read
-
-echo This script does not work at all yet !
-echo Please be patient so that I can write a safe upgrade script
-echo of completely drop your existing database to start anew
-echo with this version of PyKota.
-
-#echo -n Update begins...
-#pg_dump -D -N -U postgres -f pykotadb-full.dump pykota >upgrade.messages 2>upgrade.errors
-#pg_dump -a -D -N -U postgres -f pykotadb.dump pykota >>upgrade.messages 2>>upgrade.errors
-#dropdb pykota >>upgrade.messages 2>>upgrade.errors
-#dropuser pykotaadmin >>upgrade.messages 2>>upgrade.errors
-#dropuser pykotauser >>upgrade.messages 2>>upgrade.errors
-#psql -U postgres template1 -f pykota-postgresql.sql >>upgrade.messages 2>>upgrade.errors
-#psql -U postgres pykota -f pykotadb.dump >>upgrade.messages 2>>upgrade.errors
-#echo
-#echo Done !
-#echo Check the files upgrade.messages and upgrade.errors to see if all is OK.
-#echo NOTICE messages are normal and expected. In case other message types
-#echo are found in upgrade.errors, please file a bug report and restore
-#echo your database from pykotadb-full.dump
