Skip to content

Instantly share code, notes, and snippets.

@andreyfedoseev
Created July 28, 2011 15:53
Show Gist options
  • Save andreyfedoseev/1111802 to your computer and use it in GitHub Desktop.
Save andreyfedoseev/1111802 to your computer and use it in GitHub Desktop.
Django settings to enable separate database for specified git branches
# This snippet allows to use separate databases for specified git branches.
# These databases are created automatically as copies of the default database.
# It works only with PostgreSQL.
# If you use password to connect to your database you should add it to ~/.pgpass file!
# Add this to your local settings file.
from settings import *
import os, shlex, subprocess
BRANCH = None
for line in subprocess.Popen(shlex.split("/usr/local/bin/git branch"),
stdout=subprocess.PIPE).communicate()[0].split("\n"):
if line.startswith("*"):
BRANCH = line[2:]
break
# New databases are created only for these branches.
# For other branches the default database is used.
SEPARATE_DB_BRANCHES = [
"staging",
("awesome-branch", "awesome_database"),
]
for branch in SEPARATE_DB_BRANCHES:
if isinstance(branch, (tuple, list)):
branch, DB_NAME = branch
else:
DB_NAME = branch
if branch != BRANCH:
continue
DB_NAME = "%s_%s" % (DATABASES["default"]["NAME"], DB_NAME)
if DATABASES["default"]["NAME"] != DB_NAME:
# Get the list of existing databases
args = shlex.split("psql -U %(USER)s -A -c \"SELECT d.datname AS name FROM pg_catalog.pg_database d;\"" % DATABASES["default"])
p = subprocess.Popen(args, stdout=subprocess.PIPE)
existing_databases = p.communicate()[0].strip().split("\n")[:-1]
if DB_NAME not in existing_databases:
print "Creating database for branch", BRANCH
args = shlex.split("psql -U %(USER)s -c \"CREATE DATABASE %(DB_NAME)s WITH TEMPLATE %(ORIGINAL)s;\"" % \
dict(USER=DATABASES["default"]["USER"],
DB_NAME=DB_NAME,
ORIGINAL=DATABASES["default"]["NAME"]
)
)
subprocess.Popen(args).wait()
DATABASES["default"]["NAME"] = DB_NAME
break
@vishal-rathour-niit
Copy link

hi,
i have working a project to create separate database with exiting modal data and if users login first check credentials from my database than connect users database work next working . i got your code but i confused ho can i use your code so please give me a small program for give same work.

Thank You

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment