Index: mysql.py
===================================================================
--- mysql.py	(revision 2307)
+++ mysql.py	(working copy)
@@ -10,6 +10,9 @@
 from MySQLdb.converters import conversions
 from MySQLdb.constants import FIELD_TYPE
 import types
+import threading
+from sets import Set
+from django.utils.synch import RWLock
 
 DatabaseError = Database.DatabaseError
 
@@ -49,12 +52,39 @@
 
 class DatabaseWrapper:
     def __init__(self):
-        self.connection = None
+        self.__connections = {}
+        self.__threads = Set()
+        self.__lock = RWLock()
         self.queries = []
 
-    def cursor(self):
-        from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD, DEBUG
-        if self.connection is None:
+    def _valid_connection(self, con):
+        try:
+            con.ping()
+            return True
+        except DatabaseError:
+            con.close() # close connection
+            return False
+    
+    def __connect(self):
+        id = threading.currentThread()
+        self.__lock.reader_enters()
+        try:
+            if (id in self.__connections) and (self._valid_connection(self.__connections[id])):
+                return self.__connections[id]
+        finally:
+            self.__lock.reader_leaves()
+            
+        self.__lock.writer_enters()
+        try:
+            # remove deadwood
+            dead = self.__threads - Set(threading.enumerate())
+            for name in dead:
+                self.__connections[name].close()
+                del self.__connections[name]
+            self.__threads -= dead
+        
+            # create new connection
+            from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD
             kwargs = {
                 'user': DATABASE_USER,
                 'db': DATABASE_NAME,
@@ -64,29 +94,61 @@
             }
             if DATABASE_PORT:
                 kwargs['port'] = DATABASE_PORT
-            self.connection = Database.connect(**kwargs)
-        cursor = self.connection.cursor()
-        if self.connection.get_server_info() >= '4.1':
+            connection = Database.connect(**kwargs)
+            self.__connections[id] = connection
+            self.__threads.add(id)
+	    return connection
+        finally:
+	    self.__lock.writer_leaves()
+    def cursor(self):
+        from django.conf.settings import DEBUG
+	connection = self.__connect()
+        cursor = connection.cursor()
+        if connection.get_server_info() >= '4.1':
             cursor.execute("SET NAMES utf8")
         if DEBUG:
             return base.CursorDebugWrapper(MysqlDebugWrapper(cursor), self)
         return cursor
 
     def commit(self):
-        self.connection.commit()
+        #self.connection.commit()
+	id = threading.currentThread()
+	self.__lock.reader_enters()
+	try:
+	    if id in self.__connections:
+	        self.__connections[id].commit()
+	finally:
+	    self.__lock.reader_leaves()
 
     def rollback(self):
-        if self.connection:
-            try:
-                self.connection.rollback()
-            except Database.NotSupportedError:
-                pass
+        #if self.connection:
+        #    try:
+        #        self.connection.rollback()
+        #    except Database.NotSupportedError:
+        #        pass
+        id = threading.currentThread()
+        self.__lock.reader_enters() 
+        try: 
+           if id in self.__connections: 
+                try: 
+                    self.__connections[id].rollback() 
+                except Database.NotSupportedError: 
+                    pass 
+        finally: 
+            self.__lock.reader_leaves() 
 
     def close(self):
-        if self.connection is not None:
-            self.connection.close()
-            self.connection = None
-
+        #if self.connection is not None:
+        #    self.connection.close()
+        #    self.connection = None
+        id = threading.currentThread() 
+        self.__lock.writer_enters() 
+        try: 
+            if id in self.__connections: 
+                self.__connections[id].close() 
+                del self.__connections[id] 
+        finally: 
+            self.__lock.writer_leaves() 
     def quote_name(self, name):
         if name.startswith("`") and name.endswith("`"):
             return name # Quoting once is enough.
