Exemple #1
0
    def handle(self, *args, **options):
        if not args:
            raise CommandError("No snapshot name specified")
        snapshot = args[0]
        snapshot_path = join(ROOT, snapshot)
        if exists(snapshot_path):
            raise CommandError(
                "Snapshot already exists: {0}".format(snapshot_path))

        running = ensure_stopped(verbose=True)

        # rsync must be in the system PATH
        cmd = ['rsync', '-aP', '--progress', CURRENT + '/.', snapshot_path]
        print(' '.join(cmd))
        if subprocess.call(cmd) > 0:
            raise CommandError("rsync failed")

        if options['activate']:
            print('Activating the snapshot.')
            activate_clone(snapshot)

        if running:
            ensure_started(verbose=True)
            print("Server restarted in background.")

        print()
        print("Snapshot done.")

        if not options['activate']:
            print()
            print("To activate:")
            print()
            print("    ./manage.py pg_activate", snapshot)
Exemple #2
0
def settings(settings_locals, start=True):
    """Register settings for PostgreSQL dev database

    This will set `DATABASES['default']` to the right values for the development
    environment, and start the database server if needed.

    Usage in `settings.py`::

        # Make sure to do this after DATABASES and any settings for this module
        import pgrunner
        pgrunner.settings(locals())

    :param settings_locals: locals() in settings.py
    :type settings_locals: dict
    """
    global ROOT, BIN
    ROOT = settings_locals.get('PGRUNNER_ROOT', None)
    if not ROOT:
        ROOT = DEFAULT_ROOT
    BIN = settings_locals.get('PGRUNNER_BIN', None)
    if BIN and not (os.path.isdir(BIN) and os.path.exists(bin_path('initdb'))):
        raise ImproperlyConfigured(
            "PGRUNNER_BIN setting incorrect: "
            "no folder or initdb not found in {0}".format(BIN))

    db_exists = os.path.exists(ROOT)

    from pgrunner.commands import get_port, ensure_started

    if not db_exists:
        print("PostgreSQL dev root does not exist:", ROOT)
        print("Not changing any settings.")
        print("Please run `./manage.py pg_init` first!")

    if db_exists:
        if not 'DATABASES' in settings_locals:
            settings_locals['DATABASES'] = {}

        settings_locals['DATABASES']['default'] = {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'django',
            'USER': '',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': get_port()
        }

    running_own_command = False
    if len(sys.argv) > 1 and sys.argv[0].endswith('manage.py') \
            and sys.argv[1].startswith('pg_'):
        running_own_command = True

    help = len(sys.argv) == 1 and sys.argv[0].endswith('manage.py')

    if db_exists and start and not running_own_command and not help:
        ensure_started(verbose=True)
Exemple #3
0
    def handle(self, *args, **options):
        if not os.path.isdir(ROOT):
            raise CommandError(
                'Root does not exist, maybe you meant pg_init? {0}'.format(ROOT))

        previous = current_clone()

        # Name for clone
        name = '{:%Y%m%d-%H%M%S}'.format(datetime.datetime.now())
        target = join(ROOT, name)

        cmd = [bin_path('initdb'), target]
        print(' '.join(cmd))
        if subprocess.call(cmd) > 0:
            raise CommandError('Error creating database in {0}'.format(target))

        for fname in ['pg_hba.conf', 'postgresql.conf']:
            src = os.path.join(DEFAULT, fname)
            dst = os.path.join(ROOT, name, fname)
            shutil.copyfile(src, dst)

        print("Stopping server")
        ensure_stopped()

        print("New database in {0}".format(target))
        activate_clone(name)

        print("Starting server to create database 'django'")
        ensure_started()

        print("Pausing 3s so that the database can start up")
        time.sleep(3)

        print("Creating database 'django'")
        cmd = [bin_path('createdb'), '-p', str(get_port()),
               '-h', '127.0.0.1', 'django']
        print(' '.join(cmd))
        if subprocess.call(cmd) > 0:
            raise CommandError('Error creating database')

        print("Blank database {} created and activated".format(name))
        print()
        print("To revert to your previous clone:")
        print()
        print("    ./manage.py pg_activate {}".format(previous))
Exemple #4
0
    def handle(self, *args, **options):
        if not args:
            self.list_snapshots()
            return

        snapshot = args[0]
        if snapshot == 'current':
            raise CommandError("Invalid snapshot name")

        if not exists(join(ROOT, snapshot)):
            self.list_snapshots()
            raise CommandError("Snapshot not found: {0}".format(snapshot))

        running = ensure_stopped(verbose=True)

        activate_clone(snapshot)

        if running:
            ensure_started(verbose=True)
            print("Server restarted in background.")

        print()
        print("Snapshot activated.")
Exemple #5
0
    def run_from_argv(self, argv):
        running = None

        pg_cmd = bin_path('pg_dump')
        port = get_port()
        if '--help' in argv:
            cmd = [pg_cmd, '--help']
        else:
            cmd = [pg_cmd, '-p', str(port), '-h', '127.0.0.1', 'django', '-O']
            cmd.extend(argv[2:])
            running = ensure_started()
        print(' '.join(cmd))
        subprocess.call(cmd)

        if not running and running is not None:
            ensure_stopped()