Source

fabulator / src / fabulator / core / db / pgsql.py

Full commit
"""
    mysql management functions
"""
import datetime
import time

from fabric.api import run

from base import BaseDB

class PgSQL(BaseDB):
    """Base class for database"""

    def create_database(self, database_name=None):
        """create database"""
        conf = self.conf.copy()
        if database_name:
            conf["db"] = database_name

        if "host" in conf:
            run("createdb %(db)s --username %(user)s --host %(host)s --port %(port)s" % conf)
        else:
            run("createdb %(db)s --username %(user)s" % conf)

    def backup(self, filename="plop"):
        """Backups your mysql database"""
        date = datetime.datetime.now()

        conf['backup_fname'] = "%s/backup-%s-%d-%d-%d-%s.sql" % \
            (self.conf.get('backup'), self.conf.get('db'), date.day, date.month,
             date.year, time.time())
        run("mkdir -p %(backup)s" % self.conf)
        if "host" in conf:
            run("pg_dump --host %(host)s --port %(port)s --username %(user)s %(db)s > %(backup_fname)s" % self.conf)
        else:
            run("pg_dump --username %(user)s %(db)s > %(backup_fname)s" % self.conf)

    def migrate(self, revision, sqlfile):
        """applies sql file to the database"""
        if not isinstance(sqlfile, list):
            sqlfile = [sqlfile]
        conf = self.conf.copy()

        for sql in sqlfile:
            conf["sqlfile"] = sql
            if "host" in conf:
                run("psql --host %(host)s --port %(port)s --username %(user)s %(db)s < %(sqlfile)s" % conf)
            else:
                run("psql --username %(user)s %(db)s < %(sqlfile)s" % conf)
            
        
    def populate(self, sqlfile):
        """inserts data into your db"""
        conf = self.conf.copy()
        conf["sqlfile"] = filename
        if "host" in conf:
            run("psql --host %(host)s --port %(port)s --username %(user)s < %(sqlfile)s" % conf)
        else:
            run("psql --username %(user)s < %(sqlfile)s" % conf)

    def fallback(self, revision, sqlfile):
        """fallback to an old revision"""
        #well, we have to drop db, create db, populate from
        self.drop_database()
        self.create_database()
        self.populate(sqlfile)

    def drop_table(self, table_name):
        """Drop a table"""
        conf = self.conf.copy()
        conf["table"] = table_name
        if "host" in conf:
            run("DROP TABLE %(table)s | pgsql --host %(host)s --port %(port)s --username %(user)s" % conf)
        else:
            run("DROP TABLE %(table)s | pgsql --username %(user)s" % conf)

    def drop_database(self, database_name=None):
        conf = self.conf.copy()
        if database_name:
            conf["db"] = database_name
        if "host" in conf:
            run("dropdb --username %(user)s --host %(host)s %(db)s" % conf)
        else:
            run("dropdb --username %(user)s %(db)s" % conf)