#!/bin/bash /usr/scripts/python.sh
# -*- encoding: utf-8 -*-

import psycopg2
import psycopg2.extras
import time

PG_STAT_REQ = "SELECT * FROM pg_stat_activity;"

def pg_stat_ended(curseur):
    """Fetch stat_activity from postgresql and check if
    all transactions active on first fetch is done before
    returning True.

    """
    curseur.execute(PG_STAT_REQ)
    data = curseur.fetchall()
    seuil = max([donnee['xact_start'] for donnee in data if donnee['xact_start'] is not None])
    while True and seuil:
        curseur.execute(PG_STAT_REQ)
        data = curseur.fetchall()
        front = min([donnee['xact_start'] for donnee in data if donnee['xact_start'] is not None])
        if front > seuil:
            break
        time.sleep(30)

if __name__ == "__main__":
    conn = psycopg2.connect(database='filtrage')
    conn.set_session(autocommit=True)
    curseur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    pg_stat_ended(curseur)
