import subprocess

from . import UbacDatabase, parse_list


class UbacPostgresql(UbacDatabase):
    DEST_SUBDIR = 'postgresql'

    @classmethod
    def from_section(cls, section, remote):
        return cls(
            remote,
            list(parse_list(section['pg_dbs'])),
            freshness=int(section['check_since']),
            nb_to_keep=int(section['nb_to_keep']),
        )

    def list_available_dbs(self):
        cmd = [
            'psql', 'postgres', '-t', '-c',
            "SELECT datname FROM pg_database WHERE datistemplate = false"
        ]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        assert p.wait() == 0
        return p.stdout.read()

    def dump_db(self, dbname):
        cmd = ["pg_dump", "-x", "-O", dbname]
        for db in super(UbacPostgresql, self).dump_db(cmd):
            yield db
