removed global DB connection handle; DB prefix added to DB connection pool parameter...
authorVictor Kirhenshtein <victor@netxms.org>
Wed, 11 Nov 2015 20:43:08 +0000 (22:43 +0200)
committerVictor Kirhenshtein <victor@netxms.org>
Wed, 11 Nov 2015 20:43:08 +0000 (22:43 +0200)
65 files changed:
include/netxmsdb.h
include/nxdbapi.h
src/db/libnxdb/dbcp.cpp
src/db/libnxdb/session.cpp
src/server/core/accesspoint.cpp
src/server/core/actions.cpp
src/server/core/agent_policy.cpp
src/server/core/alarm.cpp
src/server/core/ap_config.cpp
src/server/core/audit.cpp
src/server/core/bizservice.cpp
src/server/core/bizsvcroot.cpp
src/server/core/cert.cpp
src/server/core/cluster.cpp
src/server/core/columnfilter.cpp
src/server/core/condition.cpp
src/server/core/config.cpp
src/server/core/container.cpp
src/server/core/dashboard.cpp
src/server/core/dbwrite.cpp
src/server/core/dcitem.cpp
src/server/core/dcobject.cpp
src/server/core/dctable.cpp
src/server/core/dctthreshold.cpp
src/server/core/entirenet.cpp
src/server/core/epp.cpp
src/server/core/graph.cpp
src/server/core/id.cpp
src/server/core/interface.cpp
src/server/core/main.cpp
src/server/core/mobile.cpp
src/server/core/mt.cpp
src/server/core/netmap.cpp
src/server/core/netobj.cpp
src/server/core/netsrv.cpp
src/server/core/node.cpp
src/server/core/nodelink.cpp
src/server/core/np.cpp
src/server/core/objects.cpp
src/server/core/package.cpp
src/server/core/poll.cpp
src/server/core/rack.cpp
src/server/core/script.cpp
src/server/core/session.cpp
src/server/core/situation.cpp
src/server/core/slmcheck.cpp
src/server/core/snmptrap.cpp
src/server/core/subnet.cpp
src/server/core/svccontainer.cpp
src/server/core/syncer.cpp
src/server/core/template.cpp
src/server/core/uniroot.cpp
src/server/core/userdb.cpp
src/server/core/userdb_objects.cpp
src/server/core/vpnconn.cpp
src/server/core/zone.cpp
src/server/include/netxms_mt.h
src/server/include/nms_core.h
src/server/include/nms_dcoll.h
src/server/include/nms_events.h
src/server/include/nms_objects.h
src/server/include/nms_users.h
src/server/include/nxsrvapi.h
src/server/libnxsrv/messages.mc
src/server/tools/nxdbmgr/upgrade.cpp

index a9b4b2a..5abde5b 100644 (file)
@@ -23,6 +23,6 @@
 #ifndef _netxmsdb_h
 #define _netxmsdb_h
 
-#define DB_FORMAT_VERSION   377
+#define DB_FORMAT_VERSION   378
 
 #endif
index fe014ef..7b02bdf 100644 (file)
@@ -189,8 +189,10 @@ int LIBNXDB_EXPORTABLE DBGetSchemaVersion(DB_HANDLE conn);
 int LIBNXDB_EXPORTABLE DBGetSyntax(DB_HANDLE conn);
 
 String LIBNXDB_EXPORTABLE DBPrepareString(DB_HANDLE conn, const TCHAR *str, int maxSize = -1);
+String LIBNXDB_EXPORTABLE DBPrepareString(DB_DRIVER drv, const TCHAR *str, int maxSize = -1);
 #ifdef UNICODE
 String LIBNXDB_EXPORTABLE DBPrepareStringA(DB_HANDLE conn, const char *str, int maxSize = -1);
+String LIBNXDB_EXPORTABLE DBPrepareStringA(DB_DRIVER drv, const char *str, int maxSize = -1);
 #else
 #define DBPrepareStringA DBPrepareString
 #endif
index 84f1467..2c2b8b8 100644 (file)
@@ -23,6 +23,7 @@
 
 #include "libnxdb.h"
 
+static bool s_initialized = false;
 static DB_DRIVER m_driver;
 static TCHAR m_server[256];
 static TCHAR m_login[256];
@@ -44,9 +45,10 @@ static CONDITION m_condRelease = INVALID_CONDITION_HANDLE;
 /**
  * Create connections on pool initialization
  */
-static void DBConnectionPoolPopulate()
+static bool DBConnectionPoolPopulate()
 {
        TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
+       bool success = false;
 
        MutexLock(m_poolAccessMutex);
        for(int i = 0; i < m_basePoolSize; i++)
@@ -62,6 +64,7 @@ static void DBConnectionPoolPopulate()
          conn->srcFile[0] = 0;
          conn->srcLine = 0;
          m_connections.add(conn);
+         success = true;
       }
       else
       {
@@ -70,6 +73,7 @@ static void DBConnectionPoolPopulate()
       }
        }
        MutexUnlock(m_poolAccessMutex);
+       return success;
 }
 
 /**
@@ -211,6 +215,9 @@ bool LIBNXDB_EXPORTABLE DBConnectionPoolStartup(DB_DRIVER driver, const TCHAR *s
                                                                                                                                int basePoolSize, int maxPoolSize, int cooldownTime,
                                                                                                                                int connTTL)
 {
+   if (s_initialized)
+      return true;   // already initialized
+
        m_driver = driver;
        nx_strncpy(m_server, CHECK_NULL_EX(server), 256);
        nx_strncpy(m_dbName, CHECK_NULL_EX(dbName), 256);
@@ -228,10 +235,18 @@ bool LIBNXDB_EXPORTABLE DBConnectionPoolStartup(DB_DRIVER driver, const TCHAR *s
    m_condShutdown = ConditionCreate(TRUE);
    m_condRelease = ConditionCreate(FALSE);
 
-       DBConnectionPoolPopulate();
+       if (!DBConnectionPoolPopulate())
+       {
+          // cannot open at least one connection
+          ConditionDestroy(m_condShutdown);
+          ConditionDestroy(m_condRelease);
+          MutexDestroy(m_poolAccessMutex);
+          return false;
+       }
 
    m_maintThread = ThreadCreateEx(MaintenanceThread, 0, NULL);
 
+   s_initialized = true;
        __DBDbgPrintf(1, _T("Database Connection Pool initialized"));
 
        return true;
@@ -242,6 +257,9 @@ bool LIBNXDB_EXPORTABLE DBConnectionPoolStartup(DB_DRIVER driver, const TCHAR *s
  */
 void LIBNXDB_EXPORTABLE DBConnectionPoolShutdown()
 {
+   if (!s_initialized)
+      return;
+
    ConditionSet(m_condShutdown);
    ThreadJoin(m_maintThread);
 
@@ -256,6 +274,7 @@ void LIBNXDB_EXPORTABLE DBConnectionPoolShutdown()
 
    m_connections.clear();
 
+   s_initialized = false;
        __DBDbgPrintf(1, _T("Database Connection Pool terminated"));
 
 }
index 792f38b..6b06b73 100644 (file)
@@ -1550,6 +1550,14 @@ bool LIBNXDB_EXPORTABLE DBRollback(DB_HANDLE hConn)
  * Prepare string for using in SQL statement
  */
 String LIBNXDB_EXPORTABLE DBPrepareString(DB_HANDLE conn, const TCHAR *str, int maxSize)
+{
+   return DBPrepareString(conn->m_driver, str, maxSize);
+}
+
+/**
+ * Prepare string for using in SQL statement
+ */
+String LIBNXDB_EXPORTABLE DBPrepareString(DB_DRIVER drv, const TCHAR *str, int maxSize)
 {
        String out;
        if ((maxSize > 0) && (str != NULL) && (maxSize < (int)_tcslen(str)))
@@ -1557,18 +1565,18 @@ String LIBNXDB_EXPORTABLE DBPrepareString(DB_HANDLE conn, const TCHAR *str, int
                TCHAR *temp = (TCHAR *)malloc((maxSize + 1) * sizeof(TCHAR));
                nx_strncpy(temp, str, maxSize + 1);
 #ifdef UNICODE
-               out.setBuffer(conn->m_driver->m_fpDrvPrepareStringW(temp));
+               out.setBuffer(drv->m_fpDrvPrepareStringW(temp));
 #else
-               out.setBuffer(conn->m_driver->m_fpDrvPrepareStringA(temp));
+               out.setBuffer(drv->m_fpDrvPrepareStringA(temp));
 #endif
                free(temp);
        }
        else    
        {
 #ifdef UNICODE
-               out.setBuffer(conn->m_driver->m_fpDrvPrepareStringW(CHECK_NULL_EX(str)));
+               out.setBuffer(drv->m_fpDrvPrepareStringW(CHECK_NULL_EX(str)));
 #else
-               out.setBuffer(conn->m_driver->m_fpDrvPrepareStringA(CHECK_NULL_EX(str)));
+               out.setBuffer(drv->m_fpDrvPrepareStringA(CHECK_NULL_EX(str)));
 #endif
        }
        return out;
@@ -1587,6 +1595,14 @@ String LIBNXDB_EXPORTABLE DBPrepareStringA(DB_HANDLE conn, const char *str, int
        return s;
 }
 
+String LIBNXDB_EXPORTABLE DBPrepareStringA(DB_DRIVER drv, const char *str, int maxSize)
+{
+   WCHAR *wcs = WideStringFromMBString(str);
+   String s = DBPrepareString(drv, wcs, maxSize);
+   free(wcs);
+   return s;
+}
+
 #endif
 
 /**
index ffafab2..4ac2cae 100644 (file)
@@ -68,21 +68,21 @@ AccessPoint::~AccessPoint()
 /**
  * Create object from database data
  */
-BOOL AccessPoint::loadFromDatabase(UINT32 dwId)
+bool AccessPoint::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    m_id = dwId;
 
-   if (!loadCommonProperties())
+   if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for access point object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
        TCHAR query[256];
        _sntprintf(query, 256, _T("SELECT mac_address,vendor,model,serial_number,node_id,ap_state,ap_index FROM access_points WHERE id=%d"), (int)m_id);
-       DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+       DB_RESULT hResult = DBSelect(hdb, query);
        if (hResult == NULL)
-               return FALSE;
+               return false;
 
        DBGetFieldByteArray2(hResult, 0, 0, m_macAddr, MAC_ADDR_LENGTH, 0);
        m_vendor = DBGetField(hResult, 0, 1, NULL, 0);
@@ -95,14 +95,14 @@ BOOL AccessPoint::loadFromDatabase(UINT32 dwId)
        DBFreeResult(hResult);
 
    // Load DCI and access list
-   loadACLFromDB();
-   loadItemsFromDB();
+   loadACLFromDB(hdb);
+   loadItemsFromDB(hdb);
    for(int i = 0; i < m_dcObjects->size(); i++)
-      if (!m_dcObjects->get(i)->loadThresholdsFromDB())
-         return FALSE;
+      if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
+         return false;
 
    // Link access point to node
-       BOOL success = FALSE;
+       bool success = false;
    if (!m_isDeleted)
    {
       NetObj *object = FindObjectById(m_nodeId);
@@ -118,12 +118,12 @@ BOOL AccessPoint::loadFromDatabase(UINT32 dwId)
       {
          object->AddChild(this);
          AddParent(object);
-         success = TRUE;
+         success = true;
       }
    }
    else
    {
-      success = TRUE;
+      success = true;
    }
 
    return success;
index 25688be..301d717 100644 (file)
@@ -1,6 +1,6 @@
 /*
 ** NetXMS - Network Management System
-** Copyright (C) 2003-2014 Victor Kirhenshtein
+** Copyright (C) 2003-2015 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -66,7 +66,8 @@ static BOOL LoadActions()
    BOOL bResult = FALSE;
    UINT32 i;
 
-   hResult = DBSelect(g_hCoreDB, _T("SELECT action_id,action_name,action_type,")
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT action_id,action_name,action_type,")
                                  _T("is_disabled,rcpt_addr,email_subject,action_data ")
                                  _T("FROM actions ORDER BY action_id"));
    if (hResult != NULL)
@@ -92,6 +93,7 @@ static BOOL LoadActions()
    {
       nxlog_write(MSG_ACTIONS_LOAD_FAILED, EVENTLOG_ERROR_TYPE, NULL);
    }
+   DBConnectionPoolReleaseConnection(hdb);
    return bResult;
 }
 
@@ -581,6 +583,8 @@ UINT32 DeleteActionFromDB(UINT32 dwActionId)
    UINT32 i, dwResult = RCC_INVALID_ACTION_ID;
    TCHAR szQuery[256];
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    RWLockWriteLock(m_rwlockActionListAccess, INFINITE);
 
    for(i = 0; i < m_dwNumActions; i++)
@@ -593,13 +597,14 @@ UINT32 DeleteActionFromDB(UINT32 dwActionId)
          safe_free(m_pActionList[i].pszData);
          memmove(&m_pActionList[i], &m_pActionList[i + 1], sizeof(NXC_ACTION) * (m_dwNumActions - i));
          _sntprintf(szQuery, 256, _T("DELETE FROM actions WHERE action_id=%d"), dwActionId);
-         DBQuery(g_hCoreDB, szQuery);
+         DBQuery(hdb, szQuery);
 
          dwResult = RCC_SUCCESS;
          break;
       }
 
    RWLockUnlock(m_rwlockActionListAccess);
+   DBConnectionPoolReleaseConnection(hdb);
    return dwResult;
 }
 
index 63771bb..86afde0 100644 (file)
@@ -145,11 +145,11 @@ bool AgentPolicy::deleteFromDatabase(DB_HANDLE hdb)
 /**
  * Load from database
  */
-BOOL AgentPolicy::loadFromDatabase(UINT32 dwId)
+bool AgentPolicy::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
        m_id = dwId;
 
-       if (!loadCommonProperties())
+       if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for agent policy object %d"), dwId);
       return FALSE;
@@ -159,10 +159,10 @@ BOOL AgentPolicy::loadFromDatabase(UINT32 dwId)
    {
                TCHAR query[256];
 
-          loadACLFromDB();
+          loadACLFromDB(hdb);
 
                _sntprintf(query, 256, _T("SELECT version FROM ap_common WHERE id=%d"), dwId);
-               DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+               DB_RESULT hResult = DBSelect(hdb, query);
                if (hResult == NULL)
                        return FALSE;
 
@@ -171,7 +171,7 @@ BOOL AgentPolicy::loadFromDatabase(UINT32 dwId)
 
           // Load related nodes list
       _sntprintf(query, 256, _T("SELECT node_id FROM ap_bindings WHERE policy_id=%d"), m_id);
-      hResult = DBSelect(g_hCoreDB, query);
+      hResult = DBSelect(hdb, query);
       if (hResult != NULL)
       {
          int numNodes = DBGetNumRows(hResult);
index 2895a37..98fd59c 100644 (file)
@@ -77,9 +77,9 @@ static void UpdateAlarmInDB(NXC_ALARM *pAlarm)
               pAlarm->nState, pAlarm->dwAckByUser, pAlarm->dwTermByUser,
               pAlarm->dwLastChangeTime, pAlarm->nCurrentSeverity,
               pAlarm->dwRepeatCount, pAlarm->nHelpDeskState,
-                            (const TCHAR *)DBPrepareString(g_hCoreDB, pAlarm->szHelpDeskRef),
+                            (const TCHAR *)DBPrepareString(g_dbDriver, pAlarm->szHelpDeskRef),
               pAlarm->dwTimeout, pAlarm->dwTimeoutEvent,
-                            (const TCHAR *)DBPrepareString(g_hCoreDB, pAlarm->szMessage),
+                            (const TCHAR *)DBPrepareString(g_dbDriver, pAlarm->szMessage),
                                  pAlarm->dwResolvedByUser, pAlarm->ackTimeout, pAlarm->dwAlarmId);
    QueueSQLRequest(szQuery);
 
@@ -87,9 +87,10 @@ static void UpdateAlarmInDB(NXC_ALARM *pAlarm)
        {
                _sntprintf(szQuery, 256, _T("DELETE FROM alarm_events WHERE alarm_id=%d"), (int)pAlarm->dwAlarmId);
                QueueSQLRequest(szQuery);
+
                DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
                DeleteAlarmNotes(hdb, pAlarm->dwAlarmId);
-      DBConnectionPoolReleaseConnection(hdb);
+          DBConnectionPoolReleaseConnection(hdb);
        }
 }
 
@@ -345,11 +346,11 @@ void NXCORE_EXPORTABLE CreateNewAlarm(TCHAR *pszMsg, TCHAR *pszKey, int nState,
                  _T("(%d,%d,%d,%d,%d,%s,%d,%d,%s,%d,%d,%d,%d,%s,%d,%d,%d,%d,") UINT64_FMT _T(",%d)"),
               alarm->dwAlarmId, alarm->dwCreationTime, alarm->dwLastChangeTime,
                                  alarm->dwSourceObject, alarm->dwSourceEventCode,
-                                 (const TCHAR *)DBPrepareString(g_hCoreDB, alarm->szMessage),
+                                 (const TCHAR *)DBPrepareString(g_dbDriver, alarm->szMessage),
               alarm->nOriginalSeverity, alarm->nCurrentSeverity,
-                                 (const TCHAR *)DBPrepareString(g_hCoreDB, alarm->szKey),
+                                 (const TCHAR *)DBPrepareString(g_dbDriver, alarm->szKey),
                                  alarm->nState, alarm->dwAckByUser, alarm->dwResolvedByUser, alarm->nHelpDeskState,
-                                 (const TCHAR *)DBPrepareString(g_hCoreDB, alarm->szHelpDeskRef),
+                                 (const TCHAR *)DBPrepareString(g_dbDriver, alarm->szHelpDeskRef),
               alarm->dwRepeatCount, alarm->dwTermByUser, alarm->dwTimeout,
                                  alarm->dwTimeoutEvent, alarm->qwSourceEventId, alarm->ackTimeout);
       QueueSQLRequest(szQuery);
@@ -1423,13 +1424,14 @@ bool InitAlarmManager()
    DB_RESULT hResult;
 
    // Load active alarms into memory
-   hResult = DBSelect(g_hCoreDB, _T("SELECT alarm_id,source_object_id,")
-                                 _T("source_event_code,source_event_id,message,")
-                                 _T("original_severity,current_severity,")
-                                 _T("alarm_key,creation_time,last_change_time,")
-                                 _T("hd_state,hd_ref,ack_by,repeat_count,")
-                                 _T("alarm_state,timeout,timeout_event,resolved_by,")
-                                 _T("ack_timeout FROM alarms WHERE alarm_state<>3"));
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT alarm_id,source_object_id,")
+                           _T("source_event_code,source_event_id,message,")
+                           _T("original_severity,current_severity,")
+                           _T("alarm_key,creation_time,last_change_time,")
+                           _T("hd_state,hd_ref,ack_by,repeat_count,")
+                           _T("alarm_state,timeout,timeout_event,resolved_by,")
+                           _T("ack_timeout FROM alarms WHERE alarm_state<>3"));
    if (hResult == NULL)
       return false;
 
@@ -1456,7 +1458,7 @@ bool InitAlarmManager()
          alarm->nState = (BYTE)DBGetFieldLong(hResult, i, 14);
          alarm->dwTimeout = DBGetFieldULong(hResult, i, 15);
          alarm->dwTimeoutEvent = DBGetFieldULong(hResult, i, 16);
-                       alarm->noteCount = GetNoteCount(g_hCoreDB, alarm->dwAlarmId);
+                       alarm->noteCount = GetNoteCount(hdb, alarm->dwAlarmId);
          alarm->dwResolvedByUser = DBGetFieldULong(hResult, i, 17);
          alarm->ackTimeout = DBGetFieldULong(hResult, i, 18);
          m_alarmList->add(alarm);
@@ -1464,6 +1466,7 @@ bool InitAlarmManager()
    }
 
    DBFreeResult(hResult);
+   DBConnectionPoolReleaseConnection(hdb);
 
        m_hWatchdogThread = ThreadCreateEx(WatchdogThread, 0, NULL);
    return true;
index ac729a7..b08619a 100644 (file)
@@ -112,16 +112,16 @@ bool AgentPolicyConfig::deleteFromDatabase(DB_HANDLE hdb)
 /**
  * Load from database
  */
-BOOL AgentPolicyConfig::loadFromDatabase(UINT32 dwId)
+bool AgentPolicyConfig::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
        BOOL success = FALSE;
 
-       if (AgentPolicy::loadFromDatabase(dwId))
+       if (AgentPolicy::loadFromDatabase(hdb, dwId))
        {
                TCHAR query[256];
 
                _sntprintf(query, 256, _T("SELECT file_content FROM ap_config_files WHERE policy_id=%d"), dwId);
-               DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+               DB_RESULT hResult = DBSelect(hdb, query);
                if (hResult != NULL)
                {
                        if (DBGetNumRows(hResult) > 0)
index 4a96a4e..bcf3139 100644 (file)
@@ -83,7 +83,8 @@ void InitAuditLog()
 {
        DB_RESULT hResult;
 
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(record_id) FROM audit_log"));
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT max(record_id) FROM audit_log"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -116,6 +117,7 @@ void InitAuditLog()
 
                SendSyslogRecord(_T("NetXMS server audit subsystem started"));
        }
+       DBConnectionPoolReleaseConnection(hdb);
 }
 
 /**
@@ -150,8 +152,8 @@ void NXCORE_EXPORTABLE WriteAuditLog(const TCHAR *subsys, BOOL isSuccess, UINT32
        va_end(args);
 
        query.appendFormattedString(_T("INSERT INTO audit_log (record_id,timestamp,subsystem,success,user_id,workstation,session_id,object_id,message) VALUES(%d,") TIME_T_FMT _T(",%s,%d,%d,%s,%d,%d,%s)"),
-      InterlockedIncrement(&m_recordId), time(NULL), (const TCHAR *)DBPrepareString(g_hCoreDB, subsys), isSuccess ? 1 : 0, 
-               userId, (const TCHAR *)DBPrepareString(g_hCoreDB, workstation), sessionId, objectId, (const TCHAR *)DBPrepareString(g_hCoreDB, text));
+      InterlockedIncrement(&m_recordId), time(NULL), (const TCHAR *)DBPrepareString(g_dbDriver, subsys), isSuccess ? 1 : 0,
+               userId, (const TCHAR *)DBPrepareString(g_dbDriver, workstation), sessionId, objectId, (const TCHAR *)DBPrepareString(g_dbDriver, text));
        QueueSQLRequest(query);
 
        msg.setCode(CMD_AUDIT_RECORD);
index bb090c6..0943275 100644 (file)
@@ -58,13 +58,13 @@ BusinessService::~BusinessService()
 /**
  * Create object from database data
  */
-BOOL BusinessService::loadFromDatabase(UINT32 id)
+bool BusinessService::loadFromDatabase(DB_HANDLE hdb, UINT32 id)
 {
-       if (!ServiceContainer::loadFromDatabase(id))
+       if (!ServiceContainer::loadFromDatabase(hdb, id))
                return FALSE;
 
        // now it doesn't make any sense but hopefully will do in the future
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT service_id FROM business_services WHERE service_id=?"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT service_id FROM business_services WHERE service_id=?"));
        if (hStmt == NULL)
        {
                DbgPrintf(4, _T("Cannot prepare select from business_services"));
@@ -114,7 +114,7 @@ BOOL BusinessService::saveToDatabase(DB_HANDLE hdb)
        }
        DBFreeStatement(hStmt);
 
-       hStmt = DBPrepare(g_hCoreDB, bNewObject ? _T("INSERT INTO business_services (service_id) VALUES (?)") :
+       hStmt = DBPrepare(hdb, bNewObject ? _T("INSERT INTO business_services (service_id) VALUES (?)") :
                                                                                          _T("UPDATE business_services SET service_id=service_id WHERE service_id=?"));
        if (hStmt == NULL)
        {
index d517408..8924f10 100644 (file)
@@ -75,43 +75,38 @@ BOOL BusinessServiceRoot::saveToDatabase(DB_HANDLE hdb)
 /**
  * Load properties from database
  */
-void BusinessServiceRoot::LoadFromDB()
+void BusinessServiceRoot::loadFromDatabase(DB_HANDLE hdb)
 {
-   loadCommonProperties();
-   loadACLFromDB();
+   loadCommonProperties(hdb);
+   loadACLFromDB(hdb);
        initUptimeStats();
 }
 
-
-//
-// Link child objects
-// This method is expected to be called only at startup, so we don't lock
-//
-
-void BusinessServiceRoot::LinkChildObjects()
+/**
+ * Link child objects
+ * This method is expected to be called only at startup, so we don't lock
+ */
+void BusinessServiceRoot::linkChildObjects()
 {
-   UINT32 i, dwNumChilds, dwObjectId;
-   NetObj *pObject;
-   TCHAR szQuery[256];
-   DB_RESULT hResult;
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
 
-   // Load child list and link objects
+   TCHAR szQuery[256];
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT object_id FROM container_members WHERE container_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+
+   DB_RESULT hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
-      dwNumChilds = DBGetNumRows(hResult);
-      for(i = 0; i < dwNumChilds; i++)
+      int count = DBGetNumRows(hResult);
+      for(int i = 0; i < count; i++)
       {
-         dwObjectId = DBGetFieldULong(hResult, i, 0);
-         pObject = FindObjectById(dwObjectId);
+         UINT32 dwObjectId = DBGetFieldULong(hResult, i, 0);
+         NetObj *pObject = FindObjectById(dwObjectId);
          if (pObject != NULL)
-            LinkObject(pObject);
+            linkObject(pObject);
          else
-            nxlog_write(MSG_ROOT_INVALID_CHILD_ID, EVENTLOG_WARNING_TYPE, "ds", 
-                        dwObjectId, g_szClassName[getObjectClass()]);
+            nxlog_write(MSG_ROOT_INVALID_CHILD_ID, EVENTLOG_WARNING_TYPE, "ds", dwObjectId, g_szClassName[getObjectClass()]);
       }
       DBFreeResult(hResult);
    }
+   DBConnectionPoolReleaseConnection(hdb);
 }
-
index 1a9a4f8..890d26d 100644 (file)
@@ -247,7 +247,8 @@ void ReloadCertificates()
        if (m_pTrustedCertStore != NULL)
        {
                _sntprintf(szBuffer, 256, _T("SELECT cert_data,subject FROM certificates WHERE cert_type=%d"), CERT_TYPE_TRUSTED_CA);
-               hResult = DBSelect(g_hCoreDB, szBuffer);
+               DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+               hResult = DBSelect(hdb, szBuffer);
                if (hResult != NULL)
                {
                        nRows = DBGetNumRows(hResult);
@@ -289,6 +290,7 @@ void ReloadCertificates()
                        if (nLoaded > 0)
                                nxlog_write(MSG_CA_CERTIFICATES_LOADED, EVENTLOG_INFORMATION_TYPE, "d", nLoaded);
                }
+               DBConnectionPoolReleaseConnection(hdb);
        }
        else
        {
index 1e71efe..b84e48d 100644 (file)
@@ -1,6 +1,6 @@
 /*
 ** NetXMS - Network Management System
-** Copyright (C) 2003-2013 Victor Kirhenshtein
+** Copyright (C) 2003-2015 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -62,10 +62,10 @@ Cluster::~Cluster()
 /**
  * Create object from database data
  */
-BOOL Cluster::loadFromDatabase(UINT32 dwId)
+bool Cluster::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
        TCHAR szQuery[256];
-   BOOL bResult = FALSE;
+   bool bResult = false;
        DB_RESULT hResult;
        UINT32 dwNodeId;
        NetObj *pObject;
@@ -73,33 +73,33 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
+   if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for cluster object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
        _sntprintf(szQuery, 256, _T("SELECT cluster_type,zone_guid FROM clusters WHERE id=%d"), (int)m_id);
-       hResult = DBSelect(g_hCoreDB, szQuery);
+       hResult = DBSelect(hdb, szQuery);
        if (hResult == NULL)
-               return FALSE;
+               return false;
 
        m_dwClusterType = DBGetFieldULong(hResult, 0, 0);
        m_zoneId = DBGetFieldULong(hResult, 0, 1);
        DBFreeResult(hResult);
 
    // Load DCI and access list
-   loadACLFromDB();
-   loadItemsFromDB();
+   loadACLFromDB(hdb);
+   loadItemsFromDB(hdb);
    for(i = 0; i < m_dcObjects->size(); i++)
-      if (!m_dcObjects->get(i)->loadThresholdsFromDB())
-         return FALSE;
+      if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
+         return false;
 
    if (!m_isDeleted)
    {
                // Load member nodes
                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT node_id FROM cluster_members WHERE cluster_id=%d"), m_id);
-               hResult = DBSelect(g_hCoreDB, szQuery);
+               hResult = DBSelect(hdb, szQuery);
                if (hResult != NULL)
                {
                        nRows = DBGetNumRows(hResult);
@@ -127,7 +127,7 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
                                }
                        }
                        if (i == nRows)
-                               bResult = TRUE;
+                               bResult = true;
                        DBFreeResult(hResult);
                }
 
@@ -135,7 +135,7 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
                if (bResult)
                {
                        _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT subnet_addr,subnet_mask FROM cluster_sync_subnets WHERE cluster_id=%d"), m_id);
-                       hResult = DBSelect(g_hCoreDB, szQuery);
+                       hResult = DBSelect(hdb, szQuery);
                        if (hResult != NULL)
                        {
                                int count = DBGetNumRows(hResult);
@@ -149,7 +149,7 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
                        }
                        else
                        {
-                               bResult = FALSE;
+                               bResult = false;
                        }
                }
 
@@ -157,7 +157,7 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
                if (bResult)
                {
                        _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT resource_id,resource_name,ip_addr,current_owner FROM cluster_resources WHERE cluster_id=%d"), m_id);
-                       hResult = DBSelect(g_hCoreDB, szQuery);
+                       hResult = DBSelect(hdb, szQuery);
                        if (hResult != NULL)
                        {
                                m_dwNumResources = DBGetNumRows(hResult);
@@ -176,13 +176,13 @@ BOOL Cluster::loadFromDatabase(UINT32 dwId)
                        }
                        else
                        {
-                               bResult = FALSE;
+                               bResult = false;
                        }
                }
        }
    else
    {
-      bResult = TRUE;
+      bResult = true;
    }
 
    return bResult;
index 1e2a374..dcda711 100644 (file)
@@ -132,7 +132,7 @@ String ColumnFilter::generateSql()
                        {
                                if (m_negated)
                                        sql += _T("NOT ");
-                               sql.appendFormattedString(_T("%s LIKE %s"), m_column, (const TCHAR *)DBPrepareString(g_hCoreDB, m_value.like));
+                               sql.appendFormattedString(_T("%s LIKE %s"), m_column, (const TCHAR *)DBPrepareString(g_dbDriver, m_value.like));
                        }
                        break;
                case FILTER_SET:
index 8a138fc..52a429f 100644 (file)
@@ -74,7 +74,7 @@ Condition::~Condition()
 /**
  * Load object from database
  */
-BOOL Condition::loadFromDatabase(UINT32 dwId)
+bool Condition::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    TCHAR szQuery[512];
    DB_RESULT hResult;
@@ -82,22 +82,22 @@ BOOL Condition::loadFromDatabase(UINT32 dwId)
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
    // Load properties
    _sntprintf(szQuery, 512, _T("SELECT activation_event,deactivation_event,")
                             _T("source_object,active_status,inactive_status,")
                             _T("script FROM conditions WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    if (DBGetNumRows(hResult) == 0)
    {
       // No object with given ID in database
       DBFreeResult(hResult);
-      return FALSE;
+      return false;
    }
 
    m_activationEventCode = DBGetFieldULong(hResult, 0, 0);
@@ -131,9 +131,9 @@ BOOL Condition::loadFromDatabase(UINT32 dwId)
    // Load DCI map
    _sntprintf(szQuery, 512, _T("SELECT dci_id,node_id,dci_func,num_polls ")
                             _T("FROM cond_dci_map WHERE condition_id=%d ORDER BY sequence_number"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    m_dciCount = DBGetNumRows(hResult);
    if (m_dciCount > 0)
@@ -149,7 +149,7 @@ BOOL Condition::loadFromDatabase(UINT32 dwId)
    }
    DBFreeResult(hResult);
 
-   return loadACLFromDB();
+   return loadACLFromDB(hdb);
 }
 
 /**
index cb58af2..93f0e1d 100644 (file)
@@ -164,7 +164,8 @@ bool NXCORE_EXPORTABLE MetaDataReadStr(const TCHAR *szVar, TCHAR *szBuffer, int
    if (_tcslen(szVar) > 127)
       return false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT var_value FROM metadata WHERE var_name=?"));
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT var_value FROM metadata WHERE var_name=?"));
        if (hStmt != NULL)
        {
                DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, szVar, DB_BIND_STATIC);
@@ -180,6 +181,7 @@ bool NXCORE_EXPORTABLE MetaDataReadStr(const TCHAR *szVar, TCHAR *szBuffer, int
                }
                DBFreeStatement(hStmt);
        }
+       DBConnectionPoolReleaseConnection(hdb);
    return bSuccess;
 }
 
@@ -299,11 +301,8 @@ static void OnConfigVariableChange(bool isCLOB, const TCHAR *name, const TCHAR *
 /**
  * Read string value from configuration table
  */
-bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault)
+bool NXCORE_EXPORTABLE ConfigReadStrEx(DB_HANDLE dbHandle, const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault)
 {
-   DB_RESULT hResult;
-   bool bSuccess = false;
-
    nx_strncpy(szBuffer, szDefault, iBufSize);
    if (_tcslen(szVar) > 127)
       return false;
@@ -318,12 +317,13 @@ bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iB
       return true;
    }
 
-   DB_HANDLE hdb = (g_flags & AF_DB_CONNECTION_POOL_READY) ? DBConnectionPoolAcquireConnection() : g_hCoreDB;
+   bool bSuccess = false;
+   DB_HANDLE hdb = (dbHandle == NULL) ? DBConnectionPoolAcquireConnection() : dbHandle;
        DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT var_value FROM config WHERE var_name=?"));
        if (hStmt != NULL)
        {
                DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, szVar, DB_BIND_STATIC);
-               hResult = DBSelectPrepared(hStmt);
+               DB_RESULT hResult = DBSelectPrepared(hStmt);
           if (hResult != NULL)
                {
                        if (DBGetNumRows(hResult) > 0)
@@ -336,7 +336,7 @@ bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iB
                }
                DBFreeStatement(hStmt);
        }
-   if (g_flags & AF_DB_CONNECTION_POOL_READY)
+   if (dbHandle == NULL)
       DBConnectionPoolReleaseConnection(hdb);
 
    if (bSuccess)
@@ -349,6 +349,14 @@ bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iB
    return bSuccess;
 }
 
+/**
+ * Read string value from configuration table
+ */
+bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *var, TCHAR *buffer, int bufferSize, const TCHAR *defaultValue)
+{
+   return ConfigReadStrEx(NULL, var, buffer, bufferSize, defaultValue);
+}
+
 /**
  * Read multibyte string from configuration table
  */
@@ -385,7 +393,7 @@ bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int
    if (_tcslen(szVar) > 127)
       return false;
 
-   DB_HANDLE hdb = (g_flags & AF_DB_CONNECTION_POOL_READY) ? DBConnectionPoolAcquireConnection() : g_hCoreDB;
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
        DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT var_value FROM config WHERE var_name=?"));
        if (hStmt != NULL)
        {
@@ -402,8 +410,7 @@ bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int
                }
                DBFreeStatement(hStmt);
        }
-   if (g_flags & AF_DB_CONNECTION_POOL_READY)
-      DBConnectionPoolReleaseConnection(hdb);
+   DBConnectionPoolReleaseConnection(hdb);
 
    return bSuccess;
 }
@@ -412,10 +419,18 @@ bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int
  * Read integer value from configuration table
  */
 int NXCORE_EXPORTABLE ConfigReadInt(const TCHAR *szVar, int iDefault)
+{
+   return ConfigReadIntEx(NULL, szVar, iDefault);
+}
+
+/**
+ * Read integer value from configuration table
+ */
+int NXCORE_EXPORTABLE ConfigReadIntEx(DB_HANDLE hdb, const TCHAR *szVar, int iDefault)
 {
    TCHAR szBuffer[64];
 
-   if (ConfigReadStr(szVar, szBuffer, 64, _T("")))
+   if (ConfigReadStrEx(hdb, szVar, szBuffer, 64, _T("")))
       return _tcstol(szBuffer, NULL, 0);
    else
       return iDefault;
index b5e162b..f476ec0 100644 (file)
@@ -1,6 +1,6 @@
 /*
 ** NetXMS - Network Management System
-** Copyright (C) 2003-2013 Victor Kirhenshtein
+** Copyright (C) 2003-2015 Victor Kirhenshtein
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
@@ -78,7 +78,7 @@ Container::~Container()
  *
  * @param dwId object ID
  */
-BOOL Container::loadFromDatabase(UINT32 dwId)
+bool Container::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    TCHAR szQuery[256];
    DB_RESULT hResult;
@@ -86,19 +86,19 @@ BOOL Container::loadFromDatabase(UINT32 dwId)
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT category,flags,auto_bind_filter FROM containers WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    if (DBGetNumRows(hResult) == 0)
    {
       // No object with given ID in database
       DBFreeResult(hResult);
-      return FALSE;
+      return false;
    }
 
    m_dwCategory = DBGetFieldULong(hResult, 0, 0);
@@ -119,13 +119,13 @@ BOOL Container::loadFromDatabase(UINT32 dwId)
    DBFreeResult(hResult);
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
    // Load child list for later linkage
    if (!m_isDeleted)
    {
       _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT object_id FROM container_members WHERE container_id=%d"), m_id);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          m_dwChildIdListSize = DBGetNumRows(hResult);
@@ -139,7 +139,7 @@ BOOL Container::loadFromDatabase(UINT32 dwId)
       }
    }
 
-   return TRUE;
+   return true;
 }
 
 /**
index b05aaa0..2ed83c7 100644 (file)
@@ -66,18 +66,18 @@ void Dashboard::calculateCompoundStatus(BOOL bForcedRecalc)
 /**
  * Create object from database
  */
-BOOL Dashboard::loadFromDatabase(UINT32 dwId)
+bool Dashboard::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
-       if (!Container::loadFromDatabase(dwId))
-               return FALSE;
+       if (!Container::loadFromDatabase(hdb, dwId))
+               return false;
 
        m_iStatus = STATUS_NORMAL;
 
        TCHAR query[256];
        _sntprintf(query, 256, _T("SELECT num_columns,options FROM dashboards WHERE id=%d"), (int)dwId);
-       DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+       DB_RESULT hResult = DBSelect(hdb, query);
        if (hResult == NULL)
-               return FALSE;
+               return false;
        if (DBGetNumRows(hResult) > 0)
        {
                m_numColumns = (int)DBGetFieldLong(hResult, 0, 0);
@@ -87,9 +87,9 @@ BOOL Dashboard::loadFromDatabase(UINT32 dwId)
 
        _sntprintf(query, 256, _T("SELECT element_type,element_data,layout_data FROM dashboard_elements ")
                                                                  _T("WHERE dashboard_id=%d ORDER BY element_id"), (int)dwId);
-       hResult = DBSelect(g_hCoreDB, query);
+       hResult = DBSelect(hdb, query);
        if (hResult == NULL)
-               return FALSE;
+               return false;
 
        int count = DBGetNumRows(hResult);
        for(int i = 0; i < count; i++)
@@ -102,7 +102,7 @@ BOOL Dashboard::loadFromDatabase(UINT32 dwId)
        }
 
        DBFreeResult(hResult);
-       return TRUE;
+       return true;
 }
 
 /**
index dd57d08..83e300e 100644 (file)
@@ -143,21 +143,12 @@ void QueueRawDciDataUpdate(time_t timestamp, UINT32 dciId, const TCHAR *rawValue
  */
 static THREAD_RESULT THREAD_CALL DBWriteThread(void *arg)
 {
-   DB_HANDLE hdb;
-
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-               TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
-      hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
-      if (hdb == NULL)
-      {
-         nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
-         return THREAD_OK;
-      }
-   }
-   else
+   TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
+   DB_HANDLE hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
+   if (hdb == NULL)
    {
-      hdb = g_hCoreDB;
+      nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
+      return THREAD_OK;
    }
 
    while(1)
@@ -186,10 +177,7 @@ static THREAD_RESULT THREAD_CALL DBWriteThread(void *arg)
       free(rq);
    }
 
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-      DBDisconnect(hdb);
-   }
+   DBDisconnect(hdb);
    return THREAD_OK;
 }
 
@@ -198,21 +186,12 @@ static THREAD_RESULT THREAD_CALL DBWriteThread(void *arg)
  */
 static THREAD_RESULT THREAD_CALL IDataWriteThread(void *arg)
 {
-   DB_HANDLE hdb;
-
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-               TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
-      hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
-      if (hdb == NULL)
-      {
-         nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
-         return THREAD_OK;
-      }
-   }
-   else
+   TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
+   DB_HANDLE hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
+   if (hdb == NULL)
    {
-      hdb = g_hCoreDB;
+      nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
+      return THREAD_OK;
    }
 
    while(1)
@@ -264,10 +243,7 @@ static THREAD_RESULT THREAD_CALL IDataWriteThread(void *arg)
        }
 
 stop:
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-      DBDisconnect(hdb);
-   }
+   DBDisconnect(hdb);
    return THREAD_OK;
 }
 
@@ -276,21 +252,12 @@ stop:
  */
 static THREAD_RESULT THREAD_CALL RawDataWriteThread(void *arg)
 {
-   DB_HANDLE hdb;
-
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-               TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
-      hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
-      if (hdb == NULL)
-      {
-         nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
-         return THREAD_OK;
-      }
-   }
-   else
+   TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
+   DB_HANDLE hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
+   if (hdb == NULL)
    {
-      hdb = g_hCoreDB;
+      nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
+      return THREAD_OK;
    }
 
    while(1)
@@ -340,10 +307,7 @@ static THREAD_RESULT THREAD_CALL RawDataWriteThread(void *arg)
        }
 
 stop:
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-      DBDisconnect(hdb);
-   }
+   DBDisconnect(hdb);
    return THREAD_OK;
 }
 
@@ -354,14 +318,11 @@ void StartDBWriter()
 {
    int i;
 
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-      m_numWriters = ConfigReadInt(_T("NumberOfDatabaseWriters"), 1);
-      if (m_numWriters < 1)
-         m_numWriters = 1;
-      if (m_numWriters > MAX_DB_WRITERS)
-         m_numWriters = MAX_DB_WRITERS;
-   }
+   m_numWriters = ConfigReadInt(_T("NumberOfDatabaseWriters"), 1);
+   if (m_numWriters < 1)
+      m_numWriters = 1;
+   if (m_numWriters > MAX_DB_WRITERS)
+      m_numWriters = MAX_DB_WRITERS;
 
    for(i = 0; i < m_numWriters; i++)
       m_hWriteThreadList[i] = ThreadCreateEx(DBWriteThread, 0, NULL);
index d1a6164..229f486 100644 (file)
@@ -108,7 +108,7 @@ DCItem::DCItem(const DCItem *pSrc) : DCObject(pSrc)
  *    custom_units_name,perftab_settings,system_tag,snmp_port,snmp_raw_value_type,
  *    instd_method,instd_data,instd_filter,samples,comments
  */
-DCItem::DCItem(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
+DCItem::DCItem(DB_HANDLE hdb, DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
 {
    m_id = DBGetFieldULong(hResult, iRow, 0);
    DBGetField(hResult, iRow, 1, m_name, MAX_ITEM_NAME);
@@ -155,7 +155,7 @@ DCItem::DCItem(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
    // Load last raw value from database
        TCHAR szQuery[256];
    _sntprintf(szQuery, 256, _T("SELECT raw_value,last_poll_time FROM raw_dci_values WHERE item_id=%d"), m_id);
-   DB_RESULT hTempResult = DBSelect(g_hCoreDB, szQuery);
+   DB_RESULT hTempResult = DBSelect(hdb, szQuery);
    if (hTempResult != NULL)
    {
       if (DBGetNumRows(hTempResult) > 0)
@@ -168,7 +168,7 @@ DCItem::DCItem(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
       DBFreeResult(hTempResult);
    }
 
-       loadCustomSchedules();
+       loadCustomSchedules(hdb);
 }
 
 /**
@@ -292,11 +292,11 @@ void DCItem::clearCache()
 /**
  * Load data collection items thresholds from database
  */
-bool DCItem::loadThresholdsFromDB()
+bool DCItem::loadThresholdsFromDB(DB_HANDLE hdb)
 {
    bool result = false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
+       DB_STATEMENT hStmt = DBPrepare(hdb,
                   _T("SELECT threshold_id,fire_value,rearm_value,check_function,")
               _T("check_operation,sample_count,script,event_code,current_state,")
               _T("rearm_event_code,repeat_interval,current_severity,")
index 459ca37..a35541d 100644 (file)
@@ -237,15 +237,15 @@ DCObject::~DCObject()
  * Load custom schedules from database
  * (assumes that no schedules was created before this call)
  */
-BOOL DCObject::loadCustomSchedules()
+bool DCObject::loadCustomSchedules(DB_HANDLE hdb)
 {
    if (!(m_flags & DCF_ADVANCED_SCHEDULE))
-               return TRUE;
+               return true;
 
        TCHAR query[256];
 
    _sntprintf(query, 256, _T("SELECT schedule FROM dci_schedules WHERE item_id=%d"), m_id);
-   DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+   DB_RESULT hResult = DBSelect(hdb, query);
    if (hResult != NULL)
    {
       m_dwNumSchedules = (UINT32)DBGetNumRows(hResult);
@@ -760,7 +760,7 @@ void DCObject::createNXMPRecord(String &str)
 /**
  * Load data collection object thresholds from database
  */
-bool DCObject::loadThresholdsFromDB()
+bool DCObject::loadThresholdsFromDB(DB_HANDLE hdb)
 {
        return true;
 }
index f14cada..a8b7747 100644 (file)
@@ -162,7 +162,7 @@ DCTable::DCTable(UINT32 id, const TCHAR *name, int source, int pollingInterval,
  *    status,system_tag,resource_id,proxy_node,perftab_settings,
  *    transformation_script,comments
  */
-DCTable::DCTable(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
+DCTable::DCTable(DB_HANDLE hdb, DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
 {
    m_id = DBGetFieldULong(hResult, iRow, 0);
    m_dwTemplateId = DBGetFieldULong(hResult, iRow, 1);
@@ -188,7 +188,7 @@ DCTable::DCTable(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
        m_columns = new ObjectArray<DCTableColumn>(8, 8, true);
        m_lastValue = NULL;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT column_name,flags,snmp_oid,display_name FROM dc_table_columns WHERE table_id=? ORDER BY sequence_number"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT column_name,flags,snmp_oid,display_name FROM dc_table_columns WHERE table_id=? ORDER BY sequence_number"));
        if (hStmt != NULL)
        {
                DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -203,10 +203,10 @@ DCTable::DCTable(DB_RESULT hResult, int iRow, Template *pNode) : DCObject()
                DBFreeStatement(hStmt);
        }
 
-       loadCustomSchedules();
+       loadCustomSchedules(hdb);
 
    m_thresholds = new ObjectArray<DCTableThreshold>(0, 4, true);
-   loadThresholds();
+   loadThresholds(hdb);
 }
 
 /**
@@ -621,9 +621,9 @@ BOOL DCTable::saveToDB(DB_HANDLE hdb)
 /**
  * Load thresholds from database
  */
-bool DCTable::loadThresholds()
+bool DCTable::loadThresholds(DB_HANDLE hdb)
 {
-   DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT id,activation_event,deactivation_event FROM dct_thresholds WHERE table_id=? ORDER BY sequence_number"));
+   DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT id,activation_event,deactivation_event FROM dct_thresholds WHERE table_id=? ORDER BY sequence_number"));
    if (hStmt == NULL)
       return false;
 
@@ -634,7 +634,7 @@ bool DCTable::loadThresholds()
       int count = DBGetNumRows(hResult);
       for(int i = 0; i < count; i++)
       {
-         DCTableThreshold *t = new DCTableThreshold(hResult, i);
+         DCTableThreshold *t = new DCTableThreshold(hdb, hResult, i);
          m_thresholds->add(t);
       }
       DBFreeResult(hResult);
index ab8e2de..570da52 100644 (file)
@@ -330,13 +330,13 @@ DCTableThreshold::DCTableThreshold(DCTableThreshold *src)
  * Create table threshold from database
  * Expected column order: id,activation_event,deactivation_event
  */
-DCTableThreshold::DCTableThreshold(DB_RESULT hResult, int row)
+DCTableThreshold::DCTableThreshold(DB_HANDLE hdb, DB_RESULT hResult, int row)
 {
    m_id = DBGetFieldLong(hResult, row, 0);
    m_activationEvent = DBGetFieldULong(hResult, row, 1);
    m_deactivationEvent = DBGetFieldULong(hResult, row, 2);
    m_groups = new ObjectArray<DCTableConditionGroup>(4, 4, true);
-   loadConditions();
+   loadConditions(hdb);
    m_activeKeys = new StringSet;
 }
 
@@ -388,9 +388,9 @@ DCTableThreshold::DCTableThreshold(ConfigEntry *e)
 /**
  * Load conditions from database
  */
-void DCTableThreshold::loadConditions()
+void DCTableThreshold::loadConditions(DB_HANDLE hdb)
 {
-   DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT group_id,column_name,check_operation,check_value FROM dct_threshold_conditions WHERE threshold_id=? ORDER BY group_id,sequence_number"));
+   DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT group_id,column_name,check_operation,check_value FROM dct_threshold_conditions WHERE threshold_id=? ORDER BY group_id,sequence_number"));
    if (hStmt == NULL)
       return;
 
index 37dfc7b..638911a 100644 (file)
@@ -57,10 +57,10 @@ BOOL Network::saveToDatabase(DB_HANDLE hdb)
 /**
  * Load properties from database
  */
-void Network::LoadFromDB()
+void Network::loadFromDatabase(DB_HANDLE hdb)
 {
-   loadCommonProperties();
-   loadACLFromDB();
+   loadCommonProperties(hdb);
+   loadACLFromDB(hdb);
 }
 
 /**
index b3d5183..16e83ab 100644 (file)
@@ -553,7 +553,7 @@ void EPRule::generateAlarm(Event *pEvent)
 /**
  * Load rule from database
  */
-bool EPRule::loadFromDB()
+bool EPRule::loadFromDB(DB_HANDLE hdb)
 {
    DB_RESULT hResult;
    TCHAR szQuery[256], name[MAX_DB_STRING], value[MAX_DB_STRING];
@@ -562,7 +562,7 @@ bool EPRule::loadFromDB()
 
    // Load rule's sources
    _sntprintf(szQuery, 256, _T("SELECT object_id FROM policy_source_list WHERE rule_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       m_dwNumSources = DBGetNumRows(hResult);
@@ -578,7 +578,7 @@ bool EPRule::loadFromDB()
 
    // Load rule's events
    _sntprintf(szQuery, 256, _T("SELECT event_code FROM policy_event_list WHERE rule_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       m_dwNumEvents = DBGetNumRows(hResult);
@@ -594,7 +594,7 @@ bool EPRule::loadFromDB()
 
    // Load rule's actions
    _sntprintf(szQuery, 256, _T("SELECT action_id FROM policy_action_list WHERE rule_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       m_dwNumActions = DBGetNumRows(hResult);
@@ -610,7 +610,7 @@ bool EPRule::loadFromDB()
 
    // Load situation attributes
    _sntprintf(szQuery, 256, _T("SELECT attr_name,attr_value FROM policy_situation_attr_list WHERE rule_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       count = DBGetNumRows(hResult);
@@ -783,10 +783,11 @@ bool EventPolicy::loadFromDB()
    DB_RESULT hResult;
    bool bSuccess = false;
 
-   hResult = DBSelect(g_hCoreDB, _T("SELECT rule_id,rule_guid,flags,comments,alarm_message,")
-                                 _T("alarm_severity,alarm_key,script,alarm_timeout,alarm_timeout_event,")
-                                                                                       _T("situation_id,situation_instance ")
-                                 _T("FROM event_policy ORDER BY rule_id"));
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT rule_id,rule_guid,flags,comments,alarm_message,")
+                           _T("alarm_severity,alarm_key,script,alarm_timeout,alarm_timeout_event,")
+                               _T("situation_id,situation_instance ")
+                           _T("FROM event_policy ORDER BY rule_id"));
    if (hResult != NULL)
    {
       UINT32 i;
@@ -797,11 +798,12 @@ bool EventPolicy::loadFromDB()
       for(i = 0; i < m_dwNumRules; i++)
       {
          m_ppRuleList[i] = new EPRule(hResult, i);
-         bSuccess = bSuccess && m_ppRuleList[i]->loadFromDB();
+         bSuccess = bSuccess && m_ppRuleList[i]->loadFromDB(hdb);
       }
       DBFreeResult(hResult);
    }
 
+   DBConnectionPoolReleaseConnection(hdb);
    return bSuccess;
 }
 
index faa5d17..7660ce9 100644 (file)
@@ -150,10 +150,12 @@ GRAPH_ACL_AND_ID IsGraphNameExists(const TCHAR *graphName)
    GRAPH_ACL_AND_ID result;
    result.graphId = 0;
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Check existence and access rights
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT graph_id FROM graphs WHERE name=%s"), 
-              (const TCHAR *)DBPrepareString(g_hCoreDB, graphName));
-   hResult = DBSelect(g_hCoreDB, szQuery);
+              (const TCHAR *)DBPrepareString(hdb, graphName));
+   hResult = DBSelect(hdb, szQuery);
 
    if (hResult != NULL)
    {
@@ -172,5 +174,7 @@ GRAPH_ACL_AND_ID IsGraphNameExists(const TCHAR *graphName)
    {
       result.status = RCC_DB_FAILURE;
    }
+
+   DBConnectionPoolReleaseConnection(hdb);
    return result;
 }
index ed7f05c..d26a47a 100644 (file)
@@ -83,11 +83,13 @@ BOOL InitIdTable()
 
    s_mutexTableAccess = MutexCreate();
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Get first available network object ID
        UINT32 id = ConfigReadULong(_T("FirstFreeObjectId"), s_freeIdTable[IDG_NETWORK_OBJECT]);
        if (id > s_freeIdTable[IDG_NETWORK_OBJECT])
                s_freeIdTable[IDG_NETWORK_OBJECT] = id;
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM nodes"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM nodes"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -95,7 +97,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM subnets"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM subnets"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -103,7 +105,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM interfaces"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM interfaces"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -111,7 +113,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM containers"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM containers"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -119,7 +121,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM templates"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM templates"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -127,7 +129,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM network_services"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM network_services"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -135,7 +137,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM conditions"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM conditions"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -143,7 +145,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM clusters"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM clusters"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -151,7 +153,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM ap_common"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM ap_common"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -159,7 +161,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM network_maps"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM network_maps"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -167,7 +169,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM dashboards"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM dashboards"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -175,7 +177,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM slm_checks"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM slm_checks"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -183,7 +185,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM mobile_devices"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM mobile_devices"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -191,7 +193,7 @@ BOOL InitIdTable()
                                                    DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM access_points"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM access_points"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -201,7 +203,7 @@ BOOL InitIdTable()
    }
 
    // Get first available container category id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(category) FROM container_categories"));
+   hResult = DBSelect(hdb, _T("SELECT max(category) FROM container_categories"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -210,7 +212,7 @@ BOOL InitIdTable()
    }
 
    // Get first available event code
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(event_code) FROM event_cfg"));
+   hResult = DBSelect(hdb, _T("SELECT max(event_code) FROM event_cfg"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -219,14 +221,14 @@ BOOL InitIdTable()
    }
 
    // Get first available data collection object id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(item_id) FROM items"));
+   hResult = DBSelect(hdb, _T("SELECT max(item_id) FROM items"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
          s_freeIdTable[IDG_ITEM] = max(s_freeIdTable[IDG_ITEM], DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(item_id) FROM dc_tables"));
+   hResult = DBSelect(hdb, _T("SELECT max(item_id) FROM dc_tables"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -235,7 +237,7 @@ BOOL InitIdTable()
    }
 
    // Get first available server job id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM job_history"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM job_history"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -244,7 +246,7 @@ BOOL InitIdTable()
    }
 
    // Get first available SNMP trap configuration record id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(trap_id) FROM snmp_trap_cfg"));
+   hResult = DBSelect(hdb, _T("SELECT max(trap_id) FROM snmp_trap_cfg"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -253,7 +255,7 @@ BOOL InitIdTable()
    }
 
    // Get first available action id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(action_id) FROM actions"));
+   hResult = DBSelect(hdb, _T("SELECT max(action_id) FROM actions"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -262,7 +264,7 @@ BOOL InitIdTable()
    }
 
    // Get first available event group id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM event_groups"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM event_groups"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -271,7 +273,7 @@ BOOL InitIdTable()
    }
 
    // Get first available threshold id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(threshold_id) FROM thresholds"));
+   hResult = DBSelect(hdb, _T("SELECT max(threshold_id) FROM thresholds"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -279,7 +281,7 @@ BOOL InitIdTable()
                                               DBGetFieldULong(hResult, 0, 0) + 1);
       DBFreeResult(hResult);
    }
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM dct_thresholds"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM dct_thresholds"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -289,7 +291,7 @@ BOOL InitIdTable()
    }
 
    // Get first available user id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM users"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM users"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -299,7 +301,7 @@ BOOL InitIdTable()
    }
 
    // Get first available user group id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM user_groups"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM user_groups"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -309,7 +311,7 @@ BOOL InitIdTable()
    }
 
    // Get first available alarm id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(alarm_id) FROM alarms"));
+   hResult = DBSelect(hdb, _T("SELECT max(alarm_id) FROM alarms"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -319,7 +321,7 @@ BOOL InitIdTable()
    }
 
    // Get first available alarm note id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(note_id) FROM alarm_notes"));
+   hResult = DBSelect(hdb, _T("SELECT max(note_id) FROM alarm_notes"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -329,7 +331,7 @@ BOOL InitIdTable()
    }
 
    // Get first available event identifier
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(event_id) FROM event_log"));
+   hResult = DBSelect(hdb, _T("SELECT max(event_id) FROM event_log"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -338,7 +340,7 @@ BOOL InitIdTable()
    }
 
    // Get first available package id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(pkg_id) FROM agent_pkg"));
+   hResult = DBSelect(hdb, _T("SELECT max(pkg_id) FROM agent_pkg"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -348,7 +350,7 @@ BOOL InitIdTable()
    }
 
    // Get first available object tool id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(tool_id) FROM object_tools"));
+   hResult = DBSelect(hdb, _T("SELECT max(tool_id) FROM object_tools"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -358,7 +360,7 @@ BOOL InitIdTable()
    }
 
    // Get first available script id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(script_id) FROM script_library"));
+   hResult = DBSelect(hdb, _T("SELECT max(script_id) FROM script_library"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -368,7 +370,7 @@ BOOL InitIdTable()
    }
 
    // Get first available agent config id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(config_id) FROM agent_configs"));
+   hResult = DBSelect(hdb, _T("SELECT max(config_id) FROM agent_configs"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -378,7 +380,7 @@ BOOL InitIdTable()
    }
 
    // Get first available graph id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(graph_id) FROM graphs"));
+   hResult = DBSelect(hdb, _T("SELECT max(graph_id) FROM graphs"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -388,7 +390,7 @@ BOOL InitIdTable()
    }
 
    // Get first available certificate id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(cert_id) FROM certificates"));
+   hResult = DBSelect(hdb, _T("SELECT max(cert_id) FROM certificates"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -398,7 +400,7 @@ BOOL InitIdTable()
    }
 
    // Get first available situation id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM situations"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM situations"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -408,7 +410,7 @@ BOOL InitIdTable()
    }
 
    // Get first available SLM ticket id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(ticket_id) FROM slm_tickets"));
+   hResult = DBSelect(hdb, _T("SELECT max(ticket_id) FROM slm_tickets"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -418,7 +420,7 @@ BOOL InitIdTable()
    }
 
    // Get first available data collection table column id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(column_id) FROM dct_column_names"));
+   hResult = DBSelect(hdb, _T("SELECT max(column_id) FROM dct_column_names"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -428,7 +430,7 @@ BOOL InitIdTable()
    }
 
    // Get first available mapping table id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM mapping_tables"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM mapping_tables"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -438,7 +440,7 @@ BOOL InitIdTable()
    }
 
    // Get first available DCI summary table id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM dci_summary_tables"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM dci_summary_tables"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -448,7 +450,7 @@ BOOL InitIdTable()
    }
 
    // Get first available scheduled_tasks id
-   hResult = DBSelect(g_hCoreDB, _T("SELECT max(id) FROM scheduled_tasks"));
+   hResult = DBSelect(hdb, _T("SELECT max(id) FROM scheduled_tasks"));
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -457,6 +459,7 @@ BOOL InitIdTable()
       DBFreeResult(hResult);
    }
 
+   DBConnectionPoolReleaseConnection(hdb);
    return TRUE;
 }
 
index 484fcd0..f0ab323 100644 (file)
@@ -163,30 +163,30 @@ UINT32 Interface::getPingTime()
 /**
  * Create object from database record
  */
-BOOL Interface::loadFromDatabase(UINT32 dwId)
+bool Interface::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
-   BOOL bResult = FALSE;
+   bool bResult = false;
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
+       DB_STATEMENT hStmt = DBPrepare(hdb,
                _T("SELECT if_type,if_index,node_id,")
                _T("mac_addr,flags,required_polls,bridge_port,phy_slot,")
                _T("phy_port,peer_node_id,peer_if_id,description,")
                _T("dot1x_pae_state,dot1x_backend_state,admin_state,")
       _T("oper_state,peer_proto,alias,mtu,speed,iftable_suffix FROM interfaces WHERE id=?"));
        if (hStmt == NULL)
-               return FALSE;
+               return false;
        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
 
        DB_RESULT hResult = DBSelectPrepared(hStmt);
    if (hResult == NULL)
        {
                DBFreeStatement(hStmt);
-      return FALSE;     // Query failed
+      return false;     // Query failed
        }
 
    if (DBGetNumRows(hResult) != 0)
@@ -215,7 +215,7 @@ BOOL Interface::loadFromDatabase(UINT32 dwId)
       TCHAR suffixText[128];
       DBGetField(hResult, 0, 20, suffixText, 128);
       StrStrip(suffixText);
-      if (suffixText[0] = 0)
+      if (suffixText[0] == 0)
       {
          UINT32 suffix[16];
          size_t l = SNMPParseOID(suffixText, suffix, 16);
@@ -246,12 +246,12 @@ BOOL Interface::loadFromDatabase(UINT32 dwId)
             object->AddChild(this);
             AddParent(object);
                                m_zoneId = ((Node *)object)->getZoneId();
-            bResult = TRUE;
+            bResult = true;
          }
       }
       else
       {
-         bResult = TRUE;
+         bResult = true;
       }
    }
 
@@ -259,7 +259,7 @@ BOOL Interface::loadFromDatabase(UINT32 dwId)
        DBFreeStatement(hStmt);
 
    // Read IP addresses
-   hStmt = DBPrepare(g_hCoreDB, _T("SELECT ip_addr,ip_netmask FROM interface_address_list WHERE iface_id = ?"));
+   hStmt = DBPrepare(hdb, _T("SELECT ip_addr,ip_netmask FROM interface_address_list WHERE iface_id = ?"));
    if (hStmt != NULL)
    {
       DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -280,7 +280,7 @@ BOOL Interface::loadFromDatabase(UINT32 dwId)
    }
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
        // Validate loopback flag
        if (m_type == IFTYPE_SOFTWARE_LOOPBACK)
index 40d9f69..0bc274b 100644 (file)
@@ -132,7 +132,6 @@ TCHAR NXCORE_EXPORTABLE g_szListenAddress[MAX_PATH] = _T("*");
 #ifndef _WIN32
 TCHAR NXCORE_EXPORTABLE g_szPIDFile[MAX_PATH] = _T("/var/run/netxmsd.pid");
 #endif
-DB_HANDLE g_hCoreDB = 0;
 UINT32 g_dwDiscoveryPollingInterval;
 UINT32 g_dwStatusPollingInterval;
 UINT32 g_dwConfigurationPollingInterval;
@@ -189,8 +188,7 @@ bool NXCORE_EXPORTABLE SleepAndCheckForShutdown(int seconds)
  */
 void NXCORE_EXPORTABLE ShutdownDB()
 {
-       if (g_hCoreDB != NULL)
-               DBDisconnect(g_hCoreDB);
+   DBConnectionPoolShutdown();
        DBUnloadDriver(g_dbDriver);
 }
 
@@ -294,8 +292,6 @@ static void LoadGlobalConfig()
                g_flags |= AF_ENABLE_ZONING;
        if (ConfigReadInt(_T("EnableObjectTransactions"), 0))
                g_flags |= AF_ENABLE_OBJECT_TRANSACTIONS;
-       if (ConfigReadInt(_T("EnableMultipleDBConnections"), 1))
-               g_flags |= AF_ENABLE_MULTIPLE_DB_CONN;
        if (ConfigReadInt(_T("RunNetworkDiscovery"), 0))
                g_flags |= AF_ENABLE_NETWORK_DISCOVERY;
        if (ConfigReadInt(_T("ActiveNetworkDiscovery"), 0))
@@ -608,15 +604,16 @@ BOOL NXCORE_EXPORTABLE Initialize()
                return FALSE;
 
        // Connect to database
+       DB_HANDLE hdbBootstrap = NULL;
        TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
        for(i = 0; ; i++)
        {
-               g_hCoreDB = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
-               if ((g_hCoreDB != NULL) || (i == 5))
+          hdbBootstrap = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
+               if ((hdbBootstrap != NULL) || (i == 5))
                        break;
                ThreadSleep(5);
        }
-       if (g_hCoreDB == NULL)
+       if (hdbBootstrap == NULL)
        {
                nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
                return FALSE;
@@ -624,26 +621,33 @@ BOOL NXCORE_EXPORTABLE Initialize()
        DbgPrintf(1, _T("Successfully connected to database %s@%s"), g_szDbName, g_szDbServer);
 
        // Check database version
-       iDBVersion = DBGetSchemaVersion(g_hCoreDB);
+       iDBVersion = DBGetSchemaVersion(hdbBootstrap);
        if (iDBVersion != DB_FORMAT_VERSION)
        {
                nxlog_write(MSG_WRONG_DB_VERSION, EVENTLOG_ERROR_TYPE, "dd", iDBVersion, DB_FORMAT_VERSION);
+               DBDisconnect(hdbBootstrap);
                return FALSE;
        }
 
        // Read database syntax
-       g_dbSyntax = DBGetSyntax(g_hCoreDB);
+       g_dbSyntax = DBGetSyntax(hdbBootstrap);
    if (g_dbSyntax == DB_SYNTAX_ORACLE)
    {
       DBSetSessionInitCallback(OracleSessionInitCallback);
    }
 
-       int baseSize = ConfigReadInt(_T("ConnectionPoolBaseSize"), 5);
-       int maxSize = ConfigReadInt(_T("ConnectionPoolMaxSize"), 20);
-       int cooldownTime = ConfigReadInt(_T("ConnectionPoolCooldownTime"), 300);
-       int ttl = ConfigReadInt(_T("ConnectionPoolMaxLifetime"), 60*30);
-       DBConnectionPoolStartup(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, baseSize, maxSize, cooldownTime, ttl);
-   g_flags |= AF_DB_CONNECTION_POOL_READY;
+       int baseSize = ConfigReadIntEx(hdbBootstrap, _T("DBConnectionPoolBaseSize"), 10);
+       int maxSize = ConfigReadIntEx(hdbBootstrap, _T("DBConnectionPoolMaxSize"), 30);
+       int cooldownTime = ConfigReadIntEx(hdbBootstrap, _T("DBConnectionPoolCooldownTime"), 300);
+       int ttl = ConfigReadIntEx(hdbBootstrap, _T("DBConnectionPoolMaxLifetime"), 14400);
+
+   DBDisconnect(hdbBootstrap);
+
+       if (!DBConnectionPoolStartup(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, baseSize, maxSize, cooldownTime, ttl))
+       {
+      nxlog_write(MSG_DBCONNPOOL_INIT_FAILED, EVENTLOG_ERROR_TYPE, NULL);
+          return FALSE;
+       }
 
    UINT32 lrt = ConfigReadULong(_T("LongRunningQueryThreshold"), 0);
    if (lrt != 0)
@@ -728,7 +732,9 @@ retry_db_lock:
        DbgPrintf(2, _T("ID table created"));
 
        // Update status for unfinished jobs in job history
-       DBQuery(g_hCoreDB, _T("UPDATE job_history SET status=4,failure_message='Aborted due to server shutdown or crash' WHERE status NOT IN (3,4,5)"));
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       DBQuery(hdb, _T("UPDATE job_history SET status=4,failure_message='Aborted due to server shutdown or crash' WHERE status NOT IN (3,4,5)"));
+       DBConnectionPoolReleaseConnection(hdb);
 
        // Load and compile scripts
        LoadScripts();
@@ -939,10 +945,13 @@ void NXCORE_EXPORTABLE Shutdown()
                        g_pModuleList[i].pfShutdown();
        }
 
-       SaveObjects(g_hCoreDB);
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       SaveObjects(hdb);
        DbgPrintf(2, _T("All objects saved to database"));
-       SaveUsers(g_hCoreDB);
+       SaveUsers(hdb);
        DbgPrintf(2, _T("All users saved to database"));
+       DBConnectionPoolReleaseConnection(hdb);
+
        StopDBWriter();
        DbgPrintf(1, _T("Database writer stopped"));
 
@@ -952,11 +961,6 @@ void NXCORE_EXPORTABLE Shutdown()
        UnlockDB();
 
        DBConnectionPoolShutdown();
-
-       // Disconnect from database and unload driver
-       if (g_hCoreDB != NULL)
-               DBDisconnect(g_hCoreDB);
-
        DBUnloadDriver(g_dbDriver);
        DbgPrintf(1, _T("Database driver unloaded"));
 
@@ -994,12 +998,14 @@ void NXCORE_EXPORTABLE FastShutdown()
        g_flags |= AF_SHUTDOWN;     // Set shutdown flag
        ConditionSet(m_condShutdown);
 
-       SaveObjects(g_hCoreDB);
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       SaveObjects(hdb);
        DbgPrintf(2, _T("All objects saved to database"));
-       SaveUsers(g_hCoreDB);
+       SaveUsers(hdb);
        DbgPrintf(2, _T("All users saved to database"));
+       DBConnectionPoolReleaseConnection(hdb);
 
-       // Remove database lock first, because we have a chance to loose DB connection
+       // Remove database lock first, because we have a chance to lose DB connection
        UnlockDB();
 
        // Stop database writers
@@ -1432,7 +1438,6 @@ int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx)
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CATCH_EXCEPTIONS));
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_HELPDESK_LINK_ACTIVE));
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_LOCKED));
-                       ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_MULTIPLE_DB_CONN));
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_CONNECTION_LOST));
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_NO_NETWORK_CONNECTIVITY));
                        ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_EVENT_STORM_DETECTED));
index dd61743..83866f9 100644 (file)
@@ -70,21 +70,21 @@ MobileDevice::~MobileDevice()
 /**
  * Create object from database data
  */
-BOOL MobileDevice::loadFromDatabase(UINT32 dwId)
+bool MobileDevice::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    m_id = dwId;
 
-   if (!loadCommonProperties())
+   if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for mobile device object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
        TCHAR query[256];
        _sntprintf(query, 256, _T("SELECT device_id,vendor,model,serial_number,os_name,os_version,user_id,battery_level FROM mobile_devices WHERE id=%d"), (int)m_id);
-       DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+       DB_RESULT hResult = DBSelect(hdb, query);
        if (hResult == NULL)
-               return FALSE;
+               return false;
 
        m_deviceId = DBGetField(hResult, 0, 0, NULL, 0);
        m_vendor = DBGetField(hResult, 0, 1, NULL, 0);
@@ -97,13 +97,13 @@ BOOL MobileDevice::loadFromDatabase(UINT32 dwId)
        DBFreeResult(hResult);
 
    // Load DCI and access list
-   loadACLFromDB();
-   loadItemsFromDB();
+   loadACLFromDB(hdb);
+   loadItemsFromDB(hdb);
    for(int i = 0; i < m_dcObjects->size(); i++)
-      if (!m_dcObjects->get(i)->loadThresholdsFromDB())
-         return FALSE;
+      if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
+         return false;
 
-   return TRUE;
+   return true;
 }
 
 /**
index 2a04ddf..b9eddba 100644 (file)
@@ -56,12 +56,10 @@ MappingTable *MappingTable::createFromMessage(NXCPMessage *msg)
 /**
  * Create mapping table object from database
  */
-MappingTable *MappingTable::createFromDatabase(LONG id)
+MappingTable *MappingTable::createFromDatabase(DB_HANDLE hdb, LONG id)
 {
        MappingTable *mt = NULL;
 
-       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
-
        DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT name,flags,description FROM mapping_tables WHERE id=?"));
        if (hStmt != NULL)
        {
@@ -108,7 +106,6 @@ MappingTable *MappingTable::createFromDatabase(LONG id)
                }
        }
 
-       DBConnectionPoolReleaseConnection(hdb);
        return mt;
 }
 
@@ -316,18 +313,23 @@ void InitMappingTables()
 {
        s_mappingTablesLock = RWLockCreate();
 
-       DB_RESULT hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM mapping_tables"));
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       DB_RESULT hResult = DBSelect(hdb, _T("SELECT id FROM mapping_tables"));
        if (hResult == NULL)
+       {
+          DBConnectionPoolReleaseConnection(hdb);
                return;
+       }
 
        int count = DBGetNumRows(hResult);
        for(int i = 0; i < count; i++)
        {
-               MappingTable *mt = MappingTable::createFromDatabase(DBGetFieldLong(hResult, i, 0));
+               MappingTable *mt = MappingTable::createFromDatabase(hdb, DBGetFieldLong(hResult, i, 0));
                if (mt != NULL)
                        s_mappingTables.add(mt);
        }
        DBFreeResult(hResult);
+       DBConnectionPoolReleaseConnection(hdb);
        DbgPrintf(2, _T("%d mapping tables loaded"), s_mappingTables.size());
 }
 
index 2ecee49..98bf42a 100644 (file)
@@ -349,26 +349,26 @@ bool NetworkMap::deleteFromDatabase(DB_HANDLE hdb)
 /**
  * Load from database
  */
-BOOL NetworkMap::loadFromDatabase(UINT32 dwId)
+bool NetworkMap::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
        m_id = dwId;
 
-       if (!loadCommonProperties())
+       if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for network map object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
    if (!m_isDeleted)
    {
                TCHAR query[256];
 
-          loadACLFromDB();
+          loadACLFromDB(hdb);
 
                _sntprintf(query, 256, _T("SELECT map_type,layout,seed,radius,background,bg_latitude,bg_longitude,bg_zoom,flags,link_color,link_routing,bg_color,object_display_mode,filter FROM network_maps WHERE id=%d"), dwId);
-               DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+               DB_RESULT hResult = DBSelect(hdb, query);
                if (hResult == NULL)
-                       return FALSE;
+                       return false;
 
                m_mapType = DBGetFieldLong(hResult, 0, 0);
                m_layout = DBGetFieldLong(hResult, 0, 1);
@@ -392,7 +392,7 @@ BOOL NetworkMap::loadFromDatabase(UINT32 dwId)
 
           // Load elements
       _sntprintf(query, 256, _T("SELECT element_id,element_type,element_data,flags FROM network_map_elements WHERE map_id=%d"), m_id);
-      hResult = DBSelect(g_hCoreDB, query);
+      hResult = DBSelect(hdb, query);
       if (hResult != NULL)
       {
          int count = DBGetNumRows(hResult);
@@ -446,7 +446,7 @@ BOOL NetworkMap::loadFromDatabase(UINT32 dwId)
 
                // Load links
       _sntprintf(query, 256, _T("SELECT element1,element2,link_type,link_name,connector_name1,connector_name2,element_data,flags FROM network_map_links WHERE map_id=%d"), m_id);
-      hResult = DBSelect(g_hCoreDB, query);
+      hResult = DBSelect(hdb, query);
       if (hResult != NULL)
       {
          int count = DBGetNumRows(hResult);
@@ -468,7 +468,7 @@ BOOL NetworkMap::loadFromDatabase(UINT32 dwId)
 
        m_iStatus = STATUS_NORMAL;
 
-       return TRUE;
+       return true;
 }
 
 /**
index 7c9acf4..930f667 100644 (file)
@@ -94,9 +94,9 @@ NetObj::~NetObj()
 /**
  * Create object from database data
  */
-BOOL NetObj::loadFromDatabase(UINT32 dwId)
+bool NetObj::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
-   return FALSE;     // Abstract objects cannot be loaded from database
+   return false;     // Abstract objects cannot be loaded from database
 }
 
 /**
@@ -163,12 +163,12 @@ bool NetObj::deleteFromDatabase(DB_HANDLE hdb)
 /**
  * Load common object properties from database
  */
-bool NetObj::loadCommonProperties()
+bool NetObj::loadCommonProperties(DB_HANDLE hdb)
 {
    bool success = false;
 
    // Load access options
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
+       DB_STATEMENT hStmt = DBPrepare(hdb,
                                  _T("SELECT name,status,is_deleted,")
                              _T("inherit_access_rights,last_modified,status_calc_alg,")
                              _T("status_prop_alg,status_fixed_val,status_shift,")
@@ -241,7 +241,7 @@ bool NetObj::loadCommonProperties()
        // Load custom attributes
        if (success)
        {
-               hStmt = DBPrepare(g_hCoreDB, _T("SELECT attr_name,attr_value FROM object_custom_attributes WHERE object_id=?"));
+               hStmt = DBPrepare(hdb, _T("SELECT attr_name,attr_value FROM object_custom_attributes WHERE object_id=?"));
                if (hStmt != NULL)
                {
                        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -281,7 +281,7 @@ bool NetObj::loadCommonProperties()
    // Load associated dashboards
    if (success)
    {
-      hStmt = DBPrepare(g_hCoreDB, _T("SELECT dashboard_id FROM dashboard_associations WHERE object_id=?"));
+      hStmt = DBPrepare(hdb, _T("SELECT dashboard_id FROM dashboard_associations WHERE object_id=?"));
       if (hStmt != NULL)
       {
          DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -308,7 +308,7 @@ bool NetObj::loadCommonProperties()
    }
 
        if (success)
-               success = loadTrustedNodes();
+               success = loadTrustedNodes(hdb);
 
        if (!success)
                DbgPrintf(4, _T("NetObj::loadCommonProperties() failed for object %s [%ld] class=%d"), m_name, (long)m_id, getObjectClass());
@@ -881,11 +881,11 @@ void NetObj::calculateCompoundStatus(BOOL bForcedRecalc)
 /**
  * Load ACL from database
  */
-bool NetObj::loadACLFromDB()
+bool NetObj::loadACLFromDB(DB_HANDLE hdb)
 {
    bool success = false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT user_id,access_rights FROM acl WHERE object_id=?"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT user_id,access_rights FROM acl WHERE object_id=?"));
        if (hStmt != NULL)
        {
                DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -1595,14 +1595,14 @@ void NetObj::commentsToMessage(NXCPMessage *pMsg)
 /**
  * Load trusted nodes list from database
  */
-bool NetObj::loadTrustedNodes()
+bool NetObj::loadTrustedNodes(DB_HANDLE hdb)
 {
        DB_RESULT hResult;
        TCHAR query[256];
        int i, count;
 
        _sntprintf(query, 256, _T("SELECT target_node_id FROM trusted_nodes WHERE source_object_id=%d"), m_id);
-       hResult = DBSelect(g_hCoreDB, query);
+       hResult = DBSelect(hdb, query);
        if (hResult != NULL)
        {
                count = DBGetNumRows(hResult);
@@ -1958,11 +1958,13 @@ bool NetObj::isLocationTableExists()
 {
    TCHAR table[256];
    _sntprintf(table, 256, _T("gps_history_%d"), m_id);
-   int rc = DBIsTableExist(g_hCoreDB, table);
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   int rc = DBIsTableExist(hdb, table);
    if (rc == DBIsTableExist_Failure)
    {
       _tprintf(_T("WARNING: call to DBIsTableExist(\"%s\") failed\n"), table);
    }
+   DBConnectionPoolReleaseConnection(hdb);
    return rc != DBIsTableExist_NotFound;
 }
 
index b1d3ca8..4ac2d77 100644 (file)
@@ -130,25 +130,25 @@ BOOL NetworkService::saveToDatabase(DB_HANDLE hdb)
 /**
  * Load properties from database
  */
-BOOL NetworkService::loadFromDatabase(UINT32 dwId)
+bool NetworkService::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    TCHAR szQuery[256];
    DB_RESULT hResult;
    UINT32 dwHostNodeId;
    NetObj *pObject;
-   BOOL bResult = FALSE;
+   bool bResult = false;
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
    _sntprintf(szQuery, 256, _T("SELECT node_id,service_type,")
                                _T("ip_bind_addr,ip_proto,ip_port,check_request,check_responce,")
                                _T("poller_node_id,required_polls FROM network_services WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    if (DBGetNumRows(hResult) != 0)
    {
@@ -180,7 +180,7 @@ BOOL NetworkService::loadFromDatabase(UINT32 dwId)
             m_hostNode = (Node *)pObject;
             pObject->AddChild(this);
             AddParent(pObject);
-            bResult = TRUE;
+            bResult = true;
          }
 
          // Check that polling node ID is valid
@@ -189,27 +189,26 @@ BOOL NetworkService::loadFromDatabase(UINT32 dwId)
             pObject = FindObjectById(m_pollerNode);
             if (pObject == NULL)
             {
-               nxlog_write(MSG_INVALID_NODE_ID_EX, EVENTLOG_ERROR_TYPE,
-                        "dds", dwId, m_pollerNode, _T("network service"));
-               bResult = FALSE;
+               nxlog_write(MSG_INVALID_NODE_ID_EX, EVENTLOG_ERROR_TYPE, "dds", dwId, m_pollerNode, _T("network service"));
+               bResult = false;
             }
             else if (pObject->getObjectClass() != OBJECT_NODE)
             {
                nxlog_write(MSG_NODE_NOT_NODE, EVENTLOG_ERROR_TYPE, "dd", dwId, m_pollerNode);
-               bResult = FALSE;
+               bResult = false;
             }
          }
       }
       else
       {
-         bResult = TRUE;
+         bResult = true;
       }
    }
 
    DBFreeResult(hResult);
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
    return bResult;
 }
index ec9f75d..0f327e5 100644 (file)
@@ -232,22 +232,22 @@ Node::~Node()
 /**
  * Create object from database data
  */
-BOOL Node::loadFromDatabase(UINT32 dwId)
+bool Node::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    int i, iNumRows;
    UINT32 dwSubnetId;
    NetObj *pObject;
-   BOOL bResult = FALSE;
+   bool bResult = false;
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
+   if (!loadCommonProperties(hdb))
    {
       DbgPrintf(2, _T("Cannot load common properties for node object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
+       DB_STATEMENT hStmt = DBPrepare(hdb,
                _T("SELECT primary_name,primary_ip,node_flags,")
       _T("snmp_version,auth_method,secret,")
       _T("agent_port,status_poll_type,snmp_oid,agent_version,")
@@ -260,14 +260,14 @@ BOOL Node::loadFromDatabase(UINT32 dwId)
       _T("rack_id,rack_image,rack_position,rack_height,")
       _T("last_agent_comm_time FROM nodes WHERE id=?"));
        if (hStmt == NULL)
-               return FALSE;
+               return false;
 
        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, dwId);
        DB_RESULT hResult = DBSelectPrepared(hStmt);
    if (hResult == NULL)
        {
                DBFreeStatement(hStmt);
-      return FALSE;     // Query failed
+      return false;     // Query failed
        }
 
    if (DBGetNumRows(hResult) == 0)
@@ -275,7 +275,7 @@ BOOL Node::loadFromDatabase(UINT32 dwId)
       DBFreeResult(hResult);
                DBFreeStatement(hStmt);
       DbgPrintf(2, _T("Missing record in \"nodes\" table for node object %d"), dwId);
-      return FALSE;
+      return false;
    }
 
    DBGetField(hResult, 0, 0, m_primaryName, MAX_DNS_NAME);
@@ -348,16 +348,16 @@ BOOL Node::loadFromDatabase(UINT32 dwId)
    if (!m_isDeleted)
    {
       // Link node to subnets
-               hStmt = DBPrepare(g_hCoreDB, _T("SELECT subnet_id FROM nsmap WHERE node_id=?"));
+               hStmt = DBPrepare(hdb, _T("SELECT subnet_id FROM nsmap WHERE node_id=?"));
                if (hStmt == NULL)
-                       return FALSE;
+                       return false;
 
                DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
       hResult = DBSelectPrepared(hStmt);
       if (hResult == NULL)
                {
                        DBFreeStatement(hStmt);
-         return FALSE;     // Query failed
+         return false;     // Query failed
                }
 
       iNumRows = DBGetNumRows(hResult);
@@ -385,18 +385,18 @@ BOOL Node::loadFromDatabase(UINT32 dwId)
       DBFreeResult(hResult);
                DBFreeStatement(hStmt);
 
-               loadItemsFromDB();
-      loadACLFromDB();
+               loadItemsFromDB(hdb);
+      loadACLFromDB(hdb);
 
       // Walk through all items in the node and load appropriate thresholds
-               bResult = TRUE;
+               bResult = true;
       for(i = 0; i < m_dcObjects->size(); i++)
       {
-         if (!m_dcObjects->get(i)->loadThresholdsFromDB())
+         if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
          {
             DbgPrintf(3, _T("Cannot load thresholds for DCI %d of node %d (%s)"),
                       m_dcObjects->get(i)->getId(), dwId, m_name);
-            bResult = FALSE;
+            bResult = false;
          }
       }
 
@@ -404,7 +404,7 @@ BOOL Node::loadFromDatabase(UINT32 dwId)
    }
    else
    {
-      bResult = TRUE;
+      bResult = true;
    }
 
    return bResult;
index 3b1fb58..bfe3004 100644 (file)
@@ -51,19 +51,19 @@ NodeLink::~NodeLink()
 /**
  * Create object from database data
  */
-BOOL NodeLink::loadFromDatabase(UINT32 id)
+bool NodeLink::loadFromDatabase(DB_HANDLE hdb, UINT32 id)
 {
        const int script_length = 1024;
        m_id = id;
 
-       if (!ServiceContainer::loadFromDatabase(id))
-               return FALSE;
+       if (!ServiceContainer::loadFromDatabase(hdb, id))
+               return false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT node_id FROM node_links WHERE nodelink_id=?"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT node_id FROM node_links WHERE nodelink_id=?"));
        if (hStmt == NULL)
        {
                DbgPrintf(4, _T("Cannot prepare select from node_links"));
-               return FALSE;
+               return false;
        }
        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
 
@@ -71,7 +71,7 @@ BOOL NodeLink::loadFromDatabase(UINT32 id)
        if (hResult == NULL)
        {
                DBFreeStatement(hStmt);
-               return FALSE;
+               return false;
        }
 
        if (DBGetNumRows(hResult) == 0)
@@ -79,7 +79,7 @@ BOOL NodeLink::loadFromDatabase(UINT32 id)
                DBFreeResult(hResult);
                DBFreeStatement(hStmt);
                DbgPrintf(4, _T("Cannot load nodelink object %ld - record missing"), (long)m_id);
-               return FALSE;
+               return false;
        }
 
        m_nodeId        = DBGetFieldLong(hResult, 0, 0);
@@ -88,13 +88,13 @@ BOOL NodeLink::loadFromDatabase(UINT32 id)
                DBFreeResult(hResult);
                DBFreeStatement(hStmt);
                DbgPrintf(4, _T("Cannot load nodelink object %ld - node id is missing"), (long)m_id);
-               return FALSE;
+               return false;
        }
 
        DBFreeResult(hResult);
        DBFreeStatement(hStmt);
 
-       return TRUE;
+       return true;
 }
 
 /**
@@ -122,7 +122,7 @@ BOOL NodeLink::saveToDatabase(DB_HANDLE hdb)
        }
        DBFreeStatement(hStmt);
 
-       hStmt = DBPrepare(g_hCoreDB, bNewObject ? _T("INSERT INTO node_links (node_id,nodelink_id) VALUES (?,?)") :
+       hStmt = DBPrepare(hdb, bNewObject ? _T("INSERT INTO node_links (node_id,nodelink_id) VALUES (?,?)") :
                                                                                          _T("UPDATE node_links SET node_id=? WHERE nodelink_id=?"));
        if (hStmt == NULL)
        {
index d0bd1ab..d212eb2 100644 (file)
@@ -504,7 +504,8 @@ static BOOL AcceptNewNode(const InetAddress& addr, UINT32 zoneId, BYTE *macAddr)
                if (autoFilterFlags & DFF_ONLY_RANGE)
       {
                        DbgPrintf(4, _T("AcceptNewNode(%s): auto filter - checking range"), szIpAddr);
-         DB_RESULT hResult = DBSelect(g_hCoreDB, _T("SELECT addr_type,addr1,addr2 FROM address_lists WHERE list_type=2"));
+                       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+         DB_RESULT hResult = DBSelect(hdb, _T("SELECT addr_type,addr1,addr2 FROM address_lists WHERE list_type=2"));
          if (hResult != NULL)
          {
             int nRows = DBGetNumRows(hResult);
@@ -531,6 +532,7 @@ static BOOL AcceptNewNode(const InetAddress& addr, UINT32 zoneId, BYTE *macAddr)
             }
             DBFreeResult(hResult);
          }
+         DBConnectionPoolReleaseConnection(hdb);
                        DbgPrintf(4, _T("AcceptNewNode(%s): auto filter - range check result is %d"), szIpAddr, bResult);
                        if (!bResult)
                                return FALSE;
index 0066cad..4faa38b 100644 (file)
@@ -279,9 +279,11 @@ void NetObjInsert(NetObj *pObject, BOOL bNewObject)
          TCHAR szQuery[256], szQueryTemplate[256];
          UINT32 i;
 
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
          MetaDataReadStr(_T("IDataTableCreationCommand"), szQueryTemplate, 255, _T(""));
          _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), szQueryTemplate, pObject->getId());
-         DBQuery(g_hCoreDB, szQuery);
+         DBQuery(hdb, szQuery);
 
          for(i = 0; i < 10; i++)
          {
@@ -290,7 +292,7 @@ void NetObjInsert(NetObj *pObject, BOOL bNewObject)
             if (szQueryTemplate[0] != 0)
             {
                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), szQueryTemplate, pObject->getId(), pObject->getId());
-               DBQuery(g_hCoreDB, szQuery);
+               DBQuery(hdb, szQuery);
             }
          }
 
@@ -301,7 +303,7 @@ void NetObjInsert(NetObj *pObject, BOOL bNewObject)
             if (szQueryTemplate[0] != 0)
             {
                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), szQueryTemplate, pObject->getId(), pObject->getId());
-               DBQuery(g_hCoreDB, szQuery);
+               DBQuery(hdb, szQuery);
             }
          }
 
@@ -312,9 +314,11 @@ void NetObjInsert(NetObj *pObject, BOOL bNewObject)
             if (szQueryTemplate[0] != 0)
             {
                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), szQueryTemplate, pObject->getId(), pObject->getId());
-               DBQuery(g_hCoreDB, szQuery);
+               DBQuery(hdb, szQuery);
             }
          }
+
+         DBConnectionPoolReleaseConnection(hdb);
                }
    }
        g_idxObjectById.put(pObject->getId(), pObject);
@@ -1139,9 +1143,11 @@ BOOL LoadObjects()
    // Prevent objects to change it's modification flag
    g_bModificationsLocked = TRUE;
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Load container categories
    DbgPrintf(2, _T("Loading container categories..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT category,name,image_id,description FROM container_categories"));
+   hResult = DBSelect(hdb, _T("SELECT category,name,image_id,description FROM container_categories"));
    if (hResult != NULL)
    {
       g_dwNumCategories = DBGetNumRows(hResult);
@@ -1159,13 +1165,13 @@ BOOL LoadObjects()
 
    // Load built-in object properties
    DbgPrintf(2, _T("Loading built-in object properties..."));
-   g_pEntireNet->LoadFromDB();
-   g_pServiceRoot->LoadFromDB();
-   g_pTemplateRoot->LoadFromDB();
-       g_pPolicyRoot->LoadFromDB();
-       g_pMapRoot->LoadFromDB();
-       g_pDashboardRoot->LoadFromDB();
-       g_pBusinessServiceRoot->LoadFromDB();
+   g_pEntireNet->loadFromDatabase(hdb);
+   g_pServiceRoot->loadFromDatabase(hdb);
+   g_pTemplateRoot->loadFromDatabase(hdb);
+       g_pPolicyRoot->loadFromDatabase(hdb);
+       g_pMapRoot->loadFromDatabase(hdb);
+       g_pDashboardRoot->loadFromDatabase(hdb);
+       g_pBusinessServiceRoot->loadFromDatabase(hdb);
 
    // Load zones
    if (g_flags & AF_ENABLE_ZONING)
@@ -1177,11 +1183,11 @@ BOOL LoadObjects()
       // Load (or create) default zone
       pZone = new Zone;
       pZone->generateGuid();
-      pZone->loadFromDatabase(BUILTIN_OID_ZONE0);
+      pZone->loadFromDatabase(hdb, BUILTIN_OID_ZONE0);
       NetObjInsert(pZone, FALSE);
       g_pEntireNet->AddZone(pZone);
 
-      hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM zones WHERE id<>4"));
+      hResult = DBSelect(hdb, _T("SELECT id FROM zones WHERE id<>4"));
       if (hResult != 0)
       {
          dwNumRows = DBGetNumRows(hResult);
@@ -1189,7 +1195,7 @@ BOOL LoadObjects()
          {
             dwId = DBGetFieldULong(hResult, i, 0);
             pZone = new Zone;
-            if (pZone->loadFromDatabase(dwId))
+            if (pZone->loadFromDatabase(hdb, dwId))
             {
                if (!pZone->isDeleted())
                   g_pEntireNet->AddZone(pZone);
@@ -1209,7 +1215,7 @@ BOOL LoadObjects()
    // We should load conditions before nodes because
    // DCI cache size calculation uses information from condition objects
    DbgPrintf(2, _T("Loading conditions..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM conditions"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM conditions"));
    if (hResult != NULL)
    {
       Condition *pCondition;
@@ -1219,7 +1225,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pCondition = new Condition;
-         if (pCondition->loadFromDatabase(dwId))
+         if (pCondition->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pCondition, FALSE);  // Insert into indexes
          }
@@ -1234,7 +1240,7 @@ BOOL LoadObjects()
 
    // Load subnets
    DbgPrintf(2, _T("Loading subnets..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM subnets"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM subnets"));
    if (hResult != 0)
    {
       Subnet *pSubnet;
@@ -1244,7 +1250,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pSubnet = new Subnet;
-         if (pSubnet->loadFromDatabase(dwId))
+         if (pSubnet->loadFromDatabase(hdb, dwId))
          {
             if (!pSubnet->isDeleted())
             {
@@ -1274,7 +1280,7 @@ BOOL LoadObjects()
 
    // Load racks
    DbgPrintf(2, _T("Loading racks..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM racks"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM racks"));
    if (hResult != 0)
    {
       Rack *rack;
@@ -1284,7 +1290,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          rack = new Rack;
-         if (rack->loadFromDatabase(dwId))
+         if (rack->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(rack, FALSE);  // Insert into indexes
          }
@@ -1299,7 +1305,7 @@ BOOL LoadObjects()
 
    // Load mobile devices
    DbgPrintf(2, _T("Loading mobile devices..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM mobile_devices"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM mobile_devices"));
    if (hResult != 0)
    {
       MobileDevice *md;
@@ -1309,7 +1315,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          md = new MobileDevice;
-         if (md->loadFromDatabase(dwId))
+         if (md->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(md, FALSE);  // Insert into indexes
          }
@@ -1324,7 +1330,7 @@ BOOL LoadObjects()
 
    // Load nodes
    DbgPrintf(2, _T("Loading nodes..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM nodes"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM nodes"));
    if (hResult != NULL)
    {
       Node *pNode;
@@ -1334,7 +1340,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pNode = new Node;
-         if (pNode->loadFromDatabase(dwId))
+         if (pNode->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pNode, FALSE);  // Insert into indexes
          }
@@ -1349,7 +1355,7 @@ BOOL LoadObjects()
 
    // Load access points
    DbgPrintf(2, _T("Loading access points..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM access_points"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM access_points"));
    if (hResult != NULL)
    {
                AccessPoint *ap;
@@ -1359,7 +1365,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          ap = new AccessPoint;
-         if (ap->loadFromDatabase(dwId))
+         if (ap->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(ap, FALSE);  // Insert into indexes
          }
@@ -1374,7 +1380,7 @@ BOOL LoadObjects()
 
    // Load interfaces
    DbgPrintf(2, _T("Loading interfaces..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM interfaces"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM interfaces"));
    if (hResult != 0)
    {
       Interface *pInterface;
@@ -1384,7 +1390,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pInterface = new Interface;
-         if (pInterface->loadFromDatabase(dwId))
+         if (pInterface->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pInterface, FALSE);  // Insert into indexes
          }
@@ -1399,7 +1405,7 @@ BOOL LoadObjects()
 
    // Load network services
    DbgPrintf(2, _T("Loading network services..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM network_services"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM network_services"));
    if (hResult != 0)
    {
       NetworkService *pService;
@@ -1409,7 +1415,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pService = new NetworkService;
-         if (pService->loadFromDatabase(dwId))
+         if (pService->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pService, FALSE);  // Insert into indexes
          }
@@ -1424,7 +1430,7 @@ BOOL LoadObjects()
 
    // Load VPN connectors
    DbgPrintf(2, _T("Loading VPN connectors..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM vpn_connectors"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM vpn_connectors"));
    if (hResult != NULL)
    {
       VPNConnector *pConnector;
@@ -1434,7 +1440,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pConnector = new VPNConnector;
-         if (pConnector->loadFromDatabase(dwId))
+         if (pConnector->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pConnector, FALSE);  // Insert into indexes
          }
@@ -1449,7 +1455,7 @@ BOOL LoadObjects()
 
    // Load clusters
    DbgPrintf(2, _T("Loading clusters..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM clusters"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM clusters"));
    if (hResult != NULL)
    {
       Cluster *pCluster;
@@ -1459,7 +1465,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pCluster = new Cluster;
-         if (pCluster->loadFromDatabase(dwId))
+         if (pCluster->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pCluster, FALSE);  // Insert into indexes
          }
@@ -1478,7 +1484,7 @@ BOOL LoadObjects()
 
    // Load templates
    DbgPrintf(2, _T("Loading templates..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM templates"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM templates"));
    if (hResult != NULL)
    {
       dwNumRows = DBGetNumRows(hResult);
@@ -1486,7 +1492,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pTemplate = new Template;
-         if (pTemplate->loadFromDatabase(dwId))
+         if (pTemplate->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pTemplate, FALSE);  // Insert into indexes
                                pTemplate->calculateCompoundStatus();   // Force status change to NORMAL
@@ -1502,7 +1508,7 @@ BOOL LoadObjects()
 
    // Load agent policies
    DbgPrintf(2, _T("Loading agent policies..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id,policy_type FROM ap_common"));
+   hResult = DBSelect(hdb, _T("SELECT id,policy_type FROM ap_common"));
    if (hResult != NULL)
    {
       dwNumRows = DBGetNumRows(hResult);
@@ -1521,7 +1527,7 @@ BOOL LoadObjects()
                                        policy = new AgentPolicy(type);
                                        break;
                        }
-         if (policy->loadFromDatabase(dwId))
+         if (policy->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(policy, FALSE);  // Insert into indexes
                                policy->calculateCompoundStatus();      // Force status change to NORMAL
@@ -1537,7 +1543,7 @@ BOOL LoadObjects()
 
    // Load network maps
    DbgPrintf(2, _T("Loading network maps..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM network_maps"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM network_maps"));
    if (hResult != NULL)
    {
       dwNumRows = DBGetNumRows(hResult);
@@ -1545,7 +1551,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          NetworkMap *map = new NetworkMap;
-         if (map->loadFromDatabase(dwId))
+         if (map->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(map, FALSE);  // Insert into indexes
          }
@@ -1561,7 +1567,7 @@ BOOL LoadObjects()
    // Load container objects
    DbgPrintf(2, _T("Loading containers..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_CONTAINER);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
       Container *pContainer;
@@ -1571,7 +1577,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pContainer = new Container;
-         if (pContainer->loadFromDatabase(dwId))
+         if (pContainer->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pContainer, FALSE);  // Insert into indexes
          }
@@ -1587,7 +1593,7 @@ BOOL LoadObjects()
    // Load template group objects
    DbgPrintf(2, _T("Loading template groups..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_TEMPLATEGROUP);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
       TemplateGroup *pGroup;
@@ -1597,7 +1603,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pGroup = new TemplateGroup;
-         if (pGroup->loadFromDatabase(dwId))
+         if (pGroup->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pGroup, FALSE);  // Insert into indexes
          }
@@ -1613,7 +1619,7 @@ BOOL LoadObjects()
    // Load policy group objects
    DbgPrintf(2, _T("Loading policy groups..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_POLICYGROUP);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
       PolicyGroup *pGroup;
@@ -1623,7 +1629,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pGroup = new PolicyGroup;
-         if (pGroup->loadFromDatabase(dwId))
+         if (pGroup->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pGroup, FALSE);  // Insert into indexes
          }
@@ -1639,7 +1645,7 @@ BOOL LoadObjects()
    // Load map group objects
    DbgPrintf(2, _T("Loading map groups..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_NETWORKMAPGROUP);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
       NetworkMapGroup *pGroup;
@@ -1649,7 +1655,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pGroup = new NetworkMapGroup;
-         if (pGroup->loadFromDatabase(dwId))
+         if (pGroup->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pGroup, FALSE);  // Insert into indexes
          }
@@ -1664,7 +1670,7 @@ BOOL LoadObjects()
 
    // Load dashboard objects
    DbgPrintf(2, _T("Loading dashboards..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM dashboards"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM dashboards"));
    if (hResult != 0)
    {
       Dashboard *pd;
@@ -1674,7 +1680,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          pd = new Dashboard;
-         if (pd->loadFromDatabase(dwId))
+         if (pd->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(pd, FALSE);  // Insert into indexes
          }
@@ -1690,7 +1696,7 @@ BOOL LoadObjects()
    // Loading business service objects
    DbgPrintf(2, _T("Loading business services..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_BUSINESSSERVICE);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
           dwNumRows = DBGetNumRows(hResult);
@@ -1698,7 +1704,7 @@ BOOL LoadObjects()
           {
                   dwId = DBGetFieldULong(hResult, i, 0);
                   BusinessService *service = new BusinessService;
-                  if (service->loadFromDatabase(dwId))
+                  if (service->loadFromDatabase(hdb, dwId))
                   {
                           NetObjInsert(service, FALSE);  // Insert into indexes
                   }
@@ -1714,7 +1720,7 @@ BOOL LoadObjects()
    // Loading business service objects
    DbgPrintf(2, _T("Loading node links..."));
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT id FROM containers WHERE object_class=%d"), OBJECT_NODELINK);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != 0)
    {
           dwNumRows = DBGetNumRows(hResult);
@@ -1722,7 +1728,7 @@ BOOL LoadObjects()
           {
                   dwId = DBGetFieldULong(hResult, i, 0);
                   NodeLink *nl = new NodeLink;
-                  if (nl->loadFromDatabase(dwId))
+                  if (nl->loadFromDatabase(hdb, dwId))
                   {
                           NetObjInsert(nl, FALSE);  // Insert into indexes
                   }
@@ -1737,7 +1743,7 @@ BOOL LoadObjects()
 
    // Load service check objects
    DbgPrintf(2, _T("Loading service checks..."));
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id FROM slm_checks"));
+   hResult = DBSelect(hdb, _T("SELECT id FROM slm_checks"));
    if (hResult != 0)
    {
       dwNumRows = DBGetNumRows(hResult);
@@ -1745,7 +1751,7 @@ BOOL LoadObjects()
       {
          dwId = DBGetFieldULong(hResult, i, 0);
          SlmCheck *check = new SlmCheck;
-         if (check->loadFromDatabase(dwId))
+         if (check->loadFromDatabase(hdb, dwId))
          {
             NetObjInsert(check, FALSE);  // Insert into indexes
          }
@@ -1758,6 +1764,8 @@ BOOL LoadObjects()
       DBFreeResult(hResult);
    }
 
+   DBConnectionPoolReleaseConnection(hdb);
+
        // Load custom object classes provided by modules
    CALL_ALL_MODULES(pfLoadObjects, ());
 
@@ -1766,12 +1774,12 @@ BOOL LoadObjects()
        g_idxObjectById.forEach(LinkChildObjectsCallback, NULL);
 
    // Link childs to root objects
-   g_pServiceRoot->LinkChildObjects();
-   g_pTemplateRoot->LinkChildObjects();
-   g_pPolicyRoot->LinkChildObjects();
-   g_pMapRoot->LinkChildObjects();
-       g_pDashboardRoot->LinkChildObjects();
-       g_pBusinessServiceRoot->LinkChildObjects();
+   g_pServiceRoot->linkChildObjects();
+   g_pTemplateRoot->linkChildObjects();
+   g_pPolicyRoot->linkChildObjects();
+   g_pMapRoot->linkChildObjects();
+       g_pDashboardRoot->linkChildObjects();
+       g_pBusinessServiceRoot->linkChildObjects();
 
        // Link custom object classes provided by modules
    CALL_ALL_MODULES(pfLinkObjects, ());
index 33bc40c..7ba0646 100644 (file)
@@ -41,12 +41,14 @@ BOOL IsPackageInstalled(TCHAR *pszName, TCHAR *pszVersion, TCHAR *pszPlatform)
    free(pszEscVersion);
    free(pszEscPlatform);
 
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       bResult = (DBGetNumRows(hResult) > 0);
       DBFreeResult(hResult);
    }
+   DBConnectionPoolReleaseConnection(hdb);
    return bResult;
 }
 
@@ -61,13 +63,16 @@ BOOL IsValidPackageId(UINT32 dwPkgId)
    TCHAR szQuery[256];
    BOOL bResult = FALSE;
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    _sntprintf(szQuery, 256, _T("SELECT pkg_name FROM agent_pkg WHERE pkg_id=%d"), dwPkgId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       bResult = (DBGetNumRows(hResult) > 0);
       DBFreeResult(hResult);
    }
+   DBConnectionPoolReleaseConnection(hdb);
    return bResult;
 }
 
@@ -98,8 +103,10 @@ UINT32 UninstallPackage(UINT32 dwPkgId)
    DB_RESULT hResult;
    UINT32 dwResult;
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    _sntprintf(szQuery, 256, _T("SELECT pkg_file FROM agent_pkg WHERE pkg_id=%d"), dwPkgId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
       if (DBGetNumRows(hResult) > 0)
@@ -113,7 +120,7 @@ UINT32 UninstallPackage(UINT32 dwPkgId)
          {
             // Delete record from database
             _sntprintf(szQuery, 256, _T("DELETE FROM agent_pkg WHERE pkg_id=%d"), dwPkgId);
-            DBQuery(g_hCoreDB, szQuery);
+            DBQuery(hdb, szQuery);
             dwResult = RCC_SUCCESS;
          }
          else
@@ -131,6 +138,8 @@ UINT32 UninstallPackage(UINT32 dwPkgId)
    {
       dwResult = RCC_DB_FAILURE;
    }
+
+   DBConnectionPoolReleaseConnection(hdb);
    return dwResult;
 }
 
index daf8597..56dd9c0 100644 (file)
@@ -524,7 +524,9 @@ static THREAD_RESULT THREAD_CALL ActiveDiscoveryPoller(void *arg)
       if (!(g_flags & AF_ACTIVE_NETWORK_DISCOVERY))
          continue;
 
-      DB_RESULT hResult = DBSelect(g_hCoreDB, _T("SELECT addr_type,addr1,addr2 FROM address_lists WHERE list_type=1"));
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+      DB_RESULT hResult = DBSelect(hdb, _T("SELECT addr_type,addr1,addr2 FROM address_lists WHERE list_type=1"));
+      DBConnectionPoolReleaseConnection(hdb);
       if (hResult != NULL)
       {
          int nRows = DBGetNumRows(hResult);
index 6b1d13c..af60794 100644 (file)
@@ -48,16 +48,16 @@ Rack::~Rack()
 /**
  * Create object from database data
  */
-BOOL Rack::loadFromDatabase(UINT32 id)
+bool Rack::loadFromDatabase(DB_HANDLE hdb, UINT32 id)
 {
-       if (!Container::loadFromDatabase(id))
-               return FALSE;
+       if (!Container::loadFromDatabase(hdb, id))
+               return false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT height FROM racks WHERE id=?"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT height FROM racks WHERE id=?"));
        if (hStmt == NULL)
-               return FALSE;
+               return false;
 
-       BOOL success = FALSE;
+       bool success = false;
 
        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, id);
        DB_RESULT hResult = DBSelectPrepared(hStmt);
@@ -66,7 +66,7 @@ BOOL Rack::loadFromDatabase(UINT32 id)
                if (DBGetNumRows(hResult) > 0)
                {
                        m_height = DBGetFieldLong(hResult, 0, 0);
-                       success = TRUE;
+                       success = true;
                }
                DBFreeResult(hResult);
        }
index f12badc..ce6e28d 100644 (file)
@@ -38,7 +38,8 @@ void LoadScripts()
    int i, nRows;
 
    g_pScriptLibrary = new NXSL_Library;
-   hResult = DBSelect(g_hCoreDB, _T("SELECT script_id,script_name,script_code FROM script_library"));
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT script_id,script_name,script_code FROM script_library"));
    if (hResult != NULL)
    {
       nRows = DBGetNumRows(hResult);
@@ -62,6 +63,7 @@ void LoadScripts()
       }
       DBFreeResult(hResult);
    }
+   DBConnectionPoolReleaseConnection(hdb);
 }
 
 /**
index 56a5749..ffc95aa 100644 (file)
@@ -1479,10 +1479,11 @@ void ClientSession::onFileUpload(BOOL bSuccess)
     case CMD_INSTALL_PACKAGE:
       if (!bSuccess)
       {
-        TCHAR szQuery[256];
-
-        _sntprintf(szQuery, 256, _T("DELETE FROM agent_pkg WHERE pkg_id=%d"), m_dwUploadData);
-        DBQuery(g_hCoreDB, szQuery);
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+         TCHAR szQuery[256];
+         _sntprintf(szQuery, 256, _T("DELETE FROM agent_pkg WHERE pkg_id=%d"), m_dwUploadData);
+         DBQuery(hdb, szQuery);
+         DBConnectionPoolReleaseConnection(hdb);
       }
       break;
     case CMD_MODIFY_IMAGE:
@@ -2099,10 +2100,10 @@ void ClientSession::deleteEventTemplate(NXCPMessage *pRequest)
    // Check access rights
    if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) && (dwEventCode >= FIRST_USER_EVENT_ID))
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       TCHAR szQuery[256];
-
       _sntprintf(szQuery, 256, _T("DELETE FROM event_cfg WHERE event_code=%d"), dwEventCode);
-      if (DBQuery(g_hCoreDB, szQuery))
+      if (DBQuery(hdb, szQuery))
       {
          DeleteEventTemplateFromList(dwEventCode);
 
@@ -2120,6 +2121,7 @@ void ClientSession::deleteEventTemplate(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -2412,8 +2414,10 @@ void ClientSession::getConfigurationVariables(UINT32 dwRqId)
    // Check user rights
    if ((m_dwUserId == 0) || (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
       // Retrieve configuration variables from database
-      DB_RESULT hResult = DBSelect(g_hCoreDB, _T("SELECT var_name,var_value,need_server_restart FROM config WHERE is_visible=1"));
+      DB_RESULT hResult = DBSelect(hdb, _T("SELECT var_name,var_value,need_server_restart FROM config WHERE is_visible=1"));
       if (hResult != NULL)
       {
          // Send events, one per message
@@ -2429,6 +2433,7 @@ void ClientSession::getConfigurationVariables(UINT32 dwRqId)
          }
          DBFreeResult(hResult);
       }
+      DBConnectionPoolReleaseConnection(hdb);
       msg.setField(VID_RCC, RCC_SUCCESS);
    }
    else
@@ -6654,7 +6659,10 @@ void ClientSession::InstallPackage(NXCPMessage *pRequest)
                                    m_dwUploadData, szPkgName, szPkgVersion, pszEscDescr,
                                    szPlatform, pszCleanFileName);
                         free(pszEscDescr);
-                        DBQuery(g_hCoreDB, szQuery);
+
+                        DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+                        DBQuery(hdb, szQuery);
+                        DBConnectionPoolReleaseConnection(hdb);
                      }
                      else
                      {
@@ -6797,9 +6805,11 @@ void ClientSession::DeployPackage(NXCPMessage *pRequest)
       dwPkgId = pRequest->getFieldAsUInt32(VID_PACKAGE_ID);
       if (IsValidPackageId(dwPkgId))
       {
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
          // Read package information
          _sntprintf(szQuery, 256, _T("SELECT platform,pkg_file,version FROM agent_pkg WHERE pkg_id=%d"), dwPkgId);
-         hResult = DBSelect(g_hCoreDB, szQuery);
+         hResult = DBSelect(hdb, szQuery);
          if (hResult != NULL)
          {
             if (DBGetNumRows(hResult) > 0)
@@ -6866,6 +6876,7 @@ void ClientSession::DeployPackage(NXCPMessage *pRequest)
             msg.setField(VID_RCC, RCC_DB_FAILURE);
             bSuccess = FALSE;
          }
+         DBConnectionPoolReleaseConnection(hdb);
       }
       else
       {
@@ -7020,12 +7031,14 @@ void ClientSession::getUserVariable(NXCPMessage *pRequest)
    dwUserId = pRequest->isFieldExist(VID_USER_ID) ? pRequest->getFieldAsUInt32(VID_USER_ID) : m_dwUserId;
    if ((dwUserId == m_dwUserId) || (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
       // Try to read variable from database
       pRequest->getFieldAsString(VID_NAME, szVarName, MAX_VARIABLE_NAME);
       _sntprintf(szQuery, MAX_VARIABLE_NAME + 256,
                  _T("SELECT var_value FROM user_profiles WHERE user_id=%d AND var_name='%s'"),
                  dwUserId, szVarName);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          if (DBGetNumRows(hResult) > 0)
@@ -7048,6 +7061,7 @@ void ClientSession::getUserVariable(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -7080,11 +7094,13 @@ void ClientSession::setUserVariable(NXCPMessage *pRequest)
       pRequest->getFieldAsString(VID_NAME, szVarName, MAX_VARIABLE_NAME);
       if (IsValidObjectName(szVarName))
       {
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
          // Check if variable already exist in database
          _sntprintf(szQuery, MAX_VARIABLE_NAME + 256,
                     _T("SELECT var_name FROM user_profiles WHERE user_id=%d AND var_name='%s'"),
                     dwUserId, szVarName);
-         hResult = DBSelect(g_hCoreDB, szQuery);
+         hResult = DBSelect(hdb, szQuery);
          if (hResult != NULL)
          {
             if (DBGetNumRows(hResult) > 0)
@@ -7107,7 +7123,7 @@ void ClientSession::setUserVariable(NXCPMessage *pRequest)
                        _T("INSERT INTO user_profiles (user_id,var_name,var_value) VALUES (%d,'%s','%s')"),
                        dwUserId, szVarName, pszValue);
          free(pszValue);
-         if (DBQuery(g_hCoreDB, szQuery))
+         if (DBQuery(hdb, szQuery))
          {
             msg.setField(VID_RCC, RCC_SUCCESS);
          }
@@ -7115,6 +7131,8 @@ void ClientSession::setUserVariable(NXCPMessage *pRequest)
          {
             msg.setField(VID_RCC, RCC_DB_FAILURE);
          }
+
+         DBConnectionPoolReleaseConnection(hdb);
       }
       else
       {
@@ -7148,8 +7166,9 @@ void ClientSession::enumUserVariables(NXCPMessage *pRequest)
    if ((dwUserId == m_dwUserId) || (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
    {
       pRequest->getFieldAsString(VID_SEARCH_PATTERN, szPattern, MAX_VARIABLE_NAME);
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       _sntprintf(szQuery, 256, _T("SELECT var_name FROM user_profiles WHERE user_id=%d"), dwUserId);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          dwNumRows = DBGetNumRows(hResult);
@@ -7170,6 +7189,7 @@ void ClientSession::enumUserVariables(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -7196,13 +7216,15 @@ void ClientSession::deleteUserVariable(NXCPMessage *pRequest)
    dwUserId = pRequest->isFieldExist(VID_USER_ID) ? pRequest->getFieldAsUInt32(VID_USER_ID) : m_dwUserId;
    if ((dwUserId == m_dwUserId) || (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
       // Try to delete variable from database
       pRequest->getFieldAsString(VID_NAME, szVarName, MAX_VARIABLE_NAME);
       TranslateStr(szVarName, _T("*"), _T("%"));
       _sntprintf(szQuery, MAX_VARIABLE_NAME + 256,
                  _T("DELETE FROM user_profiles WHERE user_id=%d AND var_name LIKE '%s'"),
                  dwUserId, szVarName);
-      if (DBQuery(g_hCoreDB, szQuery))
+      if (DBQuery(hdb, szQuery))
       {
          msg.setField(VID_RCC, RCC_SUCCESS);
       }
@@ -7210,6 +7232,7 @@ void ClientSession::deleteUserVariable(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -7239,6 +7262,8 @@ void ClientSession::copyUserVariable(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
       dwSrcUserId = pRequest->isFieldExist(VID_USER_ID) ? pRequest->getFieldAsUInt32(VID_USER_ID) : m_dwUserId;
       dwDstUserId = pRequest->getFieldAsUInt32(VID_DST_USER_ID);
       bMove = (BOOL)pRequest->getFieldAsUInt16(VID_MOVE_FLAG);
@@ -7247,7 +7272,7 @@ void ClientSession::copyUserVariable(NXCPMessage *pRequest)
       _sntprintf(szQuery, 8192,
                  _T("SELECT var_name,var_value FROM user_profiles WHERE user_id=%d AND var_name LIKE '%s'"),
                  dwSrcUserId, szVarName);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          nRows = DBGetNumRows(hResult);
@@ -7259,7 +7284,7 @@ void ClientSession::copyUserVariable(NXCPMessage *pRequest)
             _sntprintf(szQuery, 32768,
                        _T("SELECT var_name FROM user_profiles WHERE user_id=%d AND var_name='%s'"),
                        dwDstUserId, szCurrVar);
-            hResult2 = DBSelect(g_hCoreDB, szQuery);
+            hResult2 = DBSelect(hdb, szQuery);
             if (hResult2 != NULL)
             {
                bExist = (DBGetNumRows(hResult2) > 0);
@@ -7280,14 +7305,14 @@ void ClientSession::copyUserVariable(NXCPMessage *pRequest)
                           _T("INSERT INTO user_profiles (user_id,var_name,var_value) VALUES (%d,'%s','%s')"),
                           dwDstUserId, szCurrVar, pszValue);
             free(pszValue);
-            DBQuery(g_hCoreDB, szQuery);
+            DBQuery(hdb, szQuery);
 
             if (bMove)
             {
                _sntprintf(szQuery, 32768,
                           _T("DELETE FROM user_profiles WHERE user_id=%d AND var_name='%s'"),
                           dwSrcUserId, szCurrVar);
-               DBQuery(g_hCoreDB, szQuery);
+               DBQuery(hdb, szQuery);
             }
          }
          DBFreeResult(hResult);
@@ -7297,6 +7322,7 @@ void ClientSession::copyUserVariable(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -7978,7 +8004,8 @@ void ClientSession::sendScriptList(UINT32 dwRqId)
    msg.setId(dwRqId);
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_SCRIPTS)
    {
-      hResult = DBSelect(g_hCoreDB, _T("SELECT script_id,script_name FROM script_library"));
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+      hResult = DBSelect(hdb, _T("SELECT script_id,script_name FROM script_library"));
       if (hResult != NULL)
       {
          msg.setField(VID_RCC, RCC_SUCCESS);
@@ -7995,6 +8022,7 @@ void ClientSession::sendScriptList(UINT32 dwRqId)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8017,9 +8045,10 @@ void ClientSession::sendScript(NXCPMessage *pRequest)
    msg.setId(pRequest->getId());
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_SCRIPTS)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       dwScriptId = pRequest->getFieldAsUInt32(VID_SCRIPT_ID);
       _sntprintf(szQuery, 256, _T("SELECT script_name,script_code FROM script_library WHERE script_id=%d"), dwScriptId);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          if (DBGetNumRows(hResult) > 0)
@@ -8042,6 +8071,7 @@ void ClientSession::sendScript(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8147,9 +8177,10 @@ void ClientSession::renameScript(NXCPMessage *pRequest)
       {
          if (IsValidScriptId(dwScriptId))
          {
+            DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
             _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("UPDATE script_library SET script_name=%s WHERE script_id=%d"),
-                      (const TCHAR *)DBPrepareString(g_hCoreDB, szName), dwScriptId);
-            if (DBQuery(g_hCoreDB, szQuery))
+                      (const TCHAR *)DBPrepareString(hdb, szName), dwScriptId);
+            if (DBQuery(hdb, szQuery))
             {
                ReloadScript(dwScriptId);
                msg.setField(VID_RCC, RCC_SUCCESS);
@@ -8158,6 +8189,7 @@ void ClientSession::renameScript(NXCPMessage *pRequest)
             {
                msg.setField(VID_RCC, RCC_DB_FAILURE);
             }
+            DBConnectionPoolReleaseConnection(hdb);
          }
          else
          {
@@ -8192,8 +8224,9 @@ void ClientSession::deleteScript(NXCPMessage *pRequest)
       dwScriptId = pRequest->getFieldAsUInt32(VID_SCRIPT_ID);
       if (IsValidScriptId(dwScriptId))
       {
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
          _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("DELETE FROM script_library WHERE script_id=%d"), dwScriptId);
-         if (DBQuery(g_hCoreDB, szQuery))
+         if (DBQuery(hdb, szQuery))
          {
             g_pScriptLibrary->lock();
             g_pScriptLibrary->deleteScript(dwScriptId);
@@ -8204,6 +8237,7 @@ void ClientSession::deleteScript(NXCPMessage *pRequest)
          {
             msg.setField(VID_RCC, RCC_DB_FAILURE);
          }
+         DBConnectionPoolReleaseConnection(hdb);
       }
       else
       {
@@ -8317,6 +8351,8 @@ void ClientSession::sendSyslog(NXCPMessage *pRequest)
    msg.setCode(CMD_REQUEST_COMPLETED);
    msg.setId(pRequest->getId());
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    MutexLock(m_mutexSendSyslog);
 
    // Retrieve events from database
@@ -8326,7 +8362,7 @@ void ClientSession::sendSyslog(NXCPMessage *pRequest)
       case DB_SYNTAX_PGSQL:
       case DB_SYNTAX_SQLITE:
          dwNumRows = 0;
-         hTempResult = DBSelect(g_hCoreDB, _T("SELECT count(*) FROM syslog"));
+         hTempResult = DBSelect(hdb, _T("SELECT count(*) FROM syslog"));
          if (hTempResult != NULL)
          {
             if (DBGetNumRows(hTempResult) > 0)
@@ -8363,7 +8399,6 @@ void ClientSession::sendSyslog(NXCPMessage *pRequest)
          szQuery[0] = 0;
          break;
    }
-   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
    hResult = DBAsyncSelect(hdb, szQuery);
    if (hResult != NULL)
    {
@@ -8407,8 +8442,8 @@ void ClientSession::sendSyslog(NXCPMessage *pRequest)
                sendMessage(&msg);
        }
 
-   DBConnectionPoolReleaseConnection(hdb);
    MutexUnlock(m_mutexSendSyslog);
+   DBConnectionPoolReleaseConnection(hdb);
 }
 
 /**
@@ -8456,6 +8491,7 @@ void ClientSession::SendTrapLog(NXCPMessage *pRequest)
       msg.deleteAllFields();
       msg.setCode(CMD_TRAP_LOG_RECORDS);
 
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       MutexLock(m_mutexSendTrapLog);
 
       // Retrieve trap log records from database
@@ -8465,7 +8501,7 @@ void ClientSession::SendTrapLog(NXCPMessage *pRequest)
          case DB_SYNTAX_PGSQL:
          case DB_SYNTAX_SQLITE:
             dwNumRows = 0;
-            hTempResult = DBSelect(g_hCoreDB, _T("SELECT count(*) FROM snmp_trap_log"));
+            hTempResult = DBSelect(hdb, _T("SELECT count(*) FROM snmp_trap_log"));
             if (hTempResult != NULL)
             {
                if (DBGetNumRows(hTempResult) > 0)
@@ -8504,7 +8540,6 @@ void ClientSession::SendTrapLog(NXCPMessage *pRequest)
             break;
       }
 
-      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       hResult = DBAsyncSelect(hdb, szQuery);
       if (hResult != NULL)
       {
@@ -8535,8 +8570,8 @@ void ClientSession::SendTrapLog(NXCPMessage *pRequest)
          msg.setEndOfSequence();
       }
 
-      DBConnectionPoolReleaseConnection(hdb);
       MutexUnlock(m_mutexSendTrapLog);
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8759,7 +8794,8 @@ void ClientSession::sendAgentCfgList(UINT32 dwRqId)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_AGENT_CFG)
    {
-      hResult = DBSelect(g_hCoreDB, _T("SELECT config_id,config_name,sequence_number FROM agent_configs"));
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+      hResult = DBSelect(hdb, _T("SELECT config_id,config_name,sequence_number FROM agent_configs"));
       if (hResult != NULL)
       {
          dwNumRows = DBGetNumRows(hResult);
@@ -8779,6 +8815,7 @@ void ClientSession::sendAgentCfgList(UINT32 dwRqId)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8804,9 +8841,10 @@ void ClientSession::OpenAgentConfig(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_AGENT_CFG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       dwCfgId = pRequest->getFieldAsUInt32(VID_CONFIG_ID);
       _sntprintf(szQuery, 256, _T("SELECT config_name,config_file,config_filter,sequence_number FROM agent_configs WHERE config_id=%d"), dwCfgId);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          if (DBGetNumRows(hResult) > 0)
@@ -8832,6 +8870,7 @@ void ClientSession::OpenAgentConfig(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8859,9 +8898,10 @@ void ClientSession::SaveAgentConfig(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_AGENT_CFG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       dwCfgId = pRequest->getFieldAsUInt32(VID_CONFIG_ID);
       _sntprintf(szQuery, 256, _T("SELECT config_name FROM agent_configs WHERE config_id=%d"), dwCfgId);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          bCreate = (DBGetNumRows(hResult) == 0);
@@ -8889,7 +8929,7 @@ void ClientSession::SaveAgentConfig(NXCPMessage *pRequest)
                msg.setField(VID_CONFIG_ID, dwCfgId);
 
                // Request sequence number
-               hResult = DBSelect(g_hCoreDB, _T("SELECT max(sequence_number) FROM agent_configs"));
+               hResult = DBSelect(hdb, _T("SELECT max(sequence_number) FROM agent_configs"));
                if (hResult != NULL)
                {
                   if (DBGetNumRows(hResult) > 0)
@@ -8921,7 +8961,7 @@ void ClientSession::SaveAgentConfig(NXCPMessage *pRequest)
          free(pszEscText);
          free(pszEscFilter);
 
-         if (DBQuery(g_hCoreDB, pszQuery))
+         if (DBQuery(hdb, pszQuery))
          {
             msg.setField(VID_RCC, RCC_SUCCESS);
          }
@@ -8935,6 +8975,7 @@ void ClientSession::SaveAgentConfig(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -8960,15 +9001,16 @@ void ClientSession::DeleteAgentConfig(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_AGENT_CFG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       dwCfgId = pRequest->getFieldAsUInt32(VID_CONFIG_ID);
       _sntprintf(szQuery, 256, _T("SELECT config_name FROM agent_configs WHERE config_id=%d"), dwCfgId);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          if (DBGetNumRows(hResult) > 0)
          {
             _sntprintf(szQuery, 256, _T("DELETE FROM agent_configs WHERE config_id=%d"), dwCfgId);
-            if (DBQuery(g_hCoreDB, szQuery))
+            if (DBQuery(hdb, szQuery))
             {
                msg.setField(VID_RCC, RCC_SUCCESS);
             }
@@ -8987,6 +9029,7 @@ void ClientSession::DeleteAgentConfig(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -9012,33 +9055,35 @@ void ClientSession::SwapAgentConfigs(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_AGENT_CFG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
       _sntprintf(szQuery, 256, _T("SELECT config_id,sequence_number FROM agent_configs WHERE config_id=%d OR config_id=%d"),
                  pRequest->getFieldAsUInt32(VID_CONFIG_ID), pRequest->getFieldAsUInt32(VID_CONFIG_ID_2));
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          if (DBGetNumRows(hResult) >= 2)
          {
-            if (DBBegin(g_hCoreDB))
+            if (DBBegin(hdb))
             {
                _sntprintf(szQuery, 256, _T("UPDATE agent_configs SET sequence_number=%d WHERE config_id=%d"),
                           DBGetFieldULong(hResult, 1, 1), DBGetFieldULong(hResult, 0, 0));
-               bRet = DBQuery(g_hCoreDB, szQuery);
+               bRet = DBQuery(hdb, szQuery);
                if (bRet)
                {
                   _sntprintf(szQuery, 256, _T("UPDATE agent_configs SET sequence_number=%d WHERE config_id=%d"),
                              DBGetFieldULong(hResult, 0, 1), DBGetFieldULong(hResult, 1, 0));
-                  bRet = DBQuery(g_hCoreDB, szQuery);
+                  bRet = DBQuery(hdb, szQuery);
                }
 
                if (bRet)
                {
-                  DBCommit(g_hCoreDB);
+                  DBCommit(hdb);
                   msg.setField(VID_RCC, RCC_SUCCESS);
                }
                else
                {
-                  DBRollback(g_hCoreDB);
+                  DBRollback(hdb);
                   msg.setField(VID_RCC, RCC_DB_FAILURE);
                }
             }
@@ -9057,6 +9102,7 @@ void ClientSession::SwapAgentConfigs(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -9090,7 +9136,8 @@ void ClientSession::sendConfigForAgent(NXCPMessage *pRequest)
    DbgPrintf(3, _T("Finding config for agent at %s: platform=\"%s\", version=\"%d.%d.%d\""),
              SockaddrToStr(m_clientAddr, szBuffer), szPlatform, (int)wMajor, (int)wMinor, (int)wRelease);
 
-   hResult = DBSelect(g_hCoreDB, _T("SELECT config_id,config_file,config_filter FROM agent_configs ORDER BY sequence_number"));
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   hResult = DBSelect(hdb, _T("SELECT config_id,config_file,config_filter FROM agent_configs ORDER BY sequence_number"));
    if (hResult != NULL)
    {
       nNumRows = DBGetNumRows(hResult);
@@ -9164,6 +9211,7 @@ void ClientSession::sendConfigForAgent(NXCPMessage *pRequest)
    {
       msg.setField(VID_RCC, (WORD)1);  // DB Failure
    }
+   DBConnectionPoolReleaseConnection(hdb);
 
    sendMessage(&msg);
 }
@@ -9388,9 +9436,10 @@ void ClientSession::getAddrList(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT addr_type,addr1,addr2 FROM address_lists WHERE list_type=%d"),
                 pRequest->getFieldAsUInt32(VID_ADDR_LIST_TYPE));
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          dwNumRec = DBGetNumRows(hResult);
@@ -9408,6 +9457,7 @@ void ClientSession::getAddrList(NXCPMessage *pRequest)
       {
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -9431,10 +9481,11 @@ void ClientSession::setAddrList(NXCPMessage *pRequest)
 
    if (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG)
    {
+      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
       dwListType = pRequest->getFieldAsUInt32(VID_ADDR_LIST_TYPE);
       _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("DELETE FROM address_lists WHERE list_type=%d"), dwListType);
-      DBBegin(g_hCoreDB);
-      if (DBQuery(g_hCoreDB, szQuery))
+      DBBegin(hdb);
+      if (DBQuery(hdb, szQuery))
       {
          dwNumRec = pRequest->getFieldAsUInt32(VID_NUM_RECORDS);
          for(i = 0, dwId = VID_ADDR_LIST_BASE; i < dwNumRec; i++, dwId += 10)
@@ -9443,26 +9494,27 @@ void ClientSession::setAddrList(NXCPMessage *pRequest)
                       dwListType, pRequest->getFieldAsUInt32(dwId),
                       IpToStr(pRequest->getFieldAsUInt32(dwId + 1), szIpAddr1),
                       IpToStr(pRequest->getFieldAsUInt32(dwId + 2), szIpAddr2));
-            if (!DBQuery(g_hCoreDB, szQuery))
+            if (!DBQuery(hdb, szQuery))
                break;
          }
 
          if (i == dwNumRec)
          {
-            DBCommit(g_hCoreDB);
+            DBCommit(hdb);
             msg.setField(VID_RCC, RCC_SUCCESS);
          }
          else
          {
-            DBRollback(g_hCoreDB);
+            DBRollback(hdb);
             msg.setField(VID_RCC, RCC_DB_FAILURE);
          }
       }
       else
       {
-         DBRollback(g_hCoreDB);
+         DBRollback(hdb);
          msg.setField(VID_RCC, RCC_DB_FAILURE);
       }
+      DBConnectionPoolReleaseConnection(hdb);
    }
    else
    {
@@ -10060,7 +10112,7 @@ void ClientSession::saveGraph(NXCPMessage *pRequest)
                        else
                        {
                                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("DELETE FROM graph_acl WHERE graph_id=%d"), graphId);
-                               DBQuery(g_hCoreDB, szQuery);
+                               DBQuery(hdb, szQuery);
 
                                _sntprintf(szQuery, 16384, _T("UPDATE graphs SET name='%s',config='%s' WHERE graph_id=%d"),
                                           pszEscName, pszEscData, graphId);
@@ -10313,7 +10365,8 @@ void ClientSession::AddCACertificate(NXCPMessage *pRequest)
                                free(pszEscComments);
                                BinToStr(pData, dwLen, &pszQuery[_tcslen(pszQuery)]);
                                _tcscat(pszQuery, _T("')"));
-                               if (DBQuery(g_hCoreDB, pszQuery))
+                               DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+                               if (DBQuery(hdb, pszQuery))
                                {
                NotifyClientSessions(NX_NOTIFY_CERTIFICATE_CHANGED, dwCertId);
                                        msg.setField(VID_RCC, RCC_SUCCESS);
@@ -10323,6 +10376,7 @@ void ClientSession::AddCACertificate(NXCPMessage *pRequest)
                                {
                                        msg.setField(VID_RCC, RCC_DB_FAILURE);
                                }
+                               DBConnectionPoolReleaseConnection(hdb);
                                free(pszQuery);
                        }
                        else
@@ -10367,9 +10421,10 @@ void ClientSession::DeleteCertificate(NXCPMessage *pRequest)
            (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
        {
 #ifdef _WITH_ENCRYPTION
+          DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
                dwCertId = pRequest->getFieldAsUInt32(VID_CERTIFICATE_ID);
                _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("DELETE FROM certificates WHERE cert_id=%d"), dwCertId);
-               if (DBQuery(g_hCoreDB, szQuery))
+               if (DBQuery(hdb, szQuery))
                {
                        msg.setField(VID_RCC, RCC_SUCCESS);
                        NotifyClientSessions(NX_NOTIFY_CERTIFICATE_CHANGED, dwCertId);
@@ -10379,6 +10434,7 @@ void ClientSession::DeleteCertificate(NXCPMessage *pRequest)
                {
                        msg.setField(VID_RCC, RCC_DB_FAILURE);
                }
+               DBConnectionPoolReleaseConnection(hdb);
 #else
                msg.setField(VID_RCC, RCC_NO_ENCRYPTION_SUPPORT);
 #endif
@@ -10413,18 +10469,19 @@ void ClientSession::UpdateCertificateComments(NXCPMessage *pRequest)
                pszComments= pRequest->getFieldAsString(VID_COMMENTS);
                if (pszComments != NULL)
                {
+                  DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
                        pszEscComments = EncodeSQLString(pszComments);
                        free(pszComments);
                        qlen = (UINT32)_tcslen(pszEscComments) + 256;
                        pszQuery = (TCHAR *)malloc(qlen * sizeof(TCHAR));
                        _sntprintf(pszQuery, qlen, _T("SELECT subject FROM certificates WHERE cert_id=%d"), dwCertId);
-                       hResult = DBSelect(g_hCoreDB, pszQuery);
+                       hResult = DBSelect(hdb, pszQuery);
                        if (hResult != NULL)
                        {
                                if (DBGetNumRows(hResult) > 0)
                                {
                                        _sntprintf(pszQuery, qlen, _T("UPDATE certificates SET comments='%s' WHERE cert_id=%d"), pszEscComments, dwCertId);
-                                       if (DBQuery(g_hCoreDB, pszQuery))
+                                       if (DBQuery(hdb, pszQuery))
                                        {
                   NotifyClientSessions(NX_NOTIFY_CERTIFICATE_CHANGED, dwCertId);
                                                msg.setField(VID_RCC, RCC_SUCCESS);
@@ -10446,6 +10503,7 @@ void ClientSession::UpdateCertificateComments(NXCPMessage *pRequest)
                        }
                        free(pszEscComments);
                        free(pszQuery);
+                       DBConnectionPoolReleaseConnection(hdb);
                }
                else
                {
@@ -10477,7 +10535,8 @@ void ClientSession::getCertificateList(UINT32 dwRqId)
        if ((m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS) &&
            (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
        {
-               hResult = DBSelect(g_hCoreDB, _T("SELECT cert_id,cert_type,comments,subject FROM certificates"));
+          DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+               hResult = DBSelect(hdb, _T("SELECT cert_id,cert_type,comments,subject FROM certificates"));
                if (hResult != NULL)
                {
                        nRows = DBGetNumRows(hResult);
@@ -10516,6 +10575,7 @@ void ClientSession::getCertificateList(UINT32 dwRqId)
                {
                        msg.setField(VID_RCC, RCC_DB_FAILURE);
                }
+               DBConnectionPoolReleaseConnection(hdb);
        }
        else
        {
@@ -11559,7 +11619,8 @@ void ClientSession::sendUsmCredentials(UINT32 dwRqId)
 
        if (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG)
        {
-               hResult = DBSelect(g_hCoreDB, _T("SELECT user_name,auth_method,priv_method,auth_password,priv_password FROM usm_credentials"));
+          DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+               hResult = DBSelect(hdb, _T("SELECT user_name,auth_method,priv_method,auth_password,priv_password FROM usm_credentials"));
                if (hResult != NULL)
                {
                        count = DBGetNumRows(hResult);
@@ -11585,6 +11646,7 @@ void ClientSession::sendUsmCredentials(UINT32 dwRqId)
                {
                        msg.setField(VID_RCC, RCC_DB_FAILURE);
                }
+               DBConnectionPoolReleaseConnection(hdb);
        }
        else
        {
@@ -11626,8 +11688,8 @@ void ClientSession::updateUsmCredentials(NXCPMessage *request)
                                        request->getFieldAsString(id++, authPasswd, MAX_DB_STRING);
                                        request->getFieldAsString(id++, privPasswd, MAX_DB_STRING);
                                        _sntprintf(query, 4096, _T("INSERT INTO usm_credentials (id,user_name,auth_method,priv_method,auth_password,priv_password) VALUES(%d,%s,%d,%d,%s,%s)"),
-                                                                 i + 1, (const TCHAR *)DBPrepareString(g_hCoreDB, name), authMethod, privMethod,
-                                                                 (const TCHAR *)DBPrepareString(g_hCoreDB, authPasswd), (const TCHAR *)DBPrepareString(g_hCoreDB, privPasswd));
+                                                                 i + 1, (const TCHAR *)DBPrepareString(hdb, name), authMethod, privMethod,
+                                                                 (const TCHAR *)DBPrepareString(hdb, authPasswd), (const TCHAR *)DBPrepareString(hdb, privPasswd));
                                        if (!DBQuery(hdb, query))
                                                break;
                                }
@@ -11905,9 +11967,11 @@ void ClientSession::sendLibraryImage(NXCPMessage *request)
 
        if (rcc == RCC_SUCCESS)
        {
+          DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
                TCHAR query[MAX_DB_STRING];
                _sntprintf(query, MAX_DB_STRING, _T("SELECT name,category,mimetype,protected FROM images WHERE guid = '%s'"), guidText);
-               DB_RESULT result = DBSelect(g_hCoreDB, query);
+               DB_RESULT result = DBSelect(hdb, query);
                if (result != NULL)
                {
                        int count = DBGetNumRows(result);
@@ -11950,6 +12014,7 @@ void ClientSession::sendLibraryImage(NXCPMessage *request)
                {
                        rcc = RCC_DB_FAILURE;
                }
+               DBConnectionPoolReleaseConnection(hdb);
        }
 
        msg.setField(VID_RCC, rcc);
@@ -12054,9 +12119,9 @@ void ClientSession::updateLibraryImage(NXCPMessage *request)
                                if (!isProtected)
                                {
                                        _sntprintf(query, MAX_DB_STRING, _T("UPDATE images SET name = %s, category = %s, mimetype = %s WHERE guid = '%s'"),
-                                                       (const TCHAR *)DBPrepareString(g_hCoreDB, name),
-                                                       (const TCHAR *)DBPrepareString(g_hCoreDB, category),
-                                                       (const TCHAR *)DBPrepareString(g_hCoreDB, mimetype, 32),
+                                                       (const TCHAR *)DBPrepareString(hdb, name),
+                                                       (const TCHAR *)DBPrepareString(hdb, category),
+                                                       (const TCHAR *)DBPrepareString(hdb, mimetype, 32),
                                                        guidText);
                                }
                                else
@@ -12069,9 +12134,9 @@ void ClientSession::updateLibraryImage(NXCPMessage *request)
                                // not found in DB, create
                                _sntprintf(query, MAX_DB_STRING, _T("INSERT INTO images (guid, name, category, mimetype, protected) VALUES ('%s', %s, %s, %s, 0)"),
                                                guidText,
-                                               (const TCHAR *)DBPrepareString(g_hCoreDB, name),
-                                               (const TCHAR *)DBPrepareString(g_hCoreDB, category),
-                                               (const TCHAR *)DBPrepareString(g_hCoreDB, mimetype, 32));
+                                               (const TCHAR *)DBPrepareString(hdb, name),
+                                               (const TCHAR *)DBPrepareString(hdb, category),
+                                               (const TCHAR *)DBPrepareString(hdb, mimetype, 32));
                        }
 
                        if (query[0] != 0)
@@ -12226,14 +12291,15 @@ void ClientSession::listLibraryImages(NXCPMessage *request)
        }
        debugPrintf(5, _T("listLibraryImages: category=%s"), category[0] == 0 ? _T("*ANY*") : category);
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
        _tcscpy(query, _T("SELECT guid,name,category,mimetype,protected FROM images"));
        if (category[0] != 0)
        {
                _tcscat(query, _T(" WHERE category = "));
-      _tcscat(query, (const TCHAR *)DBPrepareString(g_hCoreDB, category));
+      _tcscat(query, (const TCHAR *)DBPrepareString(hdb, category));
        }
 
-   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
        DB_RESULT result = DBSelect(hdb, query);
        if (result != NULL)
        {
index af3cc03..2b68282 100644 (file)
@@ -161,12 +161,14 @@ void Situation::SaveToDatabase()
        size_t qlen;
        BOOL isUpdate;
        
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
        escName = EncodeSQLString(CHECK_NULL_EX(m_name));
        escComments = EncodeSQLString(CHECK_NULL_EX(m_comments));
        qlen = _tcslen(escName) + _tcslen(escComments) + 256;
        query = (TCHAR *)malloc(qlen * sizeof(TCHAR));
        _sntprintf(query, qlen, _T("SELECT id FROM situations WHERE id=%d"), m_id);
-       result = DBSelect(g_hCoreDB, query);
+       result = DBSelect(hdb, query);
        if (result != NULL)
        {
                isUpdate = DBGetNumRows(result) > 0;
@@ -184,8 +186,10 @@ void Situation::SaveToDatabase()
                           m_id, escName, escComments);
        free(escName);
        free(escComments);
-       DBQuery(g_hCoreDB, query);
+       DBQuery(hdb, query);
        free(query);
+
+       DBConnectionPoolReleaseConnection(hdb);
 }
 
 
@@ -195,10 +199,11 @@ void Situation::SaveToDatabase()
 
 void Situation::DeleteFromDatabase()
 {
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
        TCHAR query[256];
-       
        _sntprintf(query, 256, _T("DELETE FROM situations WHERE id=%d"), m_id);
-       DBQuery(g_hCoreDB, query);
+       DBQuery(hdb, query);
+       DBConnectionPoolReleaseConnection(hdb);
 }
 
 
@@ -344,8 +349,10 @@ BOOL SituationsInit()
 {
        BOOL success = TRUE;
        
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Load situations from database
-   DB_RESULT result = DBSelect(g_hCoreDB, _T("SELECT id,name,comments FROM situations ORDER BY id"));
+   DB_RESULT result = DBSelect(hdb, _T("SELECT id,name,comments FROM situations ORDER BY id"));
    if (result != NULL)
    {
        int count = DBGetNumRows(result);
@@ -361,6 +368,7 @@ BOOL SituationsInit()
                DbgPrintf(3, _T("Cannot load situations from database due to DBSelect() failure"));
                success = FALSE;
        }
+   DBConnectionPoolReleaseConnection(hdb);
        return success;
 }
 
index f81a49f..a75ed89 100644 (file)
@@ -154,20 +154,20 @@ void SlmCheck::compileScript()
 /**
  * Create object from database data
  */
-BOOL SlmCheck::loadFromDatabase(UINT32 id)
+bool SlmCheck::loadFromDatabase(DB_HANDLE hdb, UINT32 id)
 {
        UINT32 thresholdId;
 
        m_id = id;
 
-       if (!loadCommonProperties())
-               return FALSE;
+       if (!loadCommonProperties(hdb))
+               return false;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT type,content,threshold_id,template_id,current_ticket,is_template,reason FROM slm_checks WHERE id=?"));
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT type,content,threshold_id,template_id,current_ticket,is_template,reason FROM slm_checks WHERE id=?"));
        if (hStmt == NULL)
        {
                DbgPrintf(4, _T("Cannot prepare select from slm_checks"));
-               return FALSE;
+               return false;
        }
        DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
 
@@ -175,7 +175,7 @@ BOOL SlmCheck::loadFromDatabase(UINT32 id)
        if (hResult == NULL)
        {
                DBFreeStatement(hStmt);
-               return FALSE;
+               return false;
        }
 
        if (DBGetNumRows(hResult) == 0)
@@ -183,7 +183,7 @@ BOOL SlmCheck::loadFromDatabase(UINT32 id)
                DBFreeResult(hResult);
                DBFreeStatement(hStmt);
                DbgPrintf(4, _T("Cannot load check object %ld - record missing"), (long)m_id);
-               return FALSE;
+               return false;
        }
 
        m_type = SlmCheck::CheckType(DBGetFieldLong(hResult, 0, 0));
@@ -205,39 +205,24 @@ BOOL SlmCheck::loadFromDatabase(UINT32 id)
        DBFreeStatement(hStmt);
 
        // Load access list
-       loadACLFromDB();
+       loadACLFromDB(hdb);
 
        return TRUE;
 }
 
-
-//
-// Save service to database
-//
-
+/**
+ * Save service check to database
+ */
 BOOL SlmCheck::saveToDatabase(DB_HANDLE hdb)
 {
-       BOOL bNewObject = TRUE;
-       BOOL ret = FALSE;
-       DB_RESULT hResult = NULL;
+       bool ret = false;
 
        lockProperties();
 
        saveCommonProperties(hdb);
 
-       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT id FROM slm_checks WHERE id=?"));
-       if (hStmt == NULL)
-               goto finish;
-       DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
-       hResult = DBSelectPrepared(hStmt);
-       if (hResult != NULL)
-       {
-               bNewObject = (DBGetNumRows(hResult) <= 0);
-               DBFreeResult(hResult);
-       }
-       DBFreeStatement(hStmt);
-
-       hStmt = DBPrepare(g_hCoreDB, bNewObject ?
+       bool newObject = IsDatabaseRecordExist(hdb, _T("slm_checks"), _T("id"), m_id);
+       DB_STATEMENT hStmt = DBPrepare(hdb, newObject ?
                _T("INSERT INTO slm_checks (id,type,content,threshold_id,reason,is_template,template_id,current_ticket) VALUES (?,?,?,?,?,?,?,?)") :
                _T("UPDATE slm_checks SET id=?,type=?,content=?,threshold_id=?,reason=?,is_template=?,template_id=?,current_ticket=? WHERE id=?"));
        if (hStmt == NULL)
@@ -250,7 +235,7 @@ BOOL SlmCheck::saveToDatabase(DB_HANDLE hdb)
        DBBind(hStmt, 6, DB_SQLTYPE_INTEGER, (LONG)(m_isTemplate ? 1 : 0));
        DBBind(hStmt, 7, DB_SQLTYPE_INTEGER, m_templateId);
        DBBind(hStmt, 8, DB_SQLTYPE_INTEGER, m_currentTicketId);
-       if (!bNewObject)
+       if (!newObject)
                DBBind(hStmt, 9, DB_SQLTYPE_INTEGER, m_id);
 
        if (!DBExecute(hStmt))
@@ -262,7 +247,7 @@ BOOL SlmCheck::saveToDatabase(DB_HANDLE hdb)
        DBFreeStatement(hStmt);
 
        saveACLToDB(hdb);
-       ret = TRUE;
+       ret = true;
 
 finish:
        // Unlock object and clear modification flag
index 99b0dbe..0fe00ae 100644 (file)
@@ -54,8 +54,10 @@ static BOOL LoadTrapCfg()
    TCHAR *pszOID, szQuery[256], szBuffer[MAX_DB_STRING];
    UINT32 i, j, pdwBuffer[MAX_OID_LEN];
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Load traps
-   hResult = DBSelect(g_hCoreDB, _T("SELECT trap_id,snmp_oid,event_code,description,user_tag FROM snmp_trap_cfg"));
+   hResult = DBSelect(hdb, _T("SELECT trap_id,snmp_oid,event_code,description,user_tag FROM snmp_trap_cfg"));
    if (hResult != NULL)
    {
       m_dwNumTraps = DBGetNumRows(hResult);
@@ -88,7 +90,7 @@ static BOOL LoadTrapCfg()
          _sntprintf(szQuery, 256, _T("SELECT snmp_oid,description,flags FROM snmp_trap_pmap ")
                                   _T("WHERE trap_id=%d ORDER BY parameter"),
                     m_pTrapCfg[i].dwId);
-         hResult = DBSelect(g_hCoreDB, szQuery);
+         hResult = DBSelect(hdb, szQuery);
          if (hResult != NULL)
          {
             m_pTrapCfg[i].dwNumMaps = DBGetNumRows(hResult);
@@ -131,6 +133,7 @@ static BOOL LoadTrapCfg()
    {
       bResult = FALSE;
    }
+   DBConnectionPoolReleaseConnection(hdb);
    return bResult;
 }
 
@@ -146,13 +149,15 @@ void InitTraps()
        m_bLogAllTraps = ConfigReadInt(_T("LogAllSNMPTraps"), FALSE);
        s_allowVarbindConversion = ConfigReadInt(_T("AllowTrapVarbindsConversion"), 1) ? true : false;
 
-       hResult = DBSelect(g_hCoreDB, _T("SELECT max(trap_id) FROM snmp_trap_log"));
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       hResult = DBSelect(hdb, _T("SELECT max(trap_id) FROM snmp_trap_log"));
        if (hResult != NULL)
        {
                if (DBGetNumRows(hResult) > 0)
                        m_qnTrapId = DBGetFieldInt64(hResult, 0, 0) + 1;
                DBFreeResult(hResult);
        }
+       DBConnectionPoolReleaseConnection(hdb);
 
        m_wTrapPort = (UINT16)ConfigReadULong(_T("SNMPTrapPort"), m_wTrapPort); // 162 by default;
 }
@@ -298,7 +303,7 @@ void ProcessTrap(SNMP_PDU *pdu, const InetAddress& srcAddr, int srcPort, SNMP_Tr
                                 _T("(") INT64_FMT _T(",%d,'%s',%d,'%s',%s)"),
                  m_qnTrapId, dwTimeStamp, srcAddr.toString(szBuffer),
                  (pNode != NULL) ? pNode->getId() : (UINT32)0, pdu->getTrapId()->getValueAsText(),
-                 (const TCHAR *)DBPrepareString(g_hCoreDB, pszTrapArgs));
+                 (const TCHAR *)DBPrepareString(g_dbDriver, pszTrapArgs));
       QueueSQLRequest(szQuery);
 
       // Notify connected clients
@@ -908,10 +913,12 @@ UINT32 CreateNewTrap(UINT32 *pdwTrapId)
        m_dwNumTraps++;
    MutexUnlock(m_mutexTrapCfgAccess);
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("INSERT INTO snmp_trap_cfg (trap_id,snmp_oid,event_code,description,user_tag) ")
                       _T("VALUES (%d,'',%d,'','')"), *pdwTrapId, (UINT32)EVENT_SNMP_UNMATCHED_TRAP);
-   if (!DBQuery(g_hCoreDB, szQuery))
+   if (!DBQuery(hdb, szQuery))
       dwResult = RCC_DB_FAILURE;
+   DBConnectionPoolReleaseConnection(hdb);
 
    return dwResult;
 }
@@ -938,15 +945,16 @@ UINT32 CreateNewTrap(NXC_TRAP_CFG_ENTRY *pTrap)
                        m_pTrapCfg[m_dwNumTraps].pMaps[i].pdwObjectId = (UINT32 *)nx_memdup(pTrap->pMaps[i].pdwObjectId, sizeof(UINT32) * pTrap->pMaps[i].dwOidLen);
        }
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
        // Write new trap to database
    SNMPConvertOIDToText(m_pTrapCfg[m_dwNumTraps].dwOidLen, m_pTrapCfg[m_dwNumTraps].pdwObjectId, szOID, 1024);
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("INSERT INTO snmp_trap_cfg (trap_id,snmp_oid,event_code,description,user_tag) ")
                       _T("VALUES (%d,'%s',%d,%s,%s)"), m_pTrapCfg[m_dwNumTraps].dwId,
                  szOID, m_pTrapCfg[m_dwNumTraps].dwEventCode,
-                                (const TCHAR *)DBPrepareString(g_hCoreDB, m_pTrapCfg[m_dwNumTraps].szDescription),
-                                (const TCHAR *)DBPrepareString(g_hCoreDB, m_pTrapCfg[m_dwNumTraps].szUserTag));
+                                (const TCHAR *)DBPrepareString(hdb, m_pTrapCfg[m_dwNumTraps].szDescription),
+                                (const TCHAR *)DBPrepareString(hdb, m_pTrapCfg[m_dwNumTraps].szUserTag));
 
-       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
        if(DBBegin(hdb))
    {
       bSuccess = DBQuery(hdb, szQuery);
@@ -1026,13 +1034,14 @@ UINT32 UpdateTrapFromMsg(NXCPMessage *pMsg)
                                m_pTrapCfg[i].pMaps[j].dwFlags = pMsg->getFieldAsUInt32(dwId4);
          }
 
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
          // Update database
          SNMPConvertOIDToText(m_pTrapCfg[i].dwOidLen, m_pTrapCfg[i].pdwObjectId, szOID, 1024);
          _sntprintf(szQuery, 1024, _T("UPDATE snmp_trap_cfg SET snmp_oid='%s',event_code=%d,description=%s,user_tag=%s WHERE trap_id=%d"),
                     szOID, m_pTrapCfg[i].dwEventCode,
-                                                 (const TCHAR *)DBPrepareString(g_hCoreDB, m_pTrapCfg[i].szDescription),
-                                                 (const TCHAR *)DBPrepareString(g_hCoreDB, m_pTrapCfg[i].szUserTag), m_pTrapCfg[i].dwId);
-                       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+                                                 (const TCHAR *)DBPrepareString(hdb, m_pTrapCfg[i].szDescription),
+                                                 (const TCHAR *)DBPrepareString(hdb, m_pTrapCfg[i].szUserTag), m_pTrapCfg[i].dwId);
          if(DBBegin(hdb))
          {
             bSuccess = DBQuery(hdb, szQuery);
index a52620a..745a32b 100644 (file)
@@ -52,25 +52,25 @@ Subnet::~Subnet()
 /**
  * Create object from database data
  */
-BOOL Subnet::loadFromDatabase(UINT32 dwId)
+bool Subnet::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    TCHAR szQuery[256];
    DB_RESULT hResult;
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT ip_addr,ip_netmask,zone_guid,synthetic_mask FROM subnets WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == 0)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    if (DBGetNumRows(hResult) == 0)
    {
       DBFreeResult(hResult);
-      return FALSE;
+      return false;
    }
 
    m_ipAddress = DBGetFieldInetAddr(hResult, 0, 0);
@@ -81,9 +81,9 @@ BOOL Subnet::loadFromDatabase(UINT32 dwId)
    DBFreeResult(hResult);
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
-   return TRUE;
+   return true;
 }
 
 /**
index 5908468..1ce4e2a 100644 (file)
@@ -63,13 +63,13 @@ void ServiceContainer::initServiceContainer()
 /**
  * Create object from database data
  */
-BOOL ServiceContainer::loadFromDatabase(UINT32 id)
+bool ServiceContainer::loadFromDatabase(DB_HANDLE hdb, UINT32 id)
 {
-       if (!Container::loadFromDatabase(id))
-               return FALSE;
+       if (!Container::loadFromDatabase(hdb, id))
+               return false;
 
        initUptimeStats();
-       return TRUE;
+       return true;
 }
 
 /**
@@ -165,9 +165,11 @@ BOOL ServiceContainer::addHistoryRecord()
        DB_RESULT hResult;
        DB_STATEMENT hStmt;
 
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
        if (ServiceContainer::logRecordId < 0)
        {
-               hResult = DBSelect(g_hCoreDB, _T("SELECT max(record_id) FROM slm_service_history"));
+               hResult = DBSelect(hdb, _T("SELECT max(record_id) FROM slm_service_history"));
                if (hResult == NULL)
                        return FALSE;
                ServiceContainer::logRecordId = DBGetNumRows(hResult) > 0 ? DBGetFieldLong(hResult, 0, 0) : 0;
@@ -176,7 +178,7 @@ BOOL ServiceContainer::addHistoryRecord()
 
        ServiceContainer::logRecordId++;
 
-       hStmt = DBPrepare(g_hCoreDB, _T("INSERT INTO slm_service_history (record_id,service_id,change_timestamp,new_status) ")
+       hStmt = DBPrepare(hdb, _T("INSERT INTO slm_service_history (record_id,service_id,change_timestamp,new_status) ")
                _T("VALUES (?,?,?,?)"));
        if (hStmt != NULL)
        {
@@ -197,6 +199,7 @@ BOOL ServiceContainer::addHistoryRecord()
        }
 
        DBFreeStatement(hStmt);
+       DBConnectionPoolReleaseConnection(hdb);
        return TRUE;
 }
 
@@ -223,8 +226,9 @@ double ServiceContainer::getUptimeFromDBFor(Period period, INT32 *downtime)
        INT32 timediffTillNow   = ServiceContainer::getSecondsSinceBeginningOf(period, &beginTime);
        double percentage = 0;
 
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, _T("SELECT change_timestamp,new_status FROM slm_service_history ")
-                                                 _T("WHERE service_id=? AND change_timestamp>?"));
+       DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+       DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT change_timestamp,new_status FROM slm_service_history ")
+                                           _T("WHERE service_id=? AND change_timestamp>?"));
        if (hStmt != NULL)
        {
                DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
@@ -264,6 +268,7 @@ double ServiceContainer::getUptimeFromDBFor(Period period, INT32 *downtime)
                DBFreeStatement(hStmt);
        }
 
+       DBConnectionPoolReleaseConnection(hdb);
        return percentage;
 }
 
index e21d29b..a7b696a 100644 (file)
@@ -115,23 +115,6 @@ THREAD_RESULT THREAD_CALL Syncer(void *arg)
 {
    int iSyncInterval;
    UINT32 dwWatchdogId;
-   DB_HANDLE hdb;
-
-   // Establish separate connection to database if needed
-   if (g_flags & AF_ENABLE_MULTIPLE_DB_CONN)
-   {
-               TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
-      hdb = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
-      if (hdb == NULL)
-      {
-         nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
-         hdb = g_hCoreDB;   // Switch to main DB connection
-      }
-   }
-   else
-   {
-      hdb = g_hCoreDB;
-   }
 
    // Read configuration
    iSyncInterval = ConfigReadInt(_T("SyncInterval"), 60);
@@ -146,17 +129,13 @@ THREAD_RESULT THREAD_CALL Syncer(void *arg)
       WatchdogNotify(dwWatchdogId);
       if (!(g_flags & AF_DB_CONNECTION_LOST))    // Don't try to save if DB connection is lost
       {
+         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
          SaveObjects(hdb);
          SaveUsers(hdb);
+         DBConnectionPoolReleaseConnection(hdb);
       }
    }
 
-   // Disconnect from database if using separate connection
-   if (hdb != g_hCoreDB)
-   {
-      DBDisconnect(hdb);
-   }
-
    DbgPrintf(1, _T("Syncer thread terminated"));
    return THREAD_OK;
 }
index ca37d19..5e7ea19 100644 (file)
@@ -167,7 +167,7 @@ void Template::setAutoApplyFilter(const TCHAR *filter)
  *
  * @param dwId object ID
  */
-BOOL Template::loadFromDatabase(UINT32 dwId)
+bool Template::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    TCHAR szQuery[256];
    DB_RESULT hResult;
@@ -177,11 +177,11 @@ BOOL Template::loadFromDatabase(UINT32 dwId)
 
    m_id = dwId;
 
-   if (!loadCommonProperties())
+   if (!loadCommonProperties(hdb))
       return FALSE;
 
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT version,flags,apply_filter FROM templates WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
       return FALSE;     // Query failed
 
@@ -209,17 +209,17 @@ BOOL Template::loadFromDatabase(UINT32 dwId)
    DBFreeResult(hResult);
 
    // Load DCI and access list
-   loadACLFromDB();
-   loadItemsFromDB();
+   loadACLFromDB(hdb);
+   loadItemsFromDB(hdb);
    for(i = 0; i < (UINT32)m_dcObjects->size(); i++)
-      if (!m_dcObjects->get(i)->loadThresholdsFromDB())
+      if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
          bResult = FALSE;
 
    // Load related nodes list
    if (!m_isDeleted)
    {
       _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT node_id FROM dct_node_map WHERE template_id=%d"), m_id);
-      hResult = DBSelect(g_hCoreDB, szQuery);
+      hResult = DBSelect(hdb, szQuery);
       if (hResult != NULL)
       {
          dwNumNodes = DBGetNumRows(hResult);
@@ -352,9 +352,9 @@ bool Template::deleteFromDatabase(DB_HANDLE hdb)
 /**
  * Load data collection items from database
  */
-void Template::loadItemsFromDB()
+void Template::loadItemsFromDB(DB_HANDLE hdb)
 {
-       DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
+       DB_STATEMENT hStmt = DBPrepare(hdb,
                   _T("SELECT item_id,name,source,datatype,polling_interval,retention_time,")
               _T("status,delta_calculation,transformation,template_id,description,")
               _T("instance,template_item_id,flags,resource_id,")
@@ -369,13 +369,13 @@ void Template::loadItemsFromDB()
                {
                        int count = DBGetNumRows(hResult);
                        for(int i = 0; i < count; i++)
-                               m_dcObjects->add(new DCItem(hResult, i, this));
+                               m_dcObjects->add(new DCItem(hdb, hResult, i, this));
                        DBFreeResult(hResult);
                }
                DBFreeStatement(hStmt);
        }
 
-       hStmt = DBPrepare(g_hCoreDB,
+       hStmt = DBPrepare(hdb,
                   _T("SELECT item_id,template_id,template_item_id,name,")
                                  _T("description,flags,source,snmp_port,polling_interval,retention_time,")
               _T("status,system_tag,resource_id,proxy_node,perftab_settings,")
@@ -388,7 +388,7 @@ void Template::loadItemsFromDB()
                {
                        int count = DBGetNumRows(hResult);
                        for(int i = 0; i < count; i++)
-                               m_dcObjects->add(new DCTable(hResult, i, this));
+                               m_dcObjects->add(new DCTable(hdb, hResult, i, this));
                        DBFreeResult(hResult);
                }
                DBFreeStatement(hStmt);
index 335ce59..24ebf19 100644 (file)
@@ -41,31 +41,30 @@ UniversalRoot::~UniversalRoot()
  * Link child objects
  * This method is expected to be called only at startup, so we don't lock
  */
-void UniversalRoot::LinkChildObjects()
+void UniversalRoot::linkChildObjects()
 {
-   UINT32 i, dwNumChilds, dwObjectId;
-   NetObj *pObject;
-   TCHAR szQuery[256];
-   DB_RESULT hResult;
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
 
-   // Load child list and link objects
+   TCHAR szQuery[256];
    _sntprintf(szQuery, sizeof(szQuery) / sizeof(TCHAR), _T("SELECT object_id FROM container_members WHERE container_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+
+   DB_RESULT hResult = DBSelect(hdb, szQuery);
    if (hResult != NULL)
    {
-      dwNumChilds = DBGetNumRows(hResult);
-      for(i = 0; i < dwNumChilds; i++)
+      int count = DBGetNumRows(hResult);
+      for(int i = 0; i < count; i++)
       {
-         dwObjectId = DBGetFieldULong(hResult, i, 0);
-         pObject = FindObjectById(dwObjectId);
+         UINT32 dwObjectId = DBGetFieldULong(hResult, i, 0);
+         NetObj *pObject = FindObjectById(dwObjectId);
          if (pObject != NULL)
-            LinkObject(pObject);
+            linkObject(pObject);
          else
-            nxlog_write(MSG_ROOT_INVALID_CHILD_ID, EVENTLOG_WARNING_TYPE, "ds", 
-                        dwObjectId, g_szClassName[getObjectClass()]);
+            nxlog_write(MSG_ROOT_INVALID_CHILD_ID, EVENTLOG_WARNING_TYPE, "ds", dwObjectId, g_szClassName[getObjectClass()]);
       }
       DBFreeResult(hResult);
    }
+
+   DBConnectionPoolReleaseConnection(hdb);
 }
 
 /**
@@ -103,8 +102,8 @@ BOOL UniversalRoot::saveToDatabase(DB_HANDLE hdb)
 /**
  * Load properties from database
  */
-void UniversalRoot::LoadFromDB()
+void UniversalRoot::loadFromDatabase(DB_HANDLE hdb)
 {
-   loadCommonProperties();
-   loadACLFromDB();
+   loadCommonProperties(hdb);
+   loadACLFromDB(hdb);
 }
index 75c6b4f..e084ae5 100644 (file)
@@ -127,20 +127,25 @@ BOOL LoadUsers()
    int i;
    DB_RESULT hResult;
 
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
    // Load users
-   hResult = DBSelect(g_hCoreDB,
+   hResult = DBSelect(hdb,
                           _T("SELECT id,name,system_access,flags,description,guid,ldap_dn,")
                                                         _T("password,full_name,grace_logins,auth_method,")
                                                         _T("cert_mapping_method,cert_mapping_data,auth_failures,")
                                                         _T("last_passwd_change,min_passwd_length,disabled_until,")
                                                         _T("last_login,xmpp_id FROM users"));
    if (hResult == NULL)
-      return FALSE;
+   {
+      DBConnectionPoolReleaseConnection(hdb);
+      return false;
+   }
 
    m_userCount = DBGetNumRows(hResult);
    m_users = (UserDatabaseObject **)malloc(sizeof(UserDatabaseObject *) * m_userCount);
    for(i = 0; i < m_userCount; i++)
-               m_users[i] = new User(hResult, i);
+               m_users[i] = new User(hdb, hResult, i);
 
    DBFreeResult(hResult);
 
@@ -159,15 +164,18 @@ BOOL LoadUsers()
    }
 
    // Load groups
-   hResult = DBSelect(g_hCoreDB, _T("SELECT id,name,system_access,flags,description,guid,ldap_dn FROM user_groups"));
+   hResult = DBSelect(hdb, _T("SELECT id,name,system_access,flags,description,guid,ldap_dn FROM user_groups"));
    if (hResult == NULL)
+   {
+      DBConnectionPoolReleaseConnection(hdb);
       return FALSE;
+   }
 
        int mark = m_userCount;
    m_userCount += DBGetNumRows(hResult);
    m_users = (UserDatabaseObject **)realloc(m_users, sizeof(UserDatabaseObject *) * m_userCount);
    for(i = mark; i < m_userCount; i++)
-               m_users[i] = new Group(hResult, i - mark);
+               m_users[i] = new Group(hdb, hResult, i - mark);
 
    DBFreeResult(hResult);
 
@@ -185,6 +193,7 @@ BOOL LoadUsers()
       nxlog_write(MSG_EVERYONE_GROUP_CREATED, EVENTLOG_WARNING_TYPE, NULL);
    }
 
+   DBConnectionPoolReleaseConnection(hdb);
    return TRUE;
 }
 
@@ -1090,10 +1099,12 @@ UINT32 NXCORE_EXPORTABLE SetUserPassword(UINT32 id, const TCHAR *newPassword, co
                                int passwordHistoryLength = ConfigReadInt(_T("PasswordHistoryLength"), 0);
                                if (passwordHistoryLength > 0)
                                {
+                                  DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
                                        TCHAR query[8192], *ph = NULL;
 
                                        _sntprintf(query, 8192, _T("SELECT password_history FROM users WHERE id=%d"), id);
-                                       DB_RESULT hResult = DBSelect(g_hCoreDB, query);
+                                       DB_RESULT hResult = DBSelect(hdb, query);
                                        if (hResult != NULL)
                                        {
                                                if (DBGetNumRows(hResult) > 0)
@@ -1143,7 +1154,7 @@ UINT32 NXCORE_EXPORTABLE SetUserPassword(UINT32 id, const TCHAR *newPassword, co
                                                        BinToStr(newPasswdHash, SHA1_DIGEST_SIZE, &ph[(phLen - 1) * SHA1_DIGEST_SIZE * 2]);
 
                                                        _sntprintf(query, 8192, _T("UPDATE users SET password_history='%s' WHERE id=%d"), ph, id);
-                                                       DBQuery(g_hCoreDB, query);
+                                                       DBQuery(hdb, query);
                                                }
 
                                                free(ph);
@@ -1155,6 +1166,7 @@ UINT32 NXCORE_EXPORTABLE SetUserPassword(UINT32 id, const TCHAR *newPassword, co
                                                dwResult = RCC_DB_FAILURE;
                                                break;
                                        }
+                                       DBConnectionPoolReleaseConnection(hdb);
                                }
 
                                user->updatePasswordChangeTime();
index 80a16ca..4c2b9fa 100644 (file)
@@ -66,7 +66,7 @@ static void CalculatePasswordHash(const TCHAR *password, PasswordHashType type,
  * Expects fields in the following order:
  *    id,name,system_access,flags,description,guid,ldap_dn
  */
-UserDatabaseObject::UserDatabaseObject(DB_RESULT hResult, int row)
+UserDatabaseObject::UserDatabaseObject(DB_HANDLE hdb, DB_RESULT hResult, int row)
 {
        m_id = DBGetFieldULong(hResult, row, 0);
        DBGetField(hResult, row, 1, m_name, MAX_USER_NAME);
@@ -349,7 +349,7 @@ void UserDatabaseObject::disable()
  *    auth_failures,last_passwd_change,min_passwd_length,disabled_until,
  *    last_login,xmpp_id
  */
-User::User(DB_RESULT hResult, int row) : UserDatabaseObject(hResult, row)
+User::User(DB_HANDLE hdb, DB_RESULT hResult, int row) : UserDatabaseObject(hdb, hResult, row)
 {
        TCHAR buffer[256];
 
@@ -399,7 +399,7 @@ User::User(DB_RESULT hResult, int row) : UserDatabaseObject(hResult, row)
        if (m_id == 0)
                m_systemRights = SYSTEM_ACCESS_FULL;
 
-       loadCustomAttributes(g_hCoreDB);
+       loadCustomAttributes(hdb);
 }
 
 /**
@@ -709,13 +709,13 @@ void User::setFullName(const TCHAR *fullName)
  * Expects fields in the following order:
  *    id,name,system_access,flags,description,guid,ldap_dn
  */
-Group::Group(DB_RESULT hr, int row) : UserDatabaseObject(hr, row)
+Group::Group(DB_HANDLE hdb, DB_RESULT hr, int row) : UserDatabaseObject(hdb, hr, row)
 {
        DB_RESULT hResult;
        TCHAR query[256];
 
        _sntprintf(query, 256, _T("SELECT user_id FROM user_group_members WHERE group_id=%d"), m_id);
-   hResult = DBSelect(g_hCoreDB, query);
+   hResult = DBSelect(hdb, query);
    if (hResult != NULL)
        {
                m_memberCount = DBGetNumRows(hResult);
@@ -732,7 +732,7 @@ Group::Group(DB_RESULT hr, int row) : UserDatabaseObject(hr, row)
                DBFreeResult(hResult);
        }
 
-       loadCustomAttributes(g_hCoreDB);
+       loadCustomAttributes(hdb);
 }
 
 /**
index 20285ea..d6c98c1 100644 (file)
@@ -55,19 +55,19 @@ VPNConnector::~VPNConnector()
 /**
  * Create object from database data
  */
-BOOL VPNConnector::loadFromDatabase(UINT32 dwId)
+bool VPNConnector::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
    // Load network lists
    TCHAR szQuery[256];
    _sntprintf(szQuery, 256, _T("SELECT ip_addr,ip_netmask,network_type FROM vpn_connector_networks WHERE vpn_id=%d"), m_id);
-   DB_RESULT hResult = DBSelect(g_hCoreDB, szQuery);
+   DB_RESULT hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
    int count = DBGetNumRows(hResult);
    for(int i = 0; i < count; i++)
    {
@@ -82,11 +82,11 @@ BOOL VPNConnector::loadFromDatabase(UINT32 dwId)
 
    // Load custom properties
    _sntprintf(szQuery, 256, _T("SELECT node_id,peer_gateway FROM vpn_connectors WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
-   BOOL success = FALSE;
+   bool success = false;
    if (DBGetNumRows(hResult) != 0)
    {
       UINT32 dwNodeId = DBGetFieldULong(hResult, 0, 0);
@@ -108,19 +108,19 @@ BOOL VPNConnector::loadFromDatabase(UINT32 dwId)
          {
             pObject->AddChild(this);
             AddParent(pObject);
-            success = TRUE;
+            success = true;
          }
       }
       else
       {
-         success = TRUE;
+         success = true;
       }
    }
 
    DBFreeResult(hResult);
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
    return success;
 }
index e1ce915..ae400ad 100644 (file)
@@ -67,20 +67,18 @@ Zone::~Zone()
 /**
  * Create object from database data
  */
-BOOL Zone::loadFromDatabase(UINT32 dwId)
+bool Zone::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
 {
-   TCHAR szQuery[256];
-   DB_RESULT hResult;
-
    m_id = dwId;
 
-   if (!loadCommonProperties())
-      return FALSE;
+   if (!loadCommonProperties(hdb))
+      return false;
 
+   TCHAR szQuery[256];
    _sntprintf(szQuery, 256, _T("SELECT zone_guid,agent_proxy,snmp_proxy,icmp_proxy FROM zones WHERE id=%d"), dwId);
-   hResult = DBSelect(g_hCoreDB, szQuery);
+   DB_RESULT hResult = DBSelect(hdb, szQuery);
    if (hResult == NULL)
-      return FALSE;     // Query failed
+      return false;     // Query failed
 
    if (DBGetNumRows(hResult) == 0)
    {
@@ -88,12 +86,12 @@ BOOL Zone::loadFromDatabase(UINT32 dwId)
       if (dwId == BUILTIN_OID_ZONE0)
       {
          m_zoneId = 0;
-         return TRUE;
+         return true;
       }
       else
       {
                        DbgPrintf(4, _T("Cannot load zone object %ld - missing record in \"zones\" table"), (long)m_id);
-         return FALSE;
+         return false;
       }
    }
 
@@ -105,9 +103,9 @@ BOOL Zone::loadFromDatabase(UINT32 dwId)
    DBFreeResult(hResult);
 
    // Load access list
-   loadACLFromDB();
+   loadACLFromDB(hdb);
 
-   return TRUE;
+   return true;
 }
 
 /**
index abfe84a..d7f9ae6 100644 (file)
@@ -63,7 +63,7 @@ public:
        ~MappingTable();
 
        static MappingTable *createFromMessage(NXCPMessage *msg);
-       static MappingTable *createFromDatabase(LONG id);
+       static MappingTable *createFromDatabase(DB_HANDLE hdb, LONG id);
 
        bool saveToDatabase();
        bool deleteFromDatabase();
index 4aae025..f0c9910 100644 (file)
@@ -862,6 +862,7 @@ public:
  * Functions
  */
 bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
+bool NXCORE_EXPORTABLE ConfigReadStrEx(DB_HANDLE hdb, const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
 #ifdef UNICODE
 bool NXCORE_EXPORTABLE ConfigReadStrA(const WCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
 #else
@@ -869,6 +870,7 @@ bool NXCORE_EXPORTABLE ConfigReadStrA(const WCHAR *szVar, char *szBuffer, int iB
 #endif
 bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
 int NXCORE_EXPORTABLE ConfigReadInt(const TCHAR *szVar, int iDefault);
+int NXCORE_EXPORTABLE ConfigReadIntEx(DB_HANDLE hdb, const TCHAR *szVar, int iDefault);
 UINT32 NXCORE_EXPORTABLE ConfigReadULong(const TCHAR *szVar, UINT32 dwDefault);
 bool NXCORE_EXPORTABLE ConfigReadByteArray(const TCHAR *pszVar, int *pnArray, int nSize, int nDefault);
 bool NXCORE_EXPORTABLE ConfigWriteStr(const TCHAR *szVar, const TCHAR *szValue, bool bCreate, bool isVisible = true, bool needRestart = false);
@@ -1110,7 +1112,6 @@ extern TCHAR g_szDbPassword[];
 extern TCHAR g_szDbName[];
 extern TCHAR g_szDbSchema[];
 extern DB_DRIVER g_dbDriver;
-extern DB_HANDLE NXCORE_EXPORTABLE g_hCoreDB;
 extern Queue *g_dbWriterQueue;
 extern Queue *g_dciDataWriterQueue;
 extern Queue *g_dciRawDataWriterQueue;
index f4d338b..330d774 100644 (file)
@@ -206,7 +206,7 @@ protected:
    void lock() { MutexLock(m_hMutex); }
    void unlock() { MutexUnlock(m_hMutex); }
 
-       BOOL loadCustomSchedules();
+       bool loadCustomSchedules(DB_HANDLE hdb);
    bool matchSchedule(struct tm *pCurrTime, TCHAR *pszSchedule, BOOL *bWithSeconds, time_t currTimestamp);
 
        void expandMacros(const TCHAR *src, TCHAR *dst, size_t dstLen);
@@ -229,7 +229,7 @@ public:
 
    virtual BOOL saveToDB(DB_HANDLE hdb);
    virtual void deleteFromDatabase();
-   virtual bool loadThresholdsFromDB();
+   virtual bool loadThresholdsFromDB(DB_HANDLE hdb);
 
    virtual bool processNewValue(time_t nTimeStamp, const void *value, bool *updateStatus);
    virtual void processNewError();
@@ -336,7 +336,7 @@ protected:
 public:
    DCItem();
    DCItem(const DCItem *pItem);
-   DCItem(DB_RESULT hResult, int iRow, Template *pNode);
+   DCItem(DB_HANDLE hdb, DB_RESULT hResult, int iRow, Template *pNode);
    DCItem(UINT32 dwId, const TCHAR *szName, int iSource, int iDataType,
           int iPollingInterval, int iRetentionTime, Template *pNode,
           const TCHAR *pszDescription = NULL, const TCHAR *systemTag = NULL);
@@ -349,7 +349,7 @@ public:
 
    virtual BOOL saveToDB(DB_HANDLE hdb);
    virtual void deleteFromDatabase();
-   virtual bool loadThresholdsFromDB();
+   virtual bool loadThresholdsFromDB(DB_HANDLE hdb);
 
    void updateCacheSize(UINT32 dwCondId = 0);
    void reloadCache();
@@ -502,11 +502,11 @@ private:
    UINT32 m_deactivationEvent;
    StringSet *m_activeKeys;
 
-   void loadConditions();
+   void loadConditions(DB_HANDLE hdb);
 
 public:
    DCTableThreshold();
-   DCTableThreshold(DB_RESULT hResult, int row);
+   DCTableThreshold(DB_HANDLE hdb, DB_RESULT hResult, int row);
    DCTableThreshold(NXCPMessage *msg, UINT32 *baseId);
    DCTableThreshold(DCTableThreshold *src);
    DCTableThreshold(ConfigEntry *e);
@@ -543,7 +543,7 @@ protected:
    bool transform(Table *value);
    void checkThresholds(Table *value);
 
-   bool loadThresholds();
+   bool loadThresholds(DB_HANDLE hdb);
    bool saveThresholds(DB_HANDLE hdb);
 
 public:
@@ -551,7 +551,7 @@ public:
    DCTable(const DCTable *src);
    DCTable(UINT32 id, const TCHAR *name, int source, int pollingInterval, int retentionTime,
                Template *node, const TCHAR *description = NULL, const TCHAR *systemTag = NULL);
-   DCTable(DB_RESULT hResult, int iRow, Template *pNode);
+   DCTable(DB_HANDLE hdb, DB_RESULT hResult, int iRow, Template *pNode);
    DCTable(ConfigEntry *config, Template *owner);
        virtual ~DCTable();
 
index df8d1b1..9a90f36 100644 (file)
@@ -159,7 +159,7 @@ public:
    UINT32 getId() const { return m_id; }
    const uuid& getGuid() const { return m_guid; }
    void setId(UINT32 dwNewId) { m_id = dwNewId; }
-   bool loadFromDB();
+   bool loadFromDB(DB_HANDLE hdb);
        void saveToDB(DB_HANDLE hdb);
    bool processEvent(Event *pEvent);
    void createMessage(NXCPMessage *pMsg);
index 43c969c..259645d 100644 (file)
@@ -482,11 +482,11 @@ protected:
 
    void setModified();                  // Used to mark object as modified
 
-   bool loadACLFromDB();
+   bool loadACLFromDB(DB_HANDLE hdb);
    bool saveACLToDB(DB_HANDLE hdb);
-   bool loadCommonProperties();
+   bool loadCommonProperties(DB_HANDLE hdb);
    bool saveCommonProperties(DB_HANDLE hdb);
-       bool loadTrustedNodes();
+       bool loadTrustedNodes(DB_HANDLE hdb);
        bool saveTrustedNodes(DB_HANDLE hdb);
    bool executeQueryOnObject(DB_HANDLE hdb, const TCHAR *query) { return ExecuteQueryOnObject(hdb, m_id, query); }
 
@@ -547,7 +547,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    void setId(UINT32 dwId) { m_id = dwId; setModified(); }
    void generateGuid() { m_guid = uuid::generate(); }
@@ -667,7 +667,7 @@ protected:
 
    virtual void onDataCollectionChange();
 
-   void loadItemsFromDB();
+   void loadItemsFromDB(DB_HANDLE hdb);
    void destroyItems();
    void updateInstanceDiscoveryItems(DCItem *dci);
 
@@ -687,7 +687,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    virtual void calculateCompoundStatus(BOOL bForcedRecalc = FALSE);
 
@@ -785,7 +785,7 @@ public:
    virtual int getObjectClass() const { return OBJECT_INTERFACE; }
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    Node *getParentNode();
    UINT32 getParentNodeId();
@@ -890,7 +890,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    void statusPoll(ClientSession *session, UINT32 rqId, Node *pollerNode, Queue *eventQueue);
 
@@ -921,7 +921,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    bool isLocalAddr(const InetAddress& addr);
    bool isRemoteAddr(const InetAddress& addr);
@@ -1012,7 +1012,7 @@ public:
 
    virtual int getObjectClass() const { return OBJECT_MOBILEDEVICE; }
 
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
 
@@ -1055,7 +1055,7 @@ public:
 
    virtual int getObjectClass() const { return OBJECT_ACCESSPOINT; }
 
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
 
@@ -1102,7 +1102,7 @@ public:
    virtual int getObjectClass() const { return OBJECT_CLUSTER; }
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    virtual void unbindFromTemplate(UINT32 dwTemplateId, bool removeDCI);
 
@@ -1293,7 +1293,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        TCHAR *expandText(const TCHAR *textTemplate, StringMap *inputFields, const TCHAR *userName);
 
@@ -1639,7 +1639,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    void addNode(Node *node) { AddChild(node); node->AddParent(this); calculateCompoundStatus(TRUE); }
 
@@ -1666,10 +1666,10 @@ public:
    virtual ~UniversalRoot();
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
-   virtual void LoadFromDB();
+   void loadFromDatabase(DB_HANDLE hdb);
 
-   void LinkChildObjects();
-   void LinkObject(NetObj *pObject) { AddChild(pObject); pObject->AddParent(this); }
+   void linkChildObjects();
+   void linkObject(NetObj *pObject) { AddChild(pObject); pObject->AddParent(this); }
 };
 
 /**
@@ -1726,7 +1726,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual bool showThresholdSummary();
 
@@ -1783,7 +1783,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 };
 
 /**
@@ -1812,7 +1812,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual bool showThresholdSummary();
 
@@ -1857,7 +1857,7 @@ public:
 
    void AddSubnet(Subnet *pSubnet) { AddChild(pSubnet); pSubnet->AddParent(this); }
    void AddZone(Zone *pZone) { AddChild(pZone); pZone->AddParent(this); }
-   void LoadFromDB(void);
+   void loadFromDatabase(DB_HANDLE hdb);
 };
 
 /**
@@ -1891,7 +1891,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    void lockForPoll();
    void doPoll(PollerInfo *poller);
@@ -1929,7 +1929,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual bool createDeploymentMessage(NXCPMessage *msg);
        virtual bool createUninstallMessage(NXCPMessage *msg);
@@ -1958,7 +1958,7 @@ public:
 
    virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual bool createDeploymentMessage(NXCPMessage *msg);
        virtual bool createUninstallMessage(NXCPMessage *msg);
@@ -2066,7 +2066,7 @@ public:
 
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
    virtual void onObjectDelete(UINT32 dwObjectId);
 
@@ -2128,7 +2128,7 @@ public:
 
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
    virtual bool deleteFromDatabase(DB_HANDLE hdb);
-   virtual BOOL loadFromDatabase(UINT32 dwId);
+   virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual bool showThresholdSummary();
 };
@@ -2175,7 +2175,7 @@ public:
 
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
        virtual bool deleteFromDatabase(DB_HANDLE hdb);
-       virtual BOOL loadFromDatabase(UINT32 dwId);
+       virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        virtual void postModify();
 
@@ -2223,7 +2223,7 @@ public:
        ServiceContainer();
        ServiceContainer(const TCHAR *pszName);
 
-       virtual BOOL loadFromDatabase(UINT32 dwId);
+       virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
        virtual bool deleteFromDatabase(DB_HANDLE hdb);
 
@@ -2248,10 +2248,10 @@ public:
        virtual int getObjectClass() const { return OBJECT_BUSINESSSERVICEROOT; }
 
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
-   void LoadFromDB();
+   void loadFromDatabase(DB_HANDLE hdb);
 
-   void LinkChildObjects();
-   void LinkObject(NetObj *pObject) { AddChild(pObject); pObject->AddParent(this); }
+   void linkChildObjects();
+   void linkObject(NetObj *pObject) { AddChild(pObject); pObject->AddParent(this); }
 };
 
 /**
@@ -2277,7 +2277,7 @@ public:
 
        virtual int getObjectClass() const { return OBJECT_BUSINESSSERVICE; }
 
-       virtual BOOL loadFromDatabase(UINT32 dwId);
+       virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
        virtual bool deleteFromDatabase(DB_HANDLE hdb);
 
@@ -2313,7 +2313,7 @@ public:
 
        virtual BOOL saveToDatabase(DB_HANDLE hdb);
        virtual bool deleteFromDatabase(DB_HANDLE hdb);
-       virtual BOOL loadFromDatabase(UINT32 dwId);
+       virtual bool loadFromDatabase(DB_HANDLE hdb, UINT32 id);
 
        void execute();
        void applyTemplates();
index 5ada9ea..7caf176 100644 (file)
@@ -186,7 +186,7 @@ protected:
 
 public:
        UserDatabaseObject();
-       UserDatabaseObject(DB_RESULT hResult, int row);
+       UserDatabaseObject(DB_HANDLE hdb, DB_RESULT hResult, int row);
        UserDatabaseObject(UINT32 id, const TCHAR *name);
        virtual ~UserDatabaseObject();
 
@@ -276,7 +276,7 @@ protected:
 
 public:
        User();
-       User(DB_RESULT hResult, int row);
+       User(DB_HANDLE hdb, DB_RESULT hResult, int row);
        User(UINT32 id, const TCHAR *name);
        virtual ~User();
 
@@ -321,7 +321,7 @@ protected:
 
 public:
        Group();
-       Group(DB_RESULT hResult, int row);
+       Group(DB_HANDLE hdb, DB_RESULT hResult, int row);
        Group(UINT32 id, const TCHAR *name);
        virtual ~Group();
 
index 98b323f..eb575ae 100644 (file)
 #define AF_RESOLVE_NODE_NAMES                  _ULL(0x0000000000100000)
 #define AF_CATCH_EXCEPTIONS                    _ULL(0x0000000000200000)
 #define AF_HELPDESK_LINK_ACTIVE                _ULL(0x0000000000400000)
-#define AF_DB_CONNECTION_POOL_READY            _ULL(0x0000000000800000)
 #define AF_DB_LOCKED                           _ULL(0x0000000001000000)
-#define AF_ENABLE_MULTIPLE_DB_CONN             _ULL(0x0000000002000000)
 #define AF_DB_CONNECTION_LOST                  _ULL(0x0000000004000000)
 #define AF_NO_NETWORK_CONNECTIVITY             _ULL(0x0000000008000000)
 #define AF_EVENT_STORM_DETECTED                _ULL(0x0000000010000000)
index 65af01a..bf5ec05 100644 (file)
@@ -986,4 +986,10 @@ Language=English
 Performance data storage driver "%1" cannot be loaded because of API version mismatch (driver: %3; server: %2)
 .
 
+MessageId=
+SymbolicName=MSG_DBCONNPOOL_INIT_FAILED
+Language=English
+Failed to initialize database connection pool
+.
+
 ;#endif
index 20db7d5..c3da1d4 100644 (file)
@@ -573,6 +573,23 @@ static bool ConvertObjectToolMacros(UINT32 id, const TCHAR *text, const TCHAR *c
    return SQLQuery(query);
 }
 
+/**
+ * Upgrade from V377 to V378
+ */
+static BOOL H_UpgradeFromV377(int currVersion, int newVersion)
+{
+   static TCHAR batch[] =
+      _T("DELETE FROM config WHERE var_name='EnableMultipleDBConnections'\n")
+      _T("UPDATE config SET var_name='DBConnectionPoolBaseSize' WHERE var_name='ConnectionPoolBaseSize'\n")
+      _T("UPDATE config SET var_name='DBConnectionPoolMaxSize' WHERE var_name='ConnectionPoolMaxSize'\n")
+      _T("UPDATE config SET var_name='DBConnectionPoolCooldownTime' WHERE var_name='ConnectionPoolCooldownTime'\n")
+      _T("UPDATE config SET var_name='DBConnectionPoolMaxLifetime' WHERE var_name='ConnectionPoolMaxLifetime'\n")
+      _T("<END>");
+   CHK_EXEC(SQLBatch(batch));
+   CHK_EXEC(SQLQuery(_T("UPDATE metadata SET var_value='378' WHERE var_name='SchemaVersion'")));
+   return TRUE;
+}
+
 /**
  * Upgrade from V376 to V377
  */
@@ -9042,6 +9059,7 @@ static struct
    { 374, 375, H_UpgradeFromV374 },
    { 375, 376, H_UpgradeFromV375 },
    { 376, 377, H_UpgradeFromV376 },
+   { 377, 378, H_UpgradeFromV377 },
    { 0, 0, NULL }
 };