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>
36 using namespace icinga;
38 REGISTER_TYPE(IdoPgsqlConnection);
40 REGISTER_STATSFUNCTION(IdoPgsqlConnection, &IdoPgsqlConnection::StatsFunc);
42 IdoPgsqlConnection::IdoPgsqlConnection(void)
43 : m_QueryQueue(1000000)
45 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
48 void IdoPgsqlConnection::OnConfigLoaded(void)
50 ObjectImpl<IdoPgsqlConnection>::OnConfigLoaded();
52 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
55 void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
57 Dictionary::Ptr nodes = new Dictionary();
59 for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
60 size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength();
61 double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0;
63 Dictionary::Ptr stats = new Dictionary();
64 stats->Set("version", idopgsqlconnection->GetSchemaVersion());
65 stats->Set("instance_name", idopgsqlconnection->GetInstanceName());
66 stats->Set("connected", idopgsqlconnection->GetConnected());
67 stats->Set("query_queue_items", queryQueueItems);
68 stats->Set("query_queue_item_rate", queryQueueItemRate);
70 nodes->Set(idopgsqlconnection->GetName(), stats);
72 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
73 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
74 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
75 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
76 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", queryQueueItems));
77 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
80 status->Set("idopgsqlconnection", nodes);
83 void IdoPgsqlConnection::Resume(void)
85 DbConnection::Resume();
87 Log(LogInformation, "IdoPgsqlConnection")
88 << "'" << GetName() << "' resumed.";
92 m_QueryQueue.SetExceptionCallback(std::bind(&IdoPgsqlConnection::ExceptionHandler, this, _1));
94 m_TxTimer = new Timer();
95 m_TxTimer->SetInterval(1);
96 m_TxTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::TxTimerHandler, this));
99 m_ReconnectTimer = new Timer();
100 m_ReconnectTimer->SetInterval(10);
101 m_ReconnectTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::ReconnectTimerHandler, this));
102 m_ReconnectTimer->Start();
103 m_ReconnectTimer->Reschedule(0);
105 ASSERT(PQisthreadsafe());
108 void IdoPgsqlConnection::Pause(void)
110 Log(LogInformation, "IdoPgsqlConnection")
111 << "'" << GetName() << "' paused.";
113 m_ReconnectTimer.reset();
115 DbConnection::Pause();
117 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Disconnect, this), PriorityHigh);
121 void IdoPgsqlConnection::ExceptionHandler(boost::exception_ptr exp)
123 Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!");
125 Log(LogDebug, "IdoPgsqlConnection")
126 << "Exception during database operation: " << DiagnosticInformation(exp);
128 if (GetConnected()) {
129 PQfinish(m_Connection);
134 void IdoPgsqlConnection::AssertOnWorkQueue(void)
136 ASSERT(m_QueryQueue.IsWorkerThread());
139 void IdoPgsqlConnection::Disconnect(void)
148 PQfinish(m_Connection);
152 void IdoPgsqlConnection::TxTimerHandler(void)
157 void IdoPgsqlConnection::NewTransaction(void)
159 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalNewTransaction, this), PriorityHigh, true);
162 void IdoPgsqlConnection::InternalNewTransaction(void)
173 void IdoPgsqlConnection::ReconnectTimerHandler(void)
175 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Reconnect, this), PriorityLow);
178 void IdoPgsqlConnection::Reconnect(void)
182 CONTEXT("Reconnecting to PostgreSQL IDO database '" + GetName() + "'");
184 double startTime = Utility::GetTime();
186 SetShouldConnect(true);
188 bool reconnect = false;
190 if (GetConnected()) {
191 /* Check if we're really still connected */
195 } catch (const std::exception&) {
196 PQfinish(m_Connection);
204 String ihost, iport, iuser, ipasswd, idb;
205 const char *host, *port, *user , *passwd, *db;
210 ipasswd = GetPassword();
213 host = (!ihost.IsEmpty()) ? ihost.CStr() : nullptr;
214 port = (!iport.IsEmpty()) ? iport.CStr() : nullptr;
215 user = (!iuser.IsEmpty()) ? iuser.CStr() : nullptr;
216 passwd = (!ipasswd.IsEmpty()) ? ipasswd.CStr() : nullptr;
217 db = (!idb.IsEmpty()) ? idb.CStr() : nullptr;
219 m_Connection = PQsetdbLogin(host, port, nullptr, nullptr, db, user, passwd);
224 if (PQstatus(m_Connection) != CONNECTION_OK) {
225 String message = PQerrorMessage(m_Connection);
226 PQfinish(m_Connection);
229 Log(LogCritical, "IdoPgsqlConnection")
230 << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
231 << "' failed: \"" << message << "\"";
233 BOOST_THROW_EXCEPTION(std::runtime_error(message));
238 IdoPgsqlResult result;
240 /* explicitely require legacy mode for string escaping in PostgreSQL >= 9.1
241 * changing standard_conforming_strings to on by default
243 if (PQserverVersion(m_Connection) >= 90100)
244 result = Query("SET standard_conforming_strings TO off");
246 String dbVersionName = "idoutils";
247 result = Query("SELECT version FROM " + GetTablePrefix() + "dbversion WHERE name=E'" + Escape(dbVersionName) + "'");
249 Dictionary::Ptr row = FetchRow(result, 0);
252 PQfinish(m_Connection);
255 Log(LogCritical, "IdoPgsqlConnection", "Schema does not provide any valid version! Verify your schema installation.");
257 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid schema."));
260 String version = row->Get("version");
262 SetSchemaVersion(version);
264 if (Utility::CompareVersion(IDO_COMPAT_SCHEMA_VERSION, version) < 0) {
265 PQfinish(m_Connection);
268 Log(LogCritical, "IdoPgsqlConnection")
269 << "Schema version '" << version << "' does not match the required version '"
270 << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
271 << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
273 BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
276 String instanceName = GetInstanceName();
278 result = Query("SELECT instance_id FROM " + GetTablePrefix() + "instances WHERE instance_name = E'" + Escape(instanceName) + "'");
279 row = FetchRow(result, 0);
282 Query("INSERT INTO " + GetTablePrefix() + "instances (instance_name, instance_description) VALUES (E'" + Escape(instanceName) + "', E'" + Escape(GetInstanceDescription()) + "')");
283 m_InstanceID = GetSequenceValue(GetTablePrefix() + "instances", "instance_id");
285 m_InstanceID = DbReference(row->Get("instance_id"));
288 Endpoint::Ptr my_endpoint = Endpoint::GetLocalEndpoint();
290 /* we have an endpoint in a cluster setup, so decide if we can proceed here */
291 if (my_endpoint && GetHAMode() == HARunOnce) {
292 /* get the current endpoint writing to programstatus table */
293 result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
294 GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
295 row = FetchRow(result, 0);
297 String endpoint_name;
300 endpoint_name = row->Get("endpoint_name");
302 Log(LogNotice, "IdoPgsqlConnection", "Empty program status table");
304 /* if we did not write into the database earlier, another instance is active */
305 if (endpoint_name != my_endpoint->GetName()) {
306 double status_update_time;
309 status_update_time = row->Get("status_update_time");
311 status_update_time = 0;
313 double status_update_age = Utility::GetTime() - status_update_time;
315 Log(LogNotice, "IdoPgsqlConnection")
316 << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
318 if (status_update_age < GetFailoverTimeout()) {
319 PQfinish(m_Connection);
321 SetShouldConnect(false);
326 /* activate the IDO only, if we're authoritative in this zone */
328 Log(LogNotice, "IdoPgsqlConnection")
329 << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
331 PQfinish(m_Connection);
338 Log(LogNotice, "IdoPgsqlConnection", "Enabling IDO connection.");
341 Log(LogInformation, "IdoPgsqlConnection")
342 << "pgSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
346 /* update programstatus table */
347 UpdateProgramStatus();
349 /* record connection */
350 Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
351 "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
352 + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
353 + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
355 /* clear config tables for the initial config dump */
358 std::ostringstream q1buf;
359 q1buf << "SELECT object_id, objecttype_id, name1, name2, is_active FROM " + GetTablePrefix() + "objects WHERE instance_id = " << static_cast<long>(m_InstanceID);
360 result = Query(q1buf.str());
362 std::vector<DbObject::Ptr> activeDbObjs;
365 while ((row = FetchRow(result, index))) {
368 DbType::Ptr dbtype = DbType::GetByID(row->Get("objecttype_id"));
373 DbObject::Ptr dbobj = dbtype->GetOrCreateObjectByName(row->Get("name1"), row->Get("name2"));
374 SetObjectID(dbobj, DbReference(row->Get("object_id")));
375 bool active = row->Get("is_active");
376 SetObjectActive(dbobj, active);
379 activeDbObjs.push_back(dbobj);
382 SetIDCacheValid(true);
384 EnableActiveChangedHandler();
386 for (const DbObject::Ptr& dbobj : activeDbObjs) {
387 if (dbobj->GetObject())
390 Log(LogNotice, "IdoPgsqlConnection")
391 << "Deactivate deleted object name1: '" << dbobj->GetName1()
392 << "' name2: '" << dbobj->GetName2() + "'.";
393 DeactivateObject(dbobj);
398 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::ClearTablesBySession, this), PriorityLow);
400 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::FinishConnect, this, startTime), PriorityLow);
403 void IdoPgsqlConnection::FinishConnect(double startTime)
410 Log(LogInformation, "IdoPgsqlConnection")
411 << "Finished reconnecting to PostgreSQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
417 void IdoPgsqlConnection::ClearTablesBySession(void)
419 /* delete all comments and downtimes without current session token */
420 ClearTableBySession("comments");
421 ClearTableBySession("scheduleddowntime");
424 void IdoPgsqlConnection::ClearTableBySession(const String& table)
426 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
427 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
428 Convert::ToString(GetSessionToken()));
431 IdoPgsqlResult IdoPgsqlConnection::Query(const String& query)
435 Log(LogDebug, "IdoPgsqlConnection")
436 << "Query: " << query;
438 IncreaseQueryCount();
440 PGresult *result = PQexec(m_Connection, query.CStr());
443 String message = PQerrorMessage(m_Connection);
444 Log(LogCritical, "IdoPgsqlConnection")
445 << "Error \"" << message << "\" when executing query \"" << query << "\"";
447 BOOST_THROW_EXCEPTION(
449 << errinfo_message(message)
450 << errinfo_database_query(query)
454 char *rowCount = PQcmdTuples(result);
455 m_AffectedRows = atoi(rowCount);
457 if (PQresultStatus(result) == PGRES_COMMAND_OK) {
459 return IdoPgsqlResult();
462 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
463 String message = PQresultErrorMessage(result);
466 Log(LogCritical, "IdoPgsqlConnection")
467 << "Error \"" << message << "\" when executing query \"" << query << "\"";
469 BOOST_THROW_EXCEPTION(
471 << errinfo_message(message)
472 << errinfo_database_query(query)
476 return IdoPgsqlResult(result, std::ptr_fun(PQclear));
479 DbReference IdoPgsqlConnection::GetSequenceValue(const String& table, const String& column)
483 IdoPgsqlResult result = Query("SELECT CURRVAL(pg_get_serial_sequence(E'" + Escape(table) + "', E'" + Escape(column) + "')) AS id");
485 Dictionary::Ptr row = FetchRow(result, 0);
489 Log(LogDebug, "IdoPgsqlConnection")
490 << "Sequence Value: " << row->Get("id");
492 return DbReference(Convert::ToLong(row->Get("id")));
495 int IdoPgsqlConnection::GetAffectedRows(void)
499 return m_AffectedRows;
502 String IdoPgsqlConnection::Escape(const String& s)
506 String utf8s = Utility::ValidateUTF8(s);
508 size_t length = utf8s.GetLength();
509 char *to = new char[utf8s.GetLength() * 2 + 1];
511 PQescapeStringConn(m_Connection, to, utf8s.CStr(), length, nullptr);
513 String result = String(to);
520 Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int row)
524 if (row >= PQntuples(result.get()))
527 int columns = PQnfields(result.get());
529 Dictionary::Ptr dict = new Dictionary();
531 for (int column = 0; column < columns; column++) {
534 if (!PQgetisnull(result.get(), row, column))
535 value = PQgetvalue(result.get(), row, column);
537 dict->Set(PQfname(result.get(), column), value);
543 void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj)
545 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalActivateObject, this, dbobj), PriorityLow);
548 void IdoPgsqlConnection::InternalActivateObject(const DbObject::Ptr& dbobj)
555 DbReference dbref = GetObjectID(dbobj);
556 std::ostringstream qbuf;
558 if (!dbref.IsValid()) {
559 if (!dbobj->GetName2().IsEmpty()) {
560 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
561 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
562 << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
564 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
565 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
566 << "E'" << Escape(dbobj->GetName1()) << "', 1)";
570 SetObjectID(dbobj, GetSequenceValue(GetTablePrefix() + "objects", "object_id"));
572 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 1 WHERE object_id = " << static_cast<long>(dbref);
577 void IdoPgsqlConnection::DeactivateObject(const DbObject::Ptr& dbobj)
579 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalDeactivateObject, this, dbobj), PriorityLow);
582 void IdoPgsqlConnection::InternalDeactivateObject(const DbObject::Ptr& dbobj)
589 DbReference dbref = GetObjectID(dbobj);
591 if (!dbref.IsValid())
594 std::ostringstream qbuf;
595 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 0 WHERE object_id = " << static_cast<long>(dbref);
598 /* Note that we're _NOT_ clearing the db refs via SetReference/SetConfigUpdate/SetStatusUpdate
599 * because the object is still in the database. */
602 bool IdoPgsqlConnection::FieldToEscapedString(const String& key, const Value& value, Value *result)
604 if (key == "instance_id") {
605 *result = static_cast<long>(m_InstanceID);
607 } else if (key == "session_token") {
608 *result = GetSessionToken();
612 Value rawvalue = DbValue::ExtractValue(value);
614 if (rawvalue.IsObjectType<ConfigObject>()) {
615 DbObject::Ptr dbobjcol = DbObject::GetOrCreateByObject(rawvalue);
622 if (!IsIDCacheValid())
625 DbReference dbrefcol;
627 if (DbValue::IsObjectInsertID(value)) {
628 dbrefcol = GetInsertID(dbobjcol);
630 if (!dbrefcol.IsValid())
633 dbrefcol = GetObjectID(dbobjcol);
635 if (!dbrefcol.IsValid()) {
636 InternalActivateObject(dbobjcol);
638 dbrefcol = GetObjectID(dbobjcol);
640 if (!dbrefcol.IsValid())
645 *result = static_cast<long>(dbrefcol);
646 } else if (DbValue::IsTimestamp(value)) {
648 std::ostringstream msgbuf;
649 msgbuf << "TO_TIMESTAMP(" << ts << ") AT TIME ZONE 'UTC'";
650 *result = Value(msgbuf.str());
651 } else if (DbValue::IsTimestampNow(value)) {
653 } else if (DbValue::IsObjectInsertID(value)) {
654 long id = static_cast<long>(rawvalue);
664 if (rawvalue.IsBoolean())
665 fvalue = Convert::ToLong(rawvalue);
669 *result = "E'" + Escape(fvalue) + "'";
675 void IdoPgsqlConnection::ExecuteQuery(const DbQuery& query)
677 ASSERT(query.Category != DbCatInvalid);
679 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority, true);
682 void IdoPgsqlConnection::ExecuteMultipleQueries(const std::vector<DbQuery>& queries)
687 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), queries[0].Priority, true);
690 bool IdoPgsqlConnection::CanExecuteQuery(const DbQuery& query)
692 if (query.Object && !IsIDCacheValid())
695 if (query.WhereCriteria) {
696 ObjectLock olock(query.WhereCriteria);
699 for (const Dictionary::Pair& kv : query.WhereCriteria) {
700 if (!FieldToEscapedString(kv.first, kv.second, &value))
706 ObjectLock olock(query.Fields);
708 for (const Dictionary::Pair& kv : query.Fields) {
711 if (kv.second.IsEmpty() && !kv.second.IsString())
714 if (!FieldToEscapedString(kv.first, kv.second, &value))
722 void IdoPgsqlConnection::InternalExecuteMultipleQueries(const std::vector<DbQuery>& queries)
729 for (const DbQuery& query : queries) {
730 ASSERT(query.Type == DbQueryNewTransaction || query.Category != DbCatInvalid);
732 if (!CanExecuteQuery(query)) {
733 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), query.Priority);
738 for (const DbQuery& query : queries) {
739 InternalExecuteQuery(query);
743 void IdoPgsqlConnection::InternalExecuteQuery(const DbQuery& query, int typeOverride)
750 if (query.Type == DbQueryNewTransaction) {
751 InternalNewTransaction();
755 /* check whether we're allowed to execute the query first */
756 if (GetCategoryFilter() != DbCatEverything && (query.Category & GetCategoryFilter()) == 0)
759 if (query.Object && query.Object->GetObject()->GetExtension("agent_check").ToBool())
762 /* check if there are missing object/insert ids and re-enqueue the query */
763 if (!CanExecuteQuery(query)) {
764 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, typeOverride), query.Priority);
768 std::ostringstream qbuf, where;
771 if (query.WhereCriteria) {
774 ObjectLock olock(query.WhereCriteria);
778 for (const Dictionary::Pair& kv : query.WhereCriteria) {
779 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
780 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
787 where << kv.first << " = " << value;
794 type = (typeOverride != -1) ? typeOverride : query.Type;
798 if ((type & DbQueryInsert) && (type & DbQueryUpdate)) {
802 if (query.ConfigUpdate)
803 hasid = GetConfigUpdate(query.Object);
804 else if (query.StatusUpdate)
805 hasid = GetStatusUpdate(query.Object);
811 type = DbQueryUpdate;
814 if ((type & DbQueryInsert) && (type & DbQueryDelete)) {
815 std::ostringstream qdel;
816 qdel << "DELETE FROM " << GetTablePrefix() << query.Table << where.str();
819 type = DbQueryInsert;
824 qbuf << "INSERT INTO " << GetTablePrefix() << query.Table;
827 qbuf << "UPDATE " << GetTablePrefix() << query.Table << " SET";
830 qbuf << "DELETE FROM " << GetTablePrefix() << query.Table;
833 VERIFY(!"Invalid query type.");
836 if (type == DbQueryInsert || type == DbQueryUpdate) {
837 std::ostringstream colbuf, valbuf;
839 if (type == DbQueryUpdate && query.Fields->GetLength() == 0)
842 ObjectLock olock(query.Fields);
846 for (const Dictionary::Pair& kv : query.Fields) {
847 if (kv.second.IsEmpty() && !kv.second.IsString())
850 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
851 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
855 if (type == DbQueryInsert) {
867 qbuf << " " << kv.first << " = " << value;
874 if (type == DbQueryInsert)
875 qbuf << " (" << colbuf.str() << ") VALUES (" << valbuf.str() << ")";
878 if (type != DbQueryInsert)
883 if (upsert && GetAffectedRows() == 0) {
884 InternalExecuteQuery(query, DbQueryDelete | DbQueryInsert);
889 if (type == DbQueryInsert && query.Object) {
890 if (query.ConfigUpdate) {
891 String idField = query.IdColumn;
893 if (idField.IsEmpty())
894 idField = query.Table.SubStr(0, query.Table.GetLength() - 1) + "_id";
896 SetInsertID(query.Object, GetSequenceValue(GetTablePrefix() + query.Table, idField));
898 SetConfigUpdate(query.Object, true);
899 } else if (query.StatusUpdate)
900 SetStatusUpdate(query.Object, true);
903 if (type == DbQueryInsert && query.Table == "notifications" && query.NotificationInsertID) {
904 DbReference seqval = GetSequenceValue(GetTablePrefix() + query.Table, "notification_id");
905 query.NotificationInsertID->SetValue(static_cast<long>(seqval));
909 void IdoPgsqlConnection::CleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
911 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalCleanUpExecuteQuery, this, table, time_column, max_age), PriorityLow, true);
914 void IdoPgsqlConnection::InternalCleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
921 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
922 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
923 " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ")");
926 void IdoPgsqlConnection::FillIDCache(const DbType::Ptr& type)
928 String query = "SELECT " + type->GetIDColumn() + " AS object_id, " + type->GetTable() + "_id, config_hash FROM " + GetTablePrefix() + type->GetTable() + "s";
929 IdoPgsqlResult result = Query(query);
934 while ((row = FetchRow(result, index))) {
936 DbReference dbref(row->Get("object_id"));
937 SetInsertID(type, dbref, DbReference(row->Get(type->GetTable() + "_id")));
938 SetConfigHash(type, dbref, row->Get("config_hash"));
942 int IdoPgsqlConnection::GetPendingQueryCount(void) const
944 return m_QueryQueue.GetLength();