Last active
August 29, 2015 14:04
-
-
Save prakashpp/252dd0c34ba64702beec to your computer and use it in GitHub Desktop.
Remove postgres databases in bulk!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""How to run: | |
POSTGRES_DATABASE_URI="postgresql://postgres:postgres@localhost/postgres" python remove-postgres.py | |
""" | |
import urlparse | |
import os | |
import psycopg2 | |
from psycopg2.extensions import AsIs | |
result = urlparse.urlparse(os.environ['POSTGRES_DATABASE_URI']) | |
connection = psycopg2.connect( | |
database=result.path[1:], | |
user=result.username, | |
password=result.password, | |
host=result.hostname | |
) | |
connection.set_isolation_level(0) | |
cursor = connection.cursor() | |
cursor.execute("SELECT datname FROM pg_database WHERE datistemplate = false") | |
for db_name, in cursor.fetchall(): | |
if db_name.startswith("test_"): | |
try: | |
cursor.execute("DROP DATABASE %s", (AsIs(db_name), )) | |
print "Dropped database: %s" % db_name | |
except: | |
continue | |
connection.commit() | |
cursor.close() | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment