1 /******************************************************************************
3 * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #include "db_ido_pgsql/idopgsqlconnection.hpp"
21 #include "db_ido_pgsql/idopgsqlconnection.tcpp"
22 #include "db_ido/dbtype.hpp"
23 #include "db_ido/dbvalue.hpp"
24 #include "base/logger.hpp"
25 #include "base/objectlock.hpp"
26 #include "base/convert.hpp"
27 #include "base/utility.hpp"
28 #include "base/perfdatavalue.hpp"
29 #include "base/application.hpp"
30 #include "base/configtype.hpp"
31 #include "base/exception.hpp"
32 #include "base/context.hpp"
33 #include "base/statsfunction.hpp"
34 #include <boost/tuple/tuple.hpp>
37 using namespace icinga;
39 REGISTER_TYPE(IdoPgsqlConnection);
41 REGISTER_STATSFUNCTION(IdoPgsqlConnection, &IdoPgsqlConnection::StatsFunc);
43 IdoPgsqlConnection::IdoPgsqlConnection()
45 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
48 void IdoPgsqlConnection::OnConfigLoaded()
50 ObjectImpl<IdoPgsqlConnection>::OnConfigLoaded();
52 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
54 Library shimLibrary{"pgsql_shim"};
56 auto create_pgsql_shim = shimLibrary.GetSymbolAddress<create_pgsql_shim_ptr>("create_pgsql_shim");
58 m_Pgsql.reset(create_pgsql_shim());
60 std::swap(m_Library, shimLibrary);
63 void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
65 Dictionary::Ptr nodes = new Dictionary();
67 for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
68 size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength();
69 double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0;
71 Dictionary::Ptr stats = new Dictionary();
72 stats->Set("version", idopgsqlconnection->GetSchemaVersion());
73 stats->Set("instance_name", idopgsqlconnection->GetInstanceName());
74 stats->Set("connected", idopgsqlconnection->GetConnected());
75 stats->Set("query_queue_items", queryQueueItems);
76 stats->Set("query_queue_item_rate", queryQueueItemRate);
78 nodes->Set(idopgsqlconnection->GetName(), stats);
80 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
81 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
82 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
83 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
84 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", queryQueueItems));
85 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
88 status->Set("idopgsqlconnection", nodes);
91 void IdoPgsqlConnection::Resume()
93 DbConnection::Resume();
95 Log(LogInformation, "IdoPgsqlConnection")
96 << "'" << GetName() << "' resumed.";
100 m_QueryQueue.SetExceptionCallback(std::bind(&IdoPgsqlConnection::ExceptionHandler, this, _1));
102 m_TxTimer = new Timer();
103 m_TxTimer->SetInterval(1);
104 m_TxTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::TxTimerHandler, this));
107 m_ReconnectTimer = new Timer();
108 m_ReconnectTimer->SetInterval(10);
109 m_ReconnectTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::ReconnectTimerHandler, this));
110 m_ReconnectTimer->Start();
111 m_ReconnectTimer->Reschedule(0);
113 ASSERT(m_Pgsql->isthreadsafe());
116 void IdoPgsqlConnection::Pause()
118 Log(LogInformation, "IdoPgsqlConnection")
119 << "'" << GetName() << "' paused.";
121 m_ReconnectTimer.reset();
123 DbConnection::Pause();
125 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Disconnect, this), PriorityHigh);
129 void IdoPgsqlConnection::ExceptionHandler(boost::exception_ptr exp)
131 Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!");
133 Log(LogDebug, "IdoPgsqlConnection")
134 << "Exception during database operation: " << DiagnosticInformation(std::move(exp));
136 if (GetConnected()) {
137 m_Pgsql->finish(m_Connection);
142 void IdoPgsqlConnection::AssertOnWorkQueue()
144 ASSERT(m_QueryQueue.IsWorkerThread());
147 void IdoPgsqlConnection::Disconnect()
156 m_Pgsql->finish(m_Connection);
160 void IdoPgsqlConnection::TxTimerHandler()
165 void IdoPgsqlConnection::NewTransaction()
167 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalNewTransaction, this), PriorityHigh, true);
170 void IdoPgsqlConnection::InternalNewTransaction()
181 void IdoPgsqlConnection::ReconnectTimerHandler()
183 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Reconnect, this), PriorityLow);
186 void IdoPgsqlConnection::Reconnect()
190 CONTEXT("Reconnecting to PostgreSQL IDO database '" + GetName() + "'");
192 double startTime = Utility::GetTime();
194 SetShouldConnect(true);
196 bool reconnect = false;
198 if (GetConnected()) {
199 /* Check if we're really still connected */
203 } catch (const std::exception&) {
204 m_Pgsql->finish(m_Connection);
212 String ihost, iport, iuser, ipasswd, idb;
213 const char *host, *port, *user , *passwd, *db;
218 ipasswd = GetPassword();
221 host = (!ihost.IsEmpty()) ? ihost.CStr() : nullptr;
222 port = (!iport.IsEmpty()) ? iport.CStr() : nullptr;
223 user = (!iuser.IsEmpty()) ? iuser.CStr() : nullptr;
224 passwd = (!ipasswd.IsEmpty()) ? ipasswd.CStr() : nullptr;
225 db = (!idb.IsEmpty()) ? idb.CStr() : nullptr;
227 m_Connection = m_Pgsql->setdbLogin(host, port, nullptr, nullptr, db, user, passwd);
232 if (m_Pgsql->status(m_Connection) != CONNECTION_OK) {
233 String message = m_Pgsql->errorMessage(m_Connection);
234 m_Pgsql->finish(m_Connection);
237 Log(LogCritical, "IdoPgsqlConnection")
238 << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
239 << "' failed: \"" << message << "\"";
241 BOOST_THROW_EXCEPTION(std::runtime_error(message));
246 IdoPgsqlResult result;
248 /* explicitely require legacy mode for string escaping in PostgreSQL >= 9.1
249 * changing standard_conforming_strings to on by default
251 if (m_Pgsql->serverVersion(m_Connection) >= 90100)
252 result = Query("SET standard_conforming_strings TO off");
254 String dbVersionName = "idoutils";
255 result = Query("SELECT version FROM " + GetTablePrefix() + "dbversion WHERE name=E'" + Escape(dbVersionName) + "'");
257 Dictionary::Ptr row = FetchRow(result, 0);
260 m_Pgsql->finish(m_Connection);
263 Log(LogCritical, "IdoPgsqlConnection", "Schema does not provide any valid version! Verify your schema installation.");
265 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid schema."));
268 String version = row->Get("version");
270 SetSchemaVersion(version);
272 if (Utility::CompareVersion(IDO_COMPAT_SCHEMA_VERSION, version) < 0) {
273 m_Pgsql->finish(m_Connection);
276 Log(LogCritical, "IdoPgsqlConnection")
277 << "Schema version '" << version << "' does not match the required version '"
278 << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
279 << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
281 BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
284 String instanceName = GetInstanceName();
286 result = Query("SELECT instance_id FROM " + GetTablePrefix() + "instances WHERE instance_name = E'" + Escape(instanceName) + "'");
287 row = FetchRow(result, 0);
290 Query("INSERT INTO " + GetTablePrefix() + "instances (instance_name, instance_description) VALUES (E'" + Escape(instanceName) + "', E'" + Escape(GetInstanceDescription()) + "')");
291 m_InstanceID = GetSequenceValue(GetTablePrefix() + "instances", "instance_id");
293 m_InstanceID = DbReference(row->Get("instance_id"));
296 Endpoint::Ptr my_endpoint = Endpoint::GetLocalEndpoint();
298 /* we have an endpoint in a cluster setup, so decide if we can proceed here */
299 if (my_endpoint && GetHAMode() == HARunOnce) {
300 /* get the current endpoint writing to programstatus table */
301 result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
302 GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
303 row = FetchRow(result, 0);
305 String endpoint_name;
308 endpoint_name = row->Get("endpoint_name");
310 Log(LogNotice, "IdoPgsqlConnection", "Empty program status table");
312 /* if we did not write into the database earlier, another instance is active */
313 if (endpoint_name != my_endpoint->GetName()) {
314 double status_update_time;
317 status_update_time = row->Get("status_update_time");
319 status_update_time = 0;
321 double status_update_age = Utility::GetTime() - status_update_time;
323 Log(LogNotice, "IdoPgsqlConnection")
324 << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
326 if (status_update_age < GetFailoverTimeout()) {
327 m_Pgsql->finish(m_Connection);
329 SetShouldConnect(false);
334 /* activate the IDO only, if we're authoritative in this zone */
336 Log(LogNotice, "IdoPgsqlConnection")
337 << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
339 m_Pgsql->finish(m_Connection);
346 Log(LogNotice, "IdoPgsqlConnection", "Enabling IDO connection.");
349 Log(LogInformation, "IdoPgsqlConnection")
350 << "pgSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
354 /* update programstatus table */
355 UpdateProgramStatus();
357 /* record connection */
358 Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
359 "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
360 + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
361 + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
363 /* clear config tables for the initial config dump */
366 std::ostringstream q1buf;
367 q1buf << "SELECT object_id, objecttype_id, name1, name2, is_active FROM " + GetTablePrefix() + "objects WHERE instance_id = " << static_cast<long>(m_InstanceID);
368 result = Query(q1buf.str());
370 std::vector<DbObject::Ptr> activeDbObjs;
373 while ((row = FetchRow(result, index))) {
376 DbType::Ptr dbtype = DbType::GetByID(row->Get("objecttype_id"));
381 DbObject::Ptr dbobj = dbtype->GetOrCreateObjectByName(row->Get("name1"), row->Get("name2"));
382 SetObjectID(dbobj, DbReference(row->Get("object_id")));
383 bool active = row->Get("is_active");
384 SetObjectActive(dbobj, active);
387 activeDbObjs.push_back(dbobj);
390 SetIDCacheValid(true);
392 EnableActiveChangedHandler();
394 for (const DbObject::Ptr& dbobj : activeDbObjs) {
395 if (dbobj->GetObject())
398 Log(LogNotice, "IdoPgsqlConnection")
399 << "Deactivate deleted object name1: '" << dbobj->GetName1()
400 << "' name2: '" << dbobj->GetName2() + "'.";
401 DeactivateObject(dbobj);
406 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::ClearTablesBySession, this), PriorityLow);
408 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::FinishConnect, this, startTime), PriorityLow);
411 void IdoPgsqlConnection::FinishConnect(double startTime)
418 Log(LogInformation, "IdoPgsqlConnection")
419 << "Finished reconnecting to PostgreSQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
425 void IdoPgsqlConnection::ClearTablesBySession()
427 /* delete all comments and downtimes without current session token */
428 ClearTableBySession("comments");
429 ClearTableBySession("scheduleddowntime");
432 void IdoPgsqlConnection::ClearTableBySession(const String& table)
434 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
435 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
436 Convert::ToString(GetSessionToken()));
439 IdoPgsqlResult IdoPgsqlConnection::Query(const String& query)
443 Log(LogDebug, "IdoPgsqlConnection")
444 << "Query: " << query;
446 IncreaseQueryCount();
448 PGresult *result = m_Pgsql->exec(m_Connection, query.CStr());
451 String message = m_Pgsql->errorMessage(m_Connection);
452 Log(LogCritical, "IdoPgsqlConnection")
453 << "Error \"" << message << "\" when executing query \"" << query << "\"";
455 BOOST_THROW_EXCEPTION(
457 << errinfo_message(message)
458 << errinfo_database_query(query)
462 char *rowCount = m_Pgsql->cmdTuples(result);
463 m_AffectedRows = atoi(rowCount);
465 if (m_Pgsql->resultStatus(result) == PGRES_COMMAND_OK) {
466 m_Pgsql->clear(result);
467 return IdoPgsqlResult();
470 if (m_Pgsql->resultStatus(result) != PGRES_TUPLES_OK) {
471 String message = m_Pgsql->resultErrorMessage(result);
472 m_Pgsql->clear(result);
474 Log(LogCritical, "IdoPgsqlConnection")
475 << "Error \"" << message << "\" when executing query \"" << query << "\"";
477 BOOST_THROW_EXCEPTION(
479 << errinfo_message(message)
480 << errinfo_database_query(query)
484 return IdoPgsqlResult(result, std::bind(&PgsqlInterface::clear, std::cref(m_Pgsql), _1));
487 DbReference IdoPgsqlConnection::GetSequenceValue(const String& table, const String& column)
491 IdoPgsqlResult result = Query("SELECT CURRVAL(pg_get_serial_sequence(E'" + Escape(table) + "', E'" + Escape(column) + "')) AS id");
493 Dictionary::Ptr row = FetchRow(result, 0);
497 Log(LogDebug, "IdoPgsqlConnection")
498 << "Sequence Value: " << row->Get("id");
500 return {Convert::ToLong(row->Get("id"))};
503 int IdoPgsqlConnection::GetAffectedRows()
507 return m_AffectedRows;
510 String IdoPgsqlConnection::Escape(const String& s)
514 String utf8s = Utility::ValidateUTF8(s);
516 size_t length = utf8s.GetLength();
517 auto *to = new char[utf8s.GetLength() * 2 + 1];
519 m_Pgsql->escapeStringConn(m_Connection, to, utf8s.CStr(), length, nullptr);
521 String result = String(to);
528 Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int row)
532 if (row >= m_Pgsql->ntuples(result.get()))
535 int columns = m_Pgsql->nfields(result.get());
537 Dictionary::Ptr dict = new Dictionary();
539 for (int column = 0; column < columns; column++) {
542 if (!m_Pgsql->getisnull(result.get(), row, column))
543 value = m_Pgsql->getvalue(result.get(), row, column);
545 dict->Set(m_Pgsql->fname(result.get(), column), value);
551 void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj)
553 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalActivateObject, this, dbobj), PriorityLow);
556 void IdoPgsqlConnection::InternalActivateObject(const DbObject::Ptr& dbobj)
563 DbReference dbref = GetObjectID(dbobj);
564 std::ostringstream qbuf;
566 if (!dbref.IsValid()) {
567 if (!dbobj->GetName2().IsEmpty()) {
568 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
569 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
570 << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
572 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
573 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
574 << "E'" << Escape(dbobj->GetName1()) << "', 1)";
578 SetObjectID(dbobj, GetSequenceValue(GetTablePrefix() + "objects", "object_id"));
580 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 1 WHERE object_id = " << static_cast<long>(dbref);
585 void IdoPgsqlConnection::DeactivateObject(const DbObject::Ptr& dbobj)
587 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalDeactivateObject, this, dbobj), PriorityLow);
590 void IdoPgsqlConnection::InternalDeactivateObject(const DbObject::Ptr& dbobj)
597 DbReference dbref = GetObjectID(dbobj);
599 if (!dbref.IsValid())
602 std::ostringstream qbuf;
603 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 0 WHERE object_id = " << static_cast<long>(dbref);
606 /* Note that we're _NOT_ clearing the db refs via SetReference/SetConfigUpdate/SetStatusUpdate
607 * because the object is still in the database. */
610 bool IdoPgsqlConnection::FieldToEscapedString(const String& key, const Value& value, Value *result)
612 if (key == "instance_id") {
613 *result = static_cast<long>(m_InstanceID);
615 } else if (key == "session_token") {
616 *result = GetSessionToken();
620 Value rawvalue = DbValue::ExtractValue(value);
622 if (rawvalue.IsObjectType<ConfigObject>()) {
623 DbObject::Ptr dbobjcol = DbObject::GetOrCreateByObject(rawvalue);
630 if (!IsIDCacheValid())
633 DbReference dbrefcol;
635 if (DbValue::IsObjectInsertID(value)) {
636 dbrefcol = GetInsertID(dbobjcol);
638 if (!dbrefcol.IsValid())
641 dbrefcol = GetObjectID(dbobjcol);
643 if (!dbrefcol.IsValid()) {
644 InternalActivateObject(dbobjcol);
646 dbrefcol = GetObjectID(dbobjcol);
648 if (!dbrefcol.IsValid())
653 *result = static_cast<long>(dbrefcol);
654 } else if (DbValue::IsTimestamp(value)) {
656 std::ostringstream msgbuf;
657 msgbuf << "TO_TIMESTAMP(" << ts << ") AT TIME ZONE 'UTC'";
658 *result = Value(msgbuf.str());
659 } else if (DbValue::IsTimestampNow(value)) {
661 } else if (DbValue::IsObjectInsertID(value)) {
662 auto id = static_cast<long>(rawvalue);
672 if (rawvalue.IsBoolean())
673 fvalue = Convert::ToLong(rawvalue);
677 *result = "E'" + Escape(fvalue) + "'";
683 void IdoPgsqlConnection::ExecuteQuery(const DbQuery& query)
685 ASSERT(query.Category != DbCatInvalid);
687 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority, true);
690 void IdoPgsqlConnection::ExecuteMultipleQueries(const std::vector<DbQuery>& queries)
695 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), queries[0].Priority, true);
698 bool IdoPgsqlConnection::CanExecuteQuery(const DbQuery& query)
700 if (query.Object && !IsIDCacheValid())
703 if (query.WhereCriteria) {
704 ObjectLock olock(query.WhereCriteria);
707 for (const Dictionary::Pair& kv : query.WhereCriteria) {
708 if (!FieldToEscapedString(kv.first, kv.second, &value))
714 ObjectLock olock(query.Fields);
716 for (const Dictionary::Pair& kv : query.Fields) {
719 if (kv.second.IsEmpty() && !kv.second.IsString())
722 if (!FieldToEscapedString(kv.first, kv.second, &value))
730 void IdoPgsqlConnection::InternalExecuteMultipleQueries(const std::vector<DbQuery>& queries)
737 for (const DbQuery& query : queries) {
738 ASSERT(query.Type == DbQueryNewTransaction || query.Category != DbCatInvalid);
740 if (!CanExecuteQuery(query)) {
741 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), query.Priority);
746 for (const DbQuery& query : queries) {
747 InternalExecuteQuery(query);
751 void IdoPgsqlConnection::InternalExecuteQuery(const DbQuery& query, int typeOverride)
758 if (query.Type == DbQueryNewTransaction) {
759 InternalNewTransaction();
763 /* check whether we're allowed to execute the query first */
764 if (GetCategoryFilter() != DbCatEverything && (query.Category & GetCategoryFilter()) == 0)
767 if (query.Object && query.Object->GetObject()->GetExtension("agent_check").ToBool())
770 /* check if there are missing object/insert ids and re-enqueue the query */
771 if (!CanExecuteQuery(query)) {
772 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, typeOverride), query.Priority);
776 std::ostringstream qbuf, where;
779 if (query.WhereCriteria) {
782 ObjectLock olock(query.WhereCriteria);
786 for (const Dictionary::Pair& kv : query.WhereCriteria) {
787 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
788 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
795 where << kv.first << " = " << value;
802 type = (typeOverride != -1) ? typeOverride : query.Type;
806 if ((type & DbQueryInsert) && (type & DbQueryUpdate)) {
810 if (query.ConfigUpdate)
811 hasid = GetConfigUpdate(query.Object);
812 else if (query.StatusUpdate)
813 hasid = GetStatusUpdate(query.Object);
819 type = DbQueryUpdate;
822 if ((type & DbQueryInsert) && (type & DbQueryDelete)) {
823 std::ostringstream qdel;
824 qdel << "DELETE FROM " << GetTablePrefix() << query.Table << where.str();
827 type = DbQueryInsert;
832 qbuf << "INSERT INTO " << GetTablePrefix() << query.Table;
835 qbuf << "UPDATE " << GetTablePrefix() << query.Table << " SET";
838 qbuf << "DELETE FROM " << GetTablePrefix() << query.Table;
841 VERIFY(!"Invalid query type.");
844 if (type == DbQueryInsert || type == DbQueryUpdate) {
845 std::ostringstream colbuf, valbuf;
847 if (type == DbQueryUpdate && query.Fields->GetLength() == 0)
850 ObjectLock olock(query.Fields);
854 for (const Dictionary::Pair& kv : query.Fields) {
855 if (kv.second.IsEmpty() && !kv.second.IsString())
858 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
859 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
863 if (type == DbQueryInsert) {
875 qbuf << " " << kv.first << " = " << value;
882 if (type == DbQueryInsert)
883 qbuf << " (" << colbuf.str() << ") VALUES (" << valbuf.str() << ")";
886 if (type != DbQueryInsert)
891 if (upsert && GetAffectedRows() == 0) {
892 InternalExecuteQuery(query, DbQueryDelete | DbQueryInsert);
897 if (type == DbQueryInsert && query.Object) {
898 if (query.ConfigUpdate) {
899 String idField = query.IdColumn;
901 if (idField.IsEmpty())
902 idField = query.Table.SubStr(0, query.Table.GetLength() - 1) + "_id";
904 SetInsertID(query.Object, GetSequenceValue(GetTablePrefix() + query.Table, idField));
906 SetConfigUpdate(query.Object, true);
907 } else if (query.StatusUpdate)
908 SetStatusUpdate(query.Object, true);
911 if (type == DbQueryInsert && query.Table == "notifications" && query.NotificationInsertID) {
912 DbReference seqval = GetSequenceValue(GetTablePrefix() + query.Table, "notification_id");
913 query.NotificationInsertID->SetValue(static_cast<long>(seqval));
917 void IdoPgsqlConnection::CleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
919 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalCleanUpExecuteQuery, this, table, time_column, max_age), PriorityLow, true);
922 void IdoPgsqlConnection::InternalCleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
929 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
930 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
931 " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ")");
934 void IdoPgsqlConnection::FillIDCache(const DbType::Ptr& type)
936 String query = "SELECT " + type->GetIDColumn() + " AS object_id, " + type->GetTable() + "_id, config_hash FROM " + GetTablePrefix() + type->GetTable() + "s";
937 IdoPgsqlResult result = Query(query);
942 while ((row = FetchRow(result, index))) {
944 DbReference dbref(row->Get("object_id"));
945 SetInsertID(type, dbref, DbReference(row->Get(type->GetTable() + "_id")));
946 SetConfigHash(type, dbref, row->Get("config_hash"));
950 int IdoPgsqlConnection::GetPendingQueryCount() const
952 return m_QueryQueue.GetLength();