#!usr/bin/python3

import psycopg2
from psycopg2.extras import *
import time, datetime

def do_transfert(bdd, newbdd):
    try:
        db      = psycopg2.connect("dbname='"+ bdd['base'] +"' user='" + bdd['login'] +"' host='" + bdd['host'] +"' password='" + bdd['mdp'] +"'")
        newdb   = psycopg2.connect("dbname='"+ newbdd['base'] +"' user='" + newbdd['login'] +"' host='" + newbdd['host'] +"' password='" + newbdd['mdp'] +"'")
        cur     = db.cursor()
        curdata = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        newcur  = newdb.cursor()
    except:
        raise
    
    error = 0
    for schema in bdd['schemanames']:
        print("\n##### SCHEMA %s #####" % schema)
        cur.execute("select tablename from pg_tables where schemaname ='%s'" % schema)
        tables = cur.fetchall()
        
        for table in tables:
            
            start = time.clock()
            print("\t##### TABLE %s #####" % table[0])
            try:
                cur.execute("Select c.column_name, c.data_type from information_schema.columns AS c \
                                WHERE c.table_schema = '%s' AND c.table_name = '%s' order by c.ordinal_position " % (schema, table[0]))
            except:
                error += 1
                raise
           
            columns = cur.fetchall()
            vNbFields = len(columns)
            req = "Select "
            i = 0
            for column in columns:
                req += column[0]
                i += 1
                if i < vNbFields: req += ", "
            
            req += " FROM " + schema + "." + table[0] + ""
            
            try:
               curdata.execute("Select * from " + schema + "." + table[0] + "")
            except:
                raise
            
            donnees = curdata.fetchall()
            print("\tIl y a %d enregistrements dans la table" % (len(donnees)))
            print("\tTransfert des données vers la nouvelle base")
            for row in donnees:
                req = "INSERT INTO " + schema + "." + table[0] + "("
                i = 0
                for column in columns:
                    req += column[0]
                    i += 1
                    if i < vNbFields:
                       req += ", "
                req +=") VALUES("
                i = 0
                for champs in row:
                    if isinstance(champs, (int, float)):
                        req += "%s" % champs
                    elif isinstance(champs, str):
                        req += "'%s'" % champs.replace("'", "''")
                    elif isinstance(champs, datetime.date):
                        req += "'%s'" % champs
                    elif champs is None:
                        req += "Null"
                    else:
                        req += "%s" % champs
                    i += 1
                    if i < vNbFields:
                        req += ", "
                        
                req +=")"
                #print(req)
                newcur.execute(req)
                newdb.commit()
            
                
            
            stop = time.clock()
            print("\tTable copiée en %s minutes\n" % str(stop-start))
            
if __name__ == '__main__' :
    #login = input("Entrez le login de connexion de la base postgres a generer en classes storm : ")
    #mdp = input("Entrez le mot de passe de cet utilisateur postgres : ")
    bdd = {}
    bdd['host'] = input("Entrez l'hote de la base a generer ; ")
    bdd['port'] = input("Entrez le port a utiliser : ")
    bdd['base'] = input("Entrez le nom de la base de donnee a copier de ce serveur : ")
    bdd['login'] = input("Entrez le nom d'utilisateur")
    bdd['mdp'] = input("Entrez le mot de passe")
    schema = ""
    bdd['schemanames'] = []
    
    newbdd = {}
    newbdd['host'] = input("Entrez l'hôte de la nouvelle bdd : ")
    newbdd['port'] = input("Entrez le port de la nouvelle bdd : ")
    newbdd['login'] = input("Entrez le login de la nouvelle bdd : ")
    newbdd['mdp'] = input("Entrez le mdp de la nouvelle bdd : ")
    newbdd['base'] = input("Entrez le nom de la bdd a copier : ")
    nb = 1
    
    while schema != "0" :
        schema = input("Entrez le nom du schema a copier n " + str(nb) + " (ou entrez le chiffre 0 pour commencer la copie des données) : ")
        nb += 1
        if schema != "0" :
            bdd['schemanames'].append(schema)
    do_transfert(bdd, newbdd)
    
    
    
    