]> git.saurik.com Git - cyql.git/commitdiff
Rename cyql.connect() to overtake connect() and make it support with.
authorJay Freeman (saurik) <saurik@saurik.com>
Wed, 2 Feb 2011 10:40:59 +0000 (10:40 +0000)
committerJay Freeman (saurik) <saurik@saurik.com>
Wed, 2 Feb 2011 10:41:29 +0000 (10:41 +0000)
__init__.py

index 90beb40190c3133c8ff7ef6cefb7301a275a60ec..53e8de3afd683f8dacc100a44da65edd7b3e7b76 100644 (file)
@@ -19,10 +19,32 @@ def one(values):
         assert len(values) == 1
         return values[0]
 
-class connection(object):
-    def __init__(self, driver):
-        self.driver = driver
-        self.driver.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
+class connect(object):
+    def __init__(self, dsn):
+        attempt = 0
+        while True:
+            try:
+                self.driver = psycopg2.connect(**dsn)
+                break
+            except psycopg2.OperationalError, e:
+                if attempt == 2:
+                    raise e
+                attempt = attempt + 1
+
+        try:
+            self.driver.set_client_encoding('UNICODE')
+            self.driver.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
+        except:
+            self.driver.close()
+
+    def close(self):
+        self.driver.close()
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.close()
 
     @contextmanager
     def cursor(self):
@@ -93,24 +115,6 @@ class connection(object):
     def has(self, statement):
         return one(self.one_('select exists(%s)' % (statement,)))
 
-@contextmanager
-def connect(dsn):
-    attempt = 0
-    while True:
-        try:
-            driver = psycopg2.connect(**dsn)
-            break
-        except psycopg2.OperationalError, e:
-            if attempt == 2:
-                raise e
-            attempt = attempt + 1
-
-    try:
-        driver.set_client_encoding('UNICODE')
-        yield connection(driver)
-    finally:
-        driver.close()
-
 def connected(dsn):
     def wrapped(method):
         def replaced(*args, **kw):