Created
November 30, 2011 16:18
-
-
Save erochest/1409659 to your computer and use it in GitHub Desktop.
Testing for existence of a Postgres database
This file contains hidden or 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
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