From 94c2cab695e6a9f0c44ea7ea385aa3e75199b41e Mon Sep 17 00:00:00 2001
From: Vincent Pelletier <vincent@nexedi.com>
Date: Mon, 26 Mar 2007 11:54:29 +0000
Subject: [PATCH] Implement MySQL connection pooling.

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@13633 20353a03-c40f-0410-a6d1-a30d3c3de9de
---
 product/ZMySQLDA/DA.py | 35 ++++++++++++++++++++++++++---------
 1 file changed, 26 insertions(+), 9 deletions(-)

diff --git a/product/ZMySQLDA/DA.py b/product/ZMySQLDA/DA.py
index 66f0b56fc3..fb5a3d3640 100644
--- a/product/ZMySQLDA/DA.py
+++ b/product/ZMySQLDA/DA.py
@@ -96,6 +96,7 @@ from Globals import HTMLFile
 from ImageFile import ImageFile
 from ExtensionClass import Base
 from DateTime import DateTime
+from thread import allocate_lock
 
 manage_addZMySQLConnectionForm=HTMLFile('connectionAdd',globals())
 
@@ -106,6 +107,10 @@ def manage_addZMySQLConnection(self, id, title,
     self._setObject(id, Connection(id, title, connection_string, check))
     if REQUEST is not None: return self.manage_main(self,REQUEST)
 
+# Connection Pool for connections to MySQL.
+database_connection_pool_lock = allocate_lock()
+database_connection_pool = {}
+
 class Connection(DABase.Connection):
     " "
     database_type=database_type
@@ -117,15 +122,27 @@ class Connection(DABase.Connection):
 
     def factory(self): return DB
 
-    def connect(self,s):
-        try: self._v_database_connection.close()
-        except: pass
-        self._v_connected=''
-        DB=self.factory()
-	## No try. DO.
-	self._v_database_connection=DB(s)
-        self._v_connected=DateTime()
-        return self
+    def connect(self, s):
+      try:
+        database_connection_pool_lock.acquire()
+        self._v_connected = ''
+        pool_key = self.getPhysicalPath()
+        connection = database_connection_pool.get(pool_key)
+        if connection is not None and connection.connection == s:
+          self._v_database_connection = connection
+        else:
+          if connection is not None:
+            connection.close()
+          DB = self.factory()
+          database_connection_pool[pool_key] = DB(s, self)
+          self._v_database_connection = database_connection_pool[pool_key]
+        # XXX If date is used as such, it can be wrong because an existing
+        # connection may be reused. But this is suposedly only used as a
+        # marker to know if connection was successfull.
+        self._v_connected = DateTime()
+      finally:
+          database_connection_pool_lock.release()
+      return self
 
     def sql_quote__(self, v, escapes={}):
         return self._v_database_connection.string_literal(v)
-- 
2.30.9