import mysql.connector
import time
import os
import sys
import datetime
from ispyb.version import __version__
import ispyb.interface.connection

class ISPyBMySQLSPConnector(ispyb.interface.connection.IF):
  '''Provides a connector to an ISPyB MySQL/MariaDB database through stored procedures.
  '''

  def __init__(self, user=None, pw=None, host='localhost', db=None, port=3306):
    self.connect(user=user, pw=pw, host=host, db=db, port=port)

  def connect(self, user=None, pw=None, host='localhost', db=None, port=3306):
    self.disconnect()
    self.conn = mysql.connector.connect(user=user,
        password=pw,
        host=host,
        database=db,
        port=int(port))
    if self.conn is not None:
      self.conn.autocommit=True

  def __del__(self):
    self.disconnect()

  def disconnect(self):
    '''Release the connection previously created.'''
    if hasattr(self, 'conn') and self.conn is not None:
    	self.conn.close()
    self.conn = None

  def cursor(self, dictionary=False):
    if hasattr(self, 'conn') and self.conn is not None:
        return self.conn.cursor(dictionary=dictionary)
    raise Exception('No database connection')

  def get_data_area_package(self):
    return 'ispyb.sp'

  def call_sp_write(self, procname, args):
    cursor = self.cursor()
    result_args = cursor.callproc(procname=procname, args=args)
    cursor.close()
    if result_args is not None and len(result_args) > 0:
        return result_args[0]

  def call_sp_retrieve(self, procname, args):
    cursor = self.cursor(dictionary=True)
    cursor.callproc(procname=procname, args=args)
    result = []
    for recordset in cursor.stored_results():
        if isinstance(cursor, mysql.connector.cursor.MySQLCursorDict):
            for row in recordset:
                result.append(dict(list(zip(recordset.column_names,row))))
        else:
            result = recordset.fetchall()
#    cursor.nextset()
    cursor.close()
    return result

  def call_sf(self, funcname, args):
    cursor = self.cursor()
    cursor.execute(('select %s' % funcname) + ' (%s)' % ','.join(['%s'] * len(args)), args)
    result = None
    rs = cursor.fetchone()
    if len(rs) > 0:
        if isinstance(cursor, mysql.connector.cursor.MySQLCursorDict):
            result = iter(rs.items()).next()[1]
        else:
            try:
                result = int(rs[0])
            except:
                result = rs[0]
    cursor.close()
    return result

@@ -16,16 +16,33 @@
 nnector%0A
+import threading%0A
 import t
@@ -382,32 +382,65 @@
 ne, port=3306):%0A
+    self.lock = threading.Lock()%0A
     self.connect
@@ -1014,204 +1014,8 @@
 ne%0A%0A
-  def cursor(self, dictionary=False):%0A    if hasattr(self, 'conn') and self.conn is not None:%0A        return self.conn.cursor(dictionary=dictionary)%0A    raise Exception('No database connection')%0A%0A
   de
@@ -1103,32 +1103,56 @@
 rocname, args):%0A
+    with self.lock:%0A    
     cursor = sel
@@ -1145,32 +1145,37 @@
   cursor = self.
+conn.
 cursor()%0A    res
@@ -1163,24 +1163,28 @@
 nn.cursor()%0A
+    
     result_a
@@ -1231,24 +1231,28 @@
  args=args)%0A
+    
     cursor.c
@@ -1384,32 +1384,56 @@
 rocname, args):%0A
+    with self.lock:%0A    
     cursor = sel
@@ -1430,24 +1430,29 @@
 rsor = self.
+conn.
 cursor(dicti
@@ -1463,16 +1463,20 @@
 y=True)%0A
+    
     curs
@@ -1513,32 +1513,36 @@
  args=args)%0A    
+  
+  
 result = %5B%5D%0A    
@@ -1537,16 +1537,20 @@
 lt = %5B%5D%0A
+    
     for 
@@ -1587,16 +1587,20 @@
 ults():%0A
+    
         
@@ -1670,24 +1670,28 @@
             
+  
+  
 for row in r
@@ -1700,16 +1700,20 @@
 ordset:%0A
+    
         
@@ -1779,32 +1779,36 @@
 row))))%0A        
+    
 else:%0A          
@@ -1801,32 +1801,36 @@
 se:%0A            
+  
+  
 result = records
@@ -1847,30 +1847,12 @@
 l()%0A
-#
     
-cursor.nextset()%0A
     
@@ -1918,24 +1918,48 @@
 ame, args):%0A
+    with self.lock:%0A    
     cursor =
@@ -1964,16 +1964,21 @@
  = self.
+conn.
 cursor()
@@ -1974,24 +1974,28 @@
 nn.cursor()%0A
+    
     cursor.e
@@ -2070,24 +2070,28 @@
 gs)), args)%0A
+    
     result =
@@ -2096,16 +2096,20 @@
  = None%0A
+    
     rs =
@@ -2123,24 +2123,28 @@
 .fetchone()%0A
+    
     if len(r
@@ -2143,32 +2143,36 @@
 if len(rs) %3E 0:%0A
+    
         if isins
@@ -2218,32 +2218,36 @@
 SQLCursorDict):%0A
+    
             resu
@@ -2278,32 +2278,36 @@
 xt()%5B1%5D%0A        
+    
 else:%0A          
@@ -2312,13 +2312,21 @@
     
+    
 try:%0A
+    
     
@@ -2373,16 +2373,20 @@
     
+    
 except:%0A
     
@@ -2381,16 +2381,20 @@
 except:%0A
+    
         
@@ -2416,16 +2416,20 @@
 = rs%5B0%5D%0A
+    
     curs

Make thread safe