Skip to content

Instantly share code, notes, and snippets.

@erochest
Created November 30, 2011 16:18
Show Gist options
  • Save erochest/1409659 to your computer and use it in GitHub Desktop.
Save erochest/1409659 to your computer and use it in GitHub Desktop.
Testing for existence of a Postgres database
from contextlib import closing
def db_exists(cxn, db_name):
"""\
This takes a connection to a Postgres object and db name and tests whether it
exists or not.
"""
with closing(cxn.cursor()) as c:
c.execute('SELECT COUNT(*) FROM pg_database WHERE datname=%s;', [db_name])
(count,) = c.fetchone()
return count > 0
# For more information on the `with` statement and closing function, see these
# pages:
#
# * http://effbot.org/zone/python-with-statement.htm
# * http://www.python.org/dev/peps/pep-0343/
# * http://docs.python.org/release/2.6.7/library/contextlib.html#contextlib.closing
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment