Allow reduction of isolation level via config.
[shibboleth/sp.git] / odbc-store / odbc-store.cpp
index b9086bd..45f684e 100644 (file)
@@ -92,27 +92,24 @@ CREATE TABLE texts (
 
 namespace {
     static const XMLCh cleanupInterval[] =  UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);
+    static const XMLCh isolationLevel[] =   UNICODE_LITERAL_14(i,s,o,l,a,t,i,o,n,L,e,v,e,l);
     static const XMLCh ConnectionString[] = UNICODE_LITERAL_16(C,o,n,n,e,c,t,i,o,n,S,t,r,i,n,g);
 
     // RAII for ODBC handles
     struct ODBCConn {
-        ODBCConn(SQLHDBC conn) : handle(conn) {}
+        ODBCConn(SQLHDBC conn) : handle(conn), autoCommit(true) {}
         ~ODBCConn() {
-            SQLRETURN sr = SQLEndTran(SQL_HANDLE_DBC, handle, SQL_COMMIT);
+            SQLRETURN sr = SQL_SUCCESS;
+            if (!autoCommit)
+                sr = SQLSetConnectAttr(handle, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON, NULL);
             SQLDisconnect(handle);
             SQLFreeHandle(SQL_HANDLE_DBC,handle);
             if (!SQL_SUCCEEDED(sr))
-                throw IOException("Failed to commit connection.");
+                throw IOException("Failed to commit connection and return to auto-commit mode.");
         }
         operator SQLHDBC() {return handle;}
         SQLHDBC handle;
-    };
-
-    struct ODBCStatement {
-        ODBCStatement(SQLHSTMT statement) : handle(statement) {}
-        ~ODBCStatement() {SQLFreeHandle(SQL_HANDLE_STMT,handle);}
-        operator SQLHSTMT() {return handle;}
-        SQLHSTMT handle;
+        bool autoCommit;
     };
 
     class ODBCStorageService : public StorageService
@@ -189,6 +186,7 @@ namespace {
 
         SQLHENV m_henv;
         string m_connstring;
+        long m_isolation;
     };
 
     StorageService* ODBCStorageServiceFactory(const DOMElement* const & e)
@@ -257,7 +255,7 @@ namespace {
 };
 
 ODBCStorageService::ODBCStorageService(const DOMElement* e) : m_log(Category::getInstance("XMLTooling.StorageService")),
-   m_cleanupInterval(900), shutdown_wait(NULL), cleanup_thread(NULL), shutdown(false), m_henv(SQL_NULL_HANDLE)
+   m_cleanupInterval(900), shutdown_wait(NULL), cleanup_thread(NULL), shutdown(false), m_henv(SQL_NULL_HANDLE), m_isolation(SQL_TXN_SERIALIZABLE)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("ODBCStorageService");
@@ -269,6 +267,20 @@ ODBCStorageService::ODBCStorageService(const DOMElement* e) : m_log(Category::ge
     if (!m_cleanupInterval)
         m_cleanupInterval = 900;
 
+    auto_ptr_char iso(e ? e->getAttributeNS(NULL,isolationLevel) : NULL);
+    if (iso.get() && *iso.get()) {
+        if (!strcmp(iso.get(),"SERIALIZABLE"))
+            m_isolation = SQL_TXN_SERIALIZABLE;
+        else if (!strcmp(iso.get(),"REPEATABLE_READ"))
+            m_isolation = SQL_TXN_REPEATABLE_READ;
+        else if (!strcmp(iso.get(),"READ_COMMITTED"))
+            m_isolation = SQL_TXN_READ_COMMITTED;
+        else if (!strcmp(iso.get(),"READ_UNCOMMITTED"))
+            m_isolation = SQL_TXN_READ_UNCOMMITTED;
+        else
+            throw XMLToolingException("Unknown transaction isolationLevel property.");
+    }
+
     if (m_henv == SQL_NULL_HANDLE) {
         // Enable connection pooling.
         SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, (void*)SQL_CP_ONE_PER_HENV, 0);
@@ -361,12 +373,9 @@ SQLHDBC ODBCStorageService::getHDBC()
         throw IOException("ODBC StorageService failed to connect to database.");
     }
 
-    sr = SQLSetConnectAttr(handle, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, NULL);
-    if (!SQL_SUCCEEDED(sr))
-        throw IOException("ODBC StorageService failed to disable auto-commit mode.");
-    sr = SQLSetConnectAttr(handle, SQL_ATTR_TXN_ISOLATION, (SQLPOINTER)SQL_TXN_SERIALIZABLE, NULL);
+    sr = SQLSetConnectAttr(handle, SQL_ATTR_TXN_ISOLATION, (SQLPOINTER)m_isolation, NULL);
     if (!SQL_SUCCEEDED(sr))
-        throw IOException("ODBC StorageService failed to enable transaction isolation.");
+        throw IOException("ODBC StorageService failed to set transaction isolation level.");
 
     return handle;
 }
@@ -386,7 +395,7 @@ SQLHSTMT ODBCStorageService::getHSTMT(SQLHDBC conn)
 pair<int,int> ODBCStorageService::getVersion(SQLHDBC conn)
 {
     // Grab the version number from the database.
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
     
     SQLRETURN sr=SQLExecDirect(stmt, (SQLCHAR*)"SELECT major,minor FROM version", SQL_NTS);
     if (!SQL_SUCCEEDED(sr)) {
@@ -418,7 +427,7 @@ bool ODBCStorageService::createRow(const char* table, const char* context, const
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // Prepare and exectute insert statement.
     //char *scontext = makeSafeSQL(context);
@@ -432,10 +441,10 @@ bool ODBCStorageService::createRow(const char* table, const char* context, const
         log_error(stmt, SQL_HANDLE_STMT);
         throw IOException("ODBC StorageService failed to insert record.");
     }
-    m_log.debug("SQLPrepare() succeded. SQL: %s", q.c_str());
+    m_log.debug("SQLPrepare succeded. SQL: %s", q.c_str());
 
     SQLINTEGER b_ind = SQL_NTS;
-    sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, 0, 0, const_cast<char*>(context), &b_ind);
+    sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(context), &b_ind);
     if (!SQL_SUCCEEDED(sr)) {
         m_log.error("SQLBindParam failed (context = %s)", context);
         log_error(stmt, SQL_HANDLE_STMT);
@@ -443,7 +452,7 @@ bool ODBCStorageService::createRow(const char* table, const char* context, const
     }
     m_log.debug("SQLBindParam succeded (context = %s)", context);
 
-    sr = SQLBindParam(stmt, 2, SQL_C_CHAR, SQL_VARCHAR, 0, 0, const_cast<char*>(key), &b_ind);
+    sr = SQLBindParam(stmt, 2, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(key), &b_ind);
     if (!SQL_SUCCEEDED(sr)) {
         m_log.error("SQLBindParam failed (key = %s)", key);
         log_error(stmt, SQL_HANDLE_STMT);
@@ -451,7 +460,10 @@ bool ODBCStorageService::createRow(const char* table, const char* context, const
     }
     m_log.debug("SQLBindParam succeded (key = %s)", key);
 
-    sr = SQLBindParam(stmt, 3, SQL_C_CHAR, (strcmp(table, TEXT_TABLE)==0 ? SQL_LONGVARCHAR : SQL_VARCHAR), 0, 0, const_cast<char*>(value), &b_ind);
+    if (strcmp(table, TEXT_TABLE)==0)
+        sr = SQLBindParam(stmt, 3, SQL_C_CHAR, SQL_LONGVARCHAR, strlen(value), 0, const_cast<char*>(value), &b_ind);
+    else
+        sr = SQLBindParam(stmt, 3, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(value), &b_ind);
     if (!SQL_SUCCEEDED(sr)) {
         m_log.error("SQLBindParam failed (value = %s)", value);
         log_error(stmt, SQL_HANDLE_STMT);
@@ -471,6 +483,8 @@ bool ODBCStorageService::createRow(const char* table, const char* context, const
             return false;   // supposedly integrity violation?
         throw IOException("ODBC StorageService failed to insert record.");
     }
+
+    m_log.debug("SQLExecute of insert succeeded");
     return true;
 }
 
@@ -484,7 +498,7 @@ int ODBCStorageService::readRow(
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // Prepare and exectute select statement.
     char timebuf[32];
@@ -551,9 +565,13 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
     if (!value && !expiration)
         throw IOException("ODBC StorageService given invalid update instructions.");
 
-    // Get statement handle.
+    // Get statement handle. Disable auto-commit mode to wrap select + update.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLRETURN sr = SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, NULL);
+    if (!SQL_SUCCEEDED(sr))
+        throw IOException("ODBC StorageService failed to disable auto-commit mode.");
+    conn.autoCommit = false;
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // First, fetch the current version for later, which also ensures the record still exists.
     char timebuf[32];
@@ -561,11 +579,11 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
     char *scontext = makeSafeSQL(context);
     char *skey = makeSafeSQL(key);
     string q("SELECT version FROM ");
-    q = q + table + " WHERE context='" + scontext + "' AND id='" + key + "' AND expires > " + timebuf;
+    q = q + table + " WHERE context='" + scontext + "' AND id='" + skey + "' AND expires > " + timebuf;
 
     m_log.debug("SQL: %s", q.c_str());
 
-    SQLRETURN sr=SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
+    sr=SQLExecDirect(stmt, (SQLCHAR*)q.c_str(), SQL_NTS);
     if (!SQL_SUCCEEDED(sr)) {
         freeSafeSQL(scontext, context);
         freeSafeSQL(skey, key);
@@ -589,6 +607,9 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
         return -1;
     }
 
+    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+    stmt = getHSTMT(conn);
+
     // Prepare and exectute update statement.
     q = string("UPDATE ") + table + " SET ";
 
@@ -602,7 +623,7 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
         q = q + "expires = " + timebuf;
     }
 
-    q = q + " WHERE context='" + scontext + "' AND id='" + key + "'";
+    q = q + " WHERE context='" + scontext + "' AND id='" + skey + "'";
     freeSafeSQL(scontext, context);
     freeSafeSQL(skey, key);
 
@@ -612,11 +633,14 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
         log_error(stmt, SQL_HANDLE_STMT);
         throw IOException("ODBC StorageService failed to update record.");
     }
-    m_log.debug("SQLPrepare() succeded. SQL: %s", q.c_str());
+    m_log.debug("SQLPrepare succeded. SQL: %s", q.c_str());
 
     SQLINTEGER b_ind = SQL_NTS;
     if (value) {
-        sr = SQLBindParam(stmt, 1, SQL_C_CHAR, (strcmp(table, TEXT_TABLE)==0 ? SQL_LONGVARCHAR : SQL_VARCHAR), 0, 0, const_cast<char*>(value), &b_ind);
+        if (strcmp(table, TEXT_TABLE)==0)
+            sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_LONGVARCHAR, strlen(value), 0, const_cast<char*>(value), &b_ind);
+        else
+            sr = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, 255, 0, const_cast<char*>(value), &b_ind);
         if (!SQL_SUCCEEDED(sr)) {
             m_log.error("SQLBindParam failed (context = %s)", context);
             log_error(stmt, SQL_HANDLE_STMT);
@@ -634,6 +658,7 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
         throw IOException("ODBC StorageService failed to update record.");
     }
 
+    m_log.debug("SQLExecute of update succeeded");
     return ver + 1;
 }
 
@@ -645,7 +670,7 @@ bool ODBCStorageService::deleteRow(const char *table, const char *context, const
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // Prepare and execute delete statement.
     char *scontext = makeSafeSQL(context);
@@ -721,7 +746,7 @@ void ODBCStorageService::updateContext(const char *table, const char* context, t
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     char timebuf[32];
     timestampFromTime(expiration, timebuf);
@@ -752,7 +777,7 @@ void ODBCStorageService::reap(const char *table, const char* context)
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // Prepare and execute delete statement.
     char nowbuf[32];
@@ -784,7 +809,7 @@ void ODBCStorageService::deleteContext(const char *table, const char* context)
 
     // Get statement handle.
     ODBCConn conn(getHDBC());
-    ODBCStatement stmt(getHSTMT(conn));
+    SQLHSTMT stmt = getHSTMT(conn);
 
     // Prepare and execute delete statement.
     char *scontext = makeSafeSQL(context);