Skip to content

Instantly share code, notes, and snippets.

@prakashpp
Last active August 29, 2015 14:04
Show Gist options
  • Save prakashpp/252dd0c34ba64702beec to your computer and use it in GitHub Desktop.
Save prakashpp/252dd0c34ba64702beec to your computer and use it in GitHub Desktop.
Remove postgres databases in bulk!
"""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