VS10 solution files, convert from NULL macro to nullptr.
[shibboleth/sp.git] / odbc-store / odbc-store.cpp
index 11405e4..0e9c089 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2007 Internet2
+ *  Copyright 2001-2010 Internet2
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
 /**
  * odbc-store.cpp
  *
- * Storage Service using ODBC
+ * Storage Service using ODBC.
  */
 
 #if defined (_MSC_VER) || defined(__BORLANDC__)
@@ -39,6 +39,7 @@
 
 #include <xercesc/util/XMLUniDefs.hpp>
 #include <xmltooling/logging.h>
+#include <xmltooling/unicode.h>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/StorageService.h>
@@ -67,8 +68,8 @@ using namespace std;
 
 /* table definitions
 CREATE TABLE version (
-    major tinyint NOT NULL,
-    minor tinyint NOT NULL
+    major int NOT nullptr,
+    minor int NOT nullptr
     )
 
 CREATE TABLE strings (
@@ -92,27 +93,25 @@ 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);
+    static const XMLCh RetryOnError[] =     UNICODE_LITERAL_12(R,e,t,r,y,O,n,E,r,r,o,r);
 
     // 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, 0);
             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
@@ -124,10 +123,10 @@ namespace {
         bool createString(const char* context, const char* key, const char* value, time_t expiration) {
             return createRow(STRING_TABLE, context, key, value, expiration);
         }
-        int readString(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
+        int readString(const char* context, const char* key, string* pvalue=nullptr, time_t* pexpiration=nullptr, int version=0) {
             return readRow(STRING_TABLE, context, key, pvalue, pexpiration, version, false);
         }
-        int updateString(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
+        int updateString(const char* context, const char* key, const char* value=nullptr, time_t expiration=0, int version=0) {
             return updateRow(STRING_TABLE, context, key, value, expiration, version);
         }
         bool deleteString(const char* context, const char* key) {
@@ -137,10 +136,10 @@ namespace {
         bool createText(const char* context, const char* key, const char* value, time_t expiration) {
             return createRow(TEXT_TABLE, context, key, value, expiration);
         }
-        int readText(const char* context, const char* key, string* pvalue=NULL, time_t* pexpiration=NULL, int version=0) {
+        int readText(const char* context, const char* key, string* pvalue=nullptr, time_t* pexpiration=nullptr, int version=0) {
             return readRow(TEXT_TABLE, context, key, pvalue, pexpiration, version, true);
         }
-        int updateText(const char* context, const char* key, const char* value=NULL, time_t expiration=0, int version=0) {
+        int updateText(const char* context, const char* key, const char* value=nullptr, time_t expiration=0, int version=0) {
             return updateRow(TEXT_TABLE, context, key, value, expiration, version);
         }
         bool deleteText(const char* context, const char* key) {
@@ -176,7 +175,7 @@ namespace {
         SQLHDBC getHDBC();
         SQLHSTMT getHSTMT(SQLHDBC);
         pair<int,int> getVersion(SQLHDBC);
-        bool log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor=NULL);
+        pair<bool,bool> log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor=nullptr);
 
         static void* cleanup_fn(void*); 
         void cleanup();
@@ -189,6 +188,8 @@ namespace {
 
         SQLHENV m_henv;
         string m_connstring;
+        long m_isolation;
+        vector<SQLINTEGER> m_retries;
     };
 
     StorageService* ODBCStorageServiceFactory(const DOMElement* const & e)
@@ -257,18 +258,32 @@ 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(nullptr), cleanup_thread(nullptr), shutdown(false), m_henv(SQL_NULL_HANDLE), m_isolation(SQL_TXN_SERIALIZABLE)
 {
 #ifdef _DEBUG
     xmltooling::NDC ndc("ODBCStorageService");
 #endif
 
-    const XMLCh* tag=e ? e->getAttributeNS(NULL,cleanupInterval) : NULL;
+    const XMLCh* tag=e ? e->getAttributeNS(nullptr,cleanupInterval) : nullptr;
     if (tag && *tag)
         m_cleanupInterval = XMLString::parseInt(tag);
     if (!m_cleanupInterval)
         m_cleanupInterval = 900;
 
+    auto_ptr_char iso(e ? e->getAttributeNS(nullptr,isolationLevel) : nullptr);
+    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);
@@ -284,7 +299,7 @@ ODBCStorageService::ODBCStorageService(const DOMElement* e) : m_log(Category::ge
     }
 
     // Grab connection string from the configuration.
-    e = e ? XMLHelper::getFirstChildElement(e,ConnectionString) : NULL;
+    e = e ? XMLHelper::getFirstChildElement(e,ConnectionString) : nullptr;
     if (!e || !e->hasChildNodes()) {
         SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
         throw XMLToolingException("ODBC StorageService requires ConnectionString element in configuration.");
@@ -303,6 +318,16 @@ ODBCStorageService::ODBCStorageService(const DOMElement* e) : m_log(Category::ge
         throw XMLToolingException("Unknown database version for ODBC StorageService.");
     }
 
+    // Load any retry errors to check.
+    e = XMLHelper::getNextSiblingElement(e,RetryOnError);
+    while (e) {
+        if (e->hasChildNodes()) {
+            m_retries.push_back(XMLString::parseInt(e->getFirstChild()->getNodeValue()));
+            m_log.info("will retry operations when native ODBC error (%ld) is returned", m_retries.back());
+        }
+        e = XMLHelper::getNextSiblingElement(e,RetryOnError);
+    }
+
     // Initialize the cleanup thread
     shutdown_wait = CondWait::create();
     cleanup_thread = Thread::create(&cleanup_fn, (void*)this);
@@ -312,12 +337,13 @@ ODBCStorageService::~ODBCStorageService()
 {
     shutdown = true;
     shutdown_wait->signal();
-    cleanup_thread->join(NULL);
+    cleanup_thread->join(nullptr);
     delete shutdown_wait;
-    SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
+    if (m_henv != SQL_NULL_HANDLE)
+        SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
 }
 
-bool ODBCStorageService::log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor)
+pair<bool,bool> ODBCStorageService::log_error(SQLHANDLE handle, SQLSMALLINT htype, const char* checkfor)
 {
     SQLSMALLINT         i = 0;
     SQLINTEGER  native;
@@ -326,13 +352,15 @@ bool ODBCStorageService::log_error(SQLHANDLE handle, SQLSMALLINT htype, const ch
     SQLSMALLINT         len;
     SQLRETURN   ret;
 
-    bool res = false;
+    pair<bool,bool> res = make_pair(false,false);
     do {
         ret = SQLGetDiagRec(htype, handle, ++i, state, &native, text, sizeof(text), &len);
         if (SQL_SUCCEEDED(ret)) {
             m_log.error("ODBC Error: %s:%ld:%ld:%s", state, i, native, text);
+            for (vector<SQLINTEGER>::const_iterator n = m_retries.begin(); !res.first && n != m_retries.end(); ++n)
+                res.first = (*n == native);
             if (checkfor && !strcmp(checkfor, (const char*)state))
-                res = true;
+                res.second = true;
         }
     } while(SQL_SUCCEEDED(ret));
     return res;
@@ -353,19 +381,16 @@ SQLHDBC ODBCStorageService::getHDBC()
         throw IOException("ODBC StorageService failed to allocate a connection handle.");
     }
 
-    sr=SQLDriverConnect(handle,NULL,(SQLCHAR*)m_connstring.c_str(),m_connstring.length(),NULL,0,NULL,SQL_DRIVER_NOPROMPT);
+    sr=SQLDriverConnect(handle,nullptr,(SQLCHAR*)m_connstring.c_str(),m_connstring.length(),nullptr,0,nullptr,SQL_DRIVER_NOPROMPT);
     if (!SQL_SUCCEEDED(sr)) {
         m_log.error("failed to connect to database");
         log_error(handle, SQL_HANDLE_DBC);
         throw IOException("ODBC StorageService failed to connect to database.");
     }
 
-    sr = SQLSetConnectAttr(handle, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, NULL);
+    sr = SQLSetConnectAttr(handle, SQL_ATTR_TXN_ISOLATION, (SQLPOINTER)m_isolation, 0);
     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);
-    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;
 }
@@ -385,7 +410,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)) {
@@ -396,8 +421,8 @@ pair<int,int> ODBCStorageService::getVersion(SQLHDBC conn)
 
     SQLINTEGER major;
     SQLINTEGER minor;
-    SQLBindCol(stmt,1,SQL_C_SLONG,&major,0,NULL);
-    SQLBindCol(stmt,2,SQL_C_SLONG,&minor,0,NULL);
+    SQLBindCol(stmt,1,SQL_C_SLONG,&major,0,nullptr);
+    SQLBindCol(stmt,2,SQL_C_SLONG,&minor,0,nullptr);
 
     if ((sr=SQLFetch(stmt)) != SQL_NO_DATA)
         return pair<int,int>(major,minor);
@@ -417,7 +442,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);
@@ -431,46 +456,58 @@ 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 succeeded. 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);
+    SQLLEN b_ind = SQL_NTS;
+    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);
         throw IOException("ODBC StorageService failed to insert record.");
     }
-    m_log.debug("SQLBindParam succeded (context = %s)", context);
+    m_log.debug("SQLBindParam succeeded (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);
         throw IOException("ODBC StorageService failed to insert record.");
     }
-    m_log.debug("SQLBindParam succeded (key = %s)", key);
+    m_log.debug("SQLBindParam succeeded (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);
         throw IOException("ODBC StorageService failed to insert record.");
     }
-    m_log.debug("SQLBindParam succeded (value = %s)", value);
+    m_log.debug("SQLBindParam succeeded (value = %s)", value);
     
     //freeSafeSQL(scontext, context);
     //freeSafeSQL(skey, key);
     //freeSafeSQL(svalue, value);
     //m_log.debug("SQL: %s", q.c_str());
 
-    sr=SQLExecute(stmt);
-    if (!SQL_SUCCEEDED(sr)) {
+    int attempts = 3;
+    pair<bool,bool> logres;
+    do {
+        logres = make_pair(false,false);
+        attempts--;
+        sr=SQLExecute(stmt);
+        if (SQL_SUCCEEDED(sr)) {
+            m_log.debug("SQLExecute of insert succeeded");
+            return true;
+        }
         m_log.error("insert record failed (t=%s, c=%s, k=%s)", table, context, key);
-        if (log_error(stmt, SQL_HANDLE_STMT, "23000"))
+        logres = log_error(stmt, SQL_HANDLE_STMT, "23000");
+        if (logres.second)
             return false;   // supposedly integrity violation?
-        throw IOException("ODBC StorageService failed to insert record.");
-    }
-    return true;
+    } while (attempts && logres.first);
+
+    throw IOException("ODBC StorageService failed to insert record.");
 }
 
 int ODBCStorageService::readRow(
@@ -483,11 +520,11 @@ 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];
-    timestampFromTime(time(NULL), timebuf);
+    timestampFromTime(time(nullptr), timebuf);
     char *scontext = makeSafeSQL(context);
     char *skey = makeSafeSQL(key);
     ostringstream q;
@@ -495,7 +532,7 @@ int ODBCStorageService::readRow(
     if (pexpiration)
         q << ",expires";
     if (pvalue)
-        q << ",CASE version WHEN " << version << " THEN NULL ELSE value END";
+        q << ",CASE version WHEN " << version << " THEN nullptr ELSE value END";
     q << " FROM " << table << " WHERE context='" << scontext << "' AND id='" << skey << "' AND expires > " << timebuf;
     freeSafeSQL(scontext, context);
     freeSafeSQL(skey, key);
@@ -512,9 +549,9 @@ int ODBCStorageService::readRow(
     SQLSMALLINT ver;
     SQL_TIMESTAMP_STRUCT expiration;
 
-    SQLBindCol(stmt,1,SQL_C_SSHORT,&ver,0,NULL);
+    SQLBindCol(stmt,1,SQL_C_SSHORT,&ver,0,nullptr);
     if (pexpiration)
-        SQLBindCol(stmt,2,SQL_C_TYPE_TIMESTAMP,&expiration,0,NULL);
+        SQLBindCol(stmt,2,SQL_C_TYPE_TIMESTAMP,&expiration,0,nullptr);
 
     if ((sr=SQLFetch(stmt)) == SQL_NO_DATA)
         return 0;
@@ -526,7 +563,7 @@ int ODBCStorageService::readRow(
         return version; // nothing's changed, so just echo back the version
 
     if (pvalue) {
-        SQLINTEGER len;
+        SQLLEN len;
         SQLCHAR buf[LONGDATA_BUFLEN];
         while ((sr=SQLGetData(stmt,pexpiration ? 3 : 2,SQL_C_CHAR,buf,sizeof(buf),&len)) != SQL_NO_DATA) {
             if (!SQL_SUCCEEDED(sr)) {
@@ -550,21 +587,25 @@ 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, 0);
+    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];
-    timestampFromTime(time(NULL), timebuf);
+    timestampFromTime(time(nullptr), timebuf);
     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);
@@ -574,7 +615,7 @@ int ODBCStorageService::updateRow(const char *table, const char* context, const
     }
 
     SQLSMALLINT ver;
-    SQLBindCol(stmt,1,SQL_C_SSHORT,&ver,0,NULL);
+    SQLBindCol(stmt,1,SQL_C_SSHORT,&ver,0,nullptr);
     if ((sr=SQLFetch(stmt)) == SQL_NO_DATA) {
         freeSafeSQL(scontext, context);
         freeSafeSQL(skey, key);
@@ -588,6 +629,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 ";
 
@@ -601,7 +645,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);
 
@@ -611,29 +655,40 @@ 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 succeeded. SQL: %s", q.c_str());
 
-    SQLINTEGER b_ind = SQL_NTS;
+    SQLLEN 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);
             throw IOException("ODBC StorageService failed to update record.");
         }
-        m_log.debug("SQLBindParam succeded (context = %s)", context);
+        m_log.debug("SQLBindParam succeeded (context = %s)", context);
     }
 
-    sr=SQLExecute(stmt);
-    if (sr==SQL_NO_DATA)
-        return 0;   // went missing?
-    else if (!SQL_SUCCEEDED(sr)) {
+    int attempts = 3;
+    pair<bool,bool> logres;
+    do {
+        logres = make_pair(false,false);
+        attempts--;
+        sr=SQLExecute(stmt);
+        if (sr==SQL_NO_DATA)
+            return 0;   // went missing?
+        else if (SQL_SUCCEEDED(sr)) {
+            m_log.debug("SQLExecute of update succeeded");
+            return ver + 1;
+        }
+
         m_log.error("update of record failed (t=%s, c=%s, k=%s", table, context, key);
-        log_error(stmt, SQL_HANDLE_STMT);
-        throw IOException("ODBC StorageService failed to update record.");
-    }
+        logres = log_error(stmt, SQL_HANDLE_STMT);
+    } while (attempts && logres.first);
 
-    return ver + 1;
+    throw IOException("ODBC StorageService failed to update record.");
 }
 
 bool ODBCStorageService::deleteRow(const char *table, const char *context, const char* key)
@@ -644,7 +699,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);
@@ -684,7 +739,7 @@ void ODBCStorageService::cleanup()
         if (shutdown)
             break;
         try {
-            reap(NULL);
+            reap(nullptr);
         }
         catch (exception& ex) {
             m_log.error("cleanup thread swallowed exception: %s", ex.what());
@@ -695,7 +750,7 @@ void ODBCStorageService::cleanup()
 
     mutex->unlock();
     delete mutex;
-    Thread::exit(NULL);
+    Thread::exit(nullptr);
 }
 
 void* ODBCStorageService::cleanup_fn(void* cache_p)
@@ -709,7 +764,7 @@ void* ODBCStorageService::cleanup_fn(void* cache_p)
 
   // Now run the cleanup process.
   cache->cleanup();
-  return NULL;
+  return nullptr;
 }
 
 void ODBCStorageService::updateContext(const char *table, const char* context, time_t expiration)
@@ -720,13 +775,13 @@ 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);
 
     char nowbuf[32];
-    timestampFromTime(time(NULL), nowbuf);
+    timestampFromTime(time(nullptr), nowbuf);
 
     char *scontext = makeSafeSQL(context);
     string q("UPDATE ");
@@ -751,11 +806,11 @@ 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];
-    timestampFromTime(time(NULL), nowbuf);
+    timestampFromTime(time(nullptr), nowbuf);
     string q;
     if (context) {
         char *scontext = makeSafeSQL(context);
@@ -783,7 +838,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);