1 /******************************************************************************
3 * Copyright (C) 2012-2017 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 "icinga/perfdatavalue.hpp"
25 #include "base/logger.hpp"
26 #include "base/objectlock.hpp"
27 #include "base/convert.hpp"
28 #include "base/utility.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 items = idopgsqlconnection->m_QueryQueue.GetLength();
62 Dictionary::Ptr stats = new Dictionary();
63 stats->Set("version", idopgsqlconnection->GetSchemaVersion());
64 stats->Set("connected", idopgsqlconnection->GetConnected());
65 stats->Set("instance_name", idopgsqlconnection->GetInstanceName());
66 stats->Set("query_queue_items", items);
68 nodes->Set(idopgsqlconnection->GetName(), stats);
70 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
71 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
72 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
73 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
74 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", items));
77 status->Set("idopgsqlconnection", nodes);
80 void IdoPgsqlConnection::Resume(void)
82 DbConnection::Resume();
84 Log(LogInformation, "IdoPgsqlConnection")
85 << "'" << GetName() << "' resumed.";
89 m_QueryQueue.SetExceptionCallback(boost::bind(&IdoPgsqlConnection::ExceptionHandler, this, _1));
91 m_TxTimer = new Timer();
92 m_TxTimer->SetInterval(1);
93 m_TxTimer->OnTimerExpired.connect(boost::bind(&IdoPgsqlConnection::TxTimerHandler, this));
96 m_ReconnectTimer = new Timer();
97 m_ReconnectTimer->SetInterval(10);
98 m_ReconnectTimer->OnTimerExpired.connect(boost::bind(&IdoPgsqlConnection::ReconnectTimerHandler, this));
99 m_ReconnectTimer->Start();
100 m_ReconnectTimer->Reschedule(0);
102 ASSERT(PQisthreadsafe());
105 void IdoPgsqlConnection::Pause(void)
107 Log(LogInformation, "IdoPgsqlConnection")
108 << "'" << GetName() << "' paused.";
110 m_ReconnectTimer.reset();
112 DbConnection::Pause();
114 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::Disconnect, this), PriorityHigh);
118 void IdoPgsqlConnection::ExceptionHandler(boost::exception_ptr exp)
120 Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!");
122 Log(LogDebug, "IdoPgsqlConnection")
123 << "Exception during database operation: " << DiagnosticInformation(exp);
125 if (GetConnected()) {
126 PQfinish(m_Connection);
131 void IdoPgsqlConnection::AssertOnWorkQueue(void)
133 ASSERT(m_QueryQueue.IsWorkerThread());
136 void IdoPgsqlConnection::Disconnect(void)
145 PQfinish(m_Connection);
149 void IdoPgsqlConnection::TxTimerHandler(void)
154 void IdoPgsqlConnection::NewTransaction(void)
156 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalNewTransaction, this), PriorityHigh, true);
159 void IdoPgsqlConnection::InternalNewTransaction(void)
170 void IdoPgsqlConnection::ReconnectTimerHandler(void)
172 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::Reconnect, this), PriorityLow);
175 void IdoPgsqlConnection::Reconnect(void)
179 CONTEXT("Reconnecting to PostgreSQL IDO database '" + GetName() + "'");
181 double startTime = Utility::GetTime();
183 SetShouldConnect(true);
185 bool reconnect = false;
187 if (GetConnected()) {
188 /* Check if we're really still connected */
192 } catch (const std::exception&) {
193 PQfinish(m_Connection);
201 String ihost, iport, iuser, ipasswd, idb;
202 const char *host, *port, *user , *passwd, *db;
207 ipasswd = GetPassword();
210 host = (!ihost.IsEmpty()) ? ihost.CStr() : NULL;
211 port = (!iport.IsEmpty()) ? iport.CStr() : NULL;
212 user = (!iuser.IsEmpty()) ? iuser.CStr() : NULL;
213 passwd = (!ipasswd.IsEmpty()) ? ipasswd.CStr() : NULL;
214 db = (!idb.IsEmpty()) ? idb.CStr() : NULL;
216 m_Connection = PQsetdbLogin(host, port, NULL, NULL, db, user, passwd);
221 if (PQstatus(m_Connection) != CONNECTION_OK) {
222 String message = PQerrorMessage(m_Connection);
223 PQfinish(m_Connection);
226 Log(LogCritical, "IdoPgsqlConnection")
227 << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port
228 << "' failed: \"" << message << "\"";
230 BOOST_THROW_EXCEPTION(std::runtime_error(message));
235 IdoPgsqlResult result;
237 /* explicitely require legacy mode for string escaping in PostgreSQL >= 9.1
238 * changing standard_conforming_strings to on by default
240 if (PQserverVersion(m_Connection) >= 90100)
241 result = Query("SET standard_conforming_strings TO off");
243 String dbVersionName = "idoutils";
244 result = Query("SELECT version FROM " + GetTablePrefix() + "dbversion WHERE name=E'" + Escape(dbVersionName) + "'");
246 Dictionary::Ptr row = FetchRow(result, 0);
249 PQfinish(m_Connection);
252 Log(LogCritical, "IdoPgsqlConnection", "Schema does not provide any valid version! Verify your schema installation.");
254 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid schema."));
257 String version = row->Get("version");
259 SetSchemaVersion(version);
261 if (Utility::CompareVersion(IDO_COMPAT_SCHEMA_VERSION, version) < 0) {
262 PQfinish(m_Connection);
265 Log(LogCritical, "IdoPgsqlConnection")
266 << "Schema version '" << version << "' does not match the required version '"
267 << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
268 << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
270 BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
273 String instanceName = GetInstanceName();
275 result = Query("SELECT instance_id FROM " + GetTablePrefix() + "instances WHERE instance_name = E'" + Escape(instanceName) + "'");
276 row = FetchRow(result, 0);
279 Query("INSERT INTO " + GetTablePrefix() + "instances (instance_name, instance_description) VALUES (E'" + Escape(instanceName) + "', E'" + Escape(GetInstanceDescription()) + "')");
280 m_InstanceID = GetSequenceValue(GetTablePrefix() + "instances", "instance_id");
282 m_InstanceID = DbReference(row->Get("instance_id"));
285 Endpoint::Ptr my_endpoint = Endpoint::GetLocalEndpoint();
287 /* we have an endpoint in a cluster setup, so decide if we can proceed here */
288 if (my_endpoint && GetHAMode() == HARunOnce) {
289 /* get the current endpoint writing to programstatus table */
290 result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
291 GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
292 row = FetchRow(result, 0);
294 String endpoint_name;
297 endpoint_name = row->Get("endpoint_name");
299 Log(LogNotice, "IdoPgsqlConnection", "Empty program status table");
301 /* if we did not write into the database earlier, another instance is active */
302 if (endpoint_name != my_endpoint->GetName()) {
303 double status_update_time;
306 status_update_time = row->Get("status_update_time");
308 status_update_time = 0;
310 double status_update_age = Utility::GetTime() - status_update_time;
312 Log(LogNotice, "IdoPgsqlConnection")
313 << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago.";
315 if (status_update_age < GetFailoverTimeout()) {
316 PQfinish(m_Connection);
318 SetShouldConnect(false);
323 /* activate the IDO only, if we're authoritative in this zone */
325 Log(LogNotice, "IdoPgsqlConnection")
326 << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
328 PQfinish(m_Connection);
335 Log(LogNotice, "IdoPgsqlConnection", "Enabling IDO connection.");
338 Log(LogInformation, "IdoPgsqlConnection")
339 << "pgSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')";
343 /* update programstatus table */
344 UpdateProgramStatus();
346 /* record connection */
347 Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
348 "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
349 + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
350 + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
352 /* clear config tables for the initial config dump */
355 std::ostringstream q1buf;
356 q1buf << "SELECT object_id, objecttype_id, name1, name2, is_active FROM " + GetTablePrefix() + "objects WHERE instance_id = " << static_cast<long>(m_InstanceID);
357 result = Query(q1buf.str());
359 std::vector<DbObject::Ptr> activeDbObjs;
362 while ((row = FetchRow(result, index))) {
365 DbType::Ptr dbtype = DbType::GetByID(row->Get("objecttype_id"));
370 DbObject::Ptr dbobj = dbtype->GetOrCreateObjectByName(row->Get("name1"), row->Get("name2"));
371 SetObjectID(dbobj, DbReference(row->Get("object_id")));
372 bool active = row->Get("is_active");
373 SetObjectActive(dbobj, active);
376 activeDbObjs.push_back(dbobj);
379 SetIDCacheValid(true);
381 EnableActiveChangedHandler();
383 for (const DbObject::Ptr& dbobj : activeDbObjs) {
384 if (dbobj->GetObject())
387 Log(LogNotice, "IdoPgsqlConnection")
388 << "Deactivate deleted object name1: '" << dbobj->GetName1()
389 << "' name2: '" << dbobj->GetName2() + "'.";
390 DeactivateObject(dbobj);
395 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::ClearTablesBySession, this), PriorityLow);
397 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::FinishConnect, this, startTime), PriorityLow);
400 void IdoPgsqlConnection::FinishConnect(double startTime)
407 Log(LogInformation, "IdoPgsqlConnection")
408 << "Finished reconnecting to PostgreSQL IDO database in " << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
414 void IdoPgsqlConnection::ClearTablesBySession(void)
416 /* delete all comments and downtimes without current session token */
417 ClearTableBySession("comments");
418 ClearTableBySession("scheduleddowntime");
421 void IdoPgsqlConnection::ClearTableBySession(const String& table)
423 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
424 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
425 Convert::ToString(GetSessionToken()));
428 IdoPgsqlResult IdoPgsqlConnection::Query(const String& query)
432 Log(LogDebug, "IdoPgsqlConnection")
433 << "Query: " << query;
435 IncreaseQueryCount();
437 PGresult *result = PQexec(m_Connection, query.CStr());
440 String message = PQerrorMessage(m_Connection);
441 Log(LogCritical, "IdoPgsqlConnection")
442 << "Error \"" << message << "\" when executing query \"" << query << "\"";
444 BOOST_THROW_EXCEPTION(
446 << errinfo_message(message)
447 << errinfo_database_query(query)
451 char *rowCount = PQcmdTuples(result);
452 m_AffectedRows = atoi(rowCount);
454 if (PQresultStatus(result) == PGRES_COMMAND_OK) {
456 return IdoPgsqlResult();
459 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
460 String message = PQresultErrorMessage(result);
463 Log(LogCritical, "IdoPgsqlConnection")
464 << "Error \"" << message << "\" when executing query \"" << query << "\"";
466 BOOST_THROW_EXCEPTION(
468 << errinfo_message(message)
469 << errinfo_database_query(query)
473 return IdoPgsqlResult(result, std::ptr_fun(PQclear));
476 DbReference IdoPgsqlConnection::GetSequenceValue(const String& table, const String& column)
480 IdoPgsqlResult result = Query("SELECT CURRVAL(pg_get_serial_sequence(E'" + Escape(table) + "', E'" + Escape(column) + "')) AS id");
482 Dictionary::Ptr row = FetchRow(result, 0);
486 Log(LogDebug, "IdoPgsqlConnection")
487 << "Sequence Value: " << row->Get("id");
489 return DbReference(Convert::ToLong(row->Get("id")));
492 int IdoPgsqlConnection::GetAffectedRows(void)
496 return m_AffectedRows;
499 String IdoPgsqlConnection::Escape(const String& s)
503 String utf8s = Utility::ValidateUTF8(s);
505 size_t length = utf8s.GetLength();
506 char *to = new char[utf8s.GetLength() * 2 + 1];
508 PQescapeStringConn(m_Connection, to, utf8s.CStr(), length, NULL);
510 String result = String(to);
517 Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int row)
521 if (row >= PQntuples(result.get()))
522 return Dictionary::Ptr();
524 int columns = PQnfields(result.get());
526 Dictionary::Ptr dict = new Dictionary();
528 for (int column = 0; column < columns; column++) {
531 if (!PQgetisnull(result.get(), row, column))
532 value = PQgetvalue(result.get(), row, column);
534 dict->Set(PQfname(result.get(), column), value);
540 void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj)
542 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalActivateObject, this, dbobj), PriorityLow);
545 void IdoPgsqlConnection::InternalActivateObject(const DbObject::Ptr& dbobj)
552 DbReference dbref = GetObjectID(dbobj);
553 std::ostringstream qbuf;
555 if (!dbref.IsValid()) {
556 if (!dbobj->GetName2().IsEmpty()) {
557 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
558 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
559 << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
561 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
562 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
563 << "E'" << Escape(dbobj->GetName1()) << "', 1)";
567 SetObjectID(dbobj, GetSequenceValue(GetTablePrefix() + "objects", "object_id"));
569 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 1 WHERE object_id = " << static_cast<long>(dbref);
574 void IdoPgsqlConnection::DeactivateObject(const DbObject::Ptr& dbobj)
576 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalDeactivateObject, this, dbobj), PriorityLow);
579 void IdoPgsqlConnection::InternalDeactivateObject(const DbObject::Ptr& dbobj)
586 DbReference dbref = GetObjectID(dbobj);
588 if (!dbref.IsValid())
591 std::ostringstream qbuf;
592 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 0 WHERE object_id = " << static_cast<long>(dbref);
595 /* Note that we're _NOT_ clearing the db refs via SetReference/SetConfigUpdate/SetStatusUpdate
596 * because the object is still in the database. */
599 bool IdoPgsqlConnection::FieldToEscapedString(const String& key, const Value& value, Value *result)
601 if (key == "instance_id") {
602 *result = static_cast<long>(m_InstanceID);
604 } else if (key == "session_token") {
605 *result = GetSessionToken();
609 Value rawvalue = DbValue::ExtractValue(value);
611 if (rawvalue.IsObjectType<ConfigObject>()) {
612 DbObject::Ptr dbobjcol = DbObject::GetOrCreateByObject(rawvalue);
619 if (!IsIDCacheValid())
622 DbReference dbrefcol;
624 if (DbValue::IsObjectInsertID(value)) {
625 dbrefcol = GetInsertID(dbobjcol);
627 if (!dbrefcol.IsValid())
630 dbrefcol = GetObjectID(dbobjcol);
632 if (!dbrefcol.IsValid()) {
633 InternalActivateObject(dbobjcol);
635 dbrefcol = GetObjectID(dbobjcol);
637 if (!dbrefcol.IsValid())
642 *result = static_cast<long>(dbrefcol);
643 } else if (DbValue::IsTimestamp(value)) {
645 std::ostringstream msgbuf;
646 msgbuf << "TO_TIMESTAMP(" << ts << ") AT TIME ZONE 'UTC'";
647 *result = Value(msgbuf.str());
648 } else if (DbValue::IsTimestampNow(value)) {
650 } else if (DbValue::IsObjectInsertID(value)) {
651 long id = static_cast<long>(rawvalue);
661 if (rawvalue.IsBoolean())
662 fvalue = Convert::ToLong(rawvalue);
666 *result = "E'" + Escape(fvalue) + "'";
672 void IdoPgsqlConnection::ExecuteQuery(const DbQuery& query)
674 ASSERT(query.Category != DbCatInvalid);
676 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority, true);
679 void IdoPgsqlConnection::ExecuteMultipleQueries(const std::vector<DbQuery>& queries)
684 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), queries[0].Priority, true);
687 bool IdoPgsqlConnection::CanExecuteQuery(const DbQuery& query)
689 if (query.Object && !IsIDCacheValid())
692 if (query.WhereCriteria) {
693 ObjectLock olock(query.WhereCriteria);
696 for (const Dictionary::Pair& kv : query.WhereCriteria) {
697 if (!FieldToEscapedString(kv.first, kv.second, &value))
703 ObjectLock olock(query.Fields);
705 for (const Dictionary::Pair& kv : query.Fields) {
708 if (kv.second.IsEmpty() && !kv.second.IsString())
711 if (!FieldToEscapedString(kv.first, kv.second, &value))
719 void IdoPgsqlConnection::InternalExecuteMultipleQueries(const std::vector<DbQuery>& queries)
726 for (const DbQuery& query : queries) {
727 ASSERT(query.Type == DbQueryNewTransaction || query.Category != DbCatInvalid);
729 if (!CanExecuteQuery(query)) {
730 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), query.Priority);
735 for (const DbQuery& query : queries) {
736 InternalExecuteQuery(query);
740 void IdoPgsqlConnection::InternalExecuteQuery(const DbQuery& query, int typeOverride)
747 if (query.Type == DbQueryNewTransaction) {
748 InternalNewTransaction();
752 /* check whether we're allowed to execute the query first */
753 if (GetCategoryFilter() != DbCatEverything && (query.Category & GetCategoryFilter()) == 0)
756 if (query.Object && query.Object->GetObject()->GetExtension("agent_check").ToBool())
759 /* check if there are missing object/insert ids and re-enqueue the query */
760 if (!CanExecuteQuery(query)) {
761 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, typeOverride), query.Priority);
765 std::ostringstream qbuf, where;
768 if (query.WhereCriteria) {
771 ObjectLock olock(query.WhereCriteria);
775 for (const Dictionary::Pair& kv : query.WhereCriteria) {
776 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
777 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
784 where << kv.first << " = " << value;
791 type = (typeOverride != -1) ? typeOverride : query.Type;
795 if ((type & DbQueryInsert) && (type & DbQueryUpdate)) {
799 if (query.ConfigUpdate)
800 hasid = GetConfigUpdate(query.Object);
801 else if (query.StatusUpdate)
802 hasid = GetStatusUpdate(query.Object);
808 type = DbQueryUpdate;
811 if ((type & DbQueryInsert) && (type & DbQueryDelete)) {
812 std::ostringstream qdel;
813 qdel << "DELETE FROM " << GetTablePrefix() << query.Table << where.str();
816 type = DbQueryInsert;
821 qbuf << "INSERT INTO " << GetTablePrefix() << query.Table;
824 qbuf << "UPDATE " << GetTablePrefix() << query.Table << " SET";
827 qbuf << "DELETE FROM " << GetTablePrefix() << query.Table;
830 VERIFY(!"Invalid query type.");
833 if (type == DbQueryInsert || type == DbQueryUpdate) {
834 std::ostringstream colbuf, valbuf;
836 if (type == DbQueryUpdate && query.Fields->GetLength() == 0)
839 ObjectLock olock(query.Fields);
843 for (const Dictionary::Pair& kv : query.Fields) {
844 if (kv.second.IsEmpty() && !kv.second.IsString())
847 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
848 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
852 if (type == DbQueryInsert) {
864 qbuf << " " << kv.first << " = " << value;
871 if (type == DbQueryInsert)
872 qbuf << " (" << colbuf.str() << ") VALUES (" << valbuf.str() << ")";
875 if (type != DbQueryInsert)
880 if (upsert && GetAffectedRows() == 0) {
881 InternalExecuteQuery(query, DbQueryDelete | DbQueryInsert);
886 if (type == DbQueryInsert && query.Object) {
887 if (query.ConfigUpdate) {
888 String idField = query.IdColumn;
890 if (idField.IsEmpty())
891 idField = query.Table.SubStr(0, query.Table.GetLength() - 1) + "_id";
893 SetInsertID(query.Object, GetSequenceValue(GetTablePrefix() + query.Table, idField));
895 SetConfigUpdate(query.Object, true);
896 } else if (query.StatusUpdate)
897 SetStatusUpdate(query.Object, true);
900 if (type == DbQueryInsert && query.Table == "notifications" && query.NotificationInsertID) {
901 DbReference seqval = GetSequenceValue(GetTablePrefix() + query.Table, "notification_id");
902 query.NotificationInsertID->SetValue(static_cast<long>(seqval));
906 void IdoPgsqlConnection::CleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
908 m_QueryQueue.Enqueue(boost::bind(&IdoPgsqlConnection::InternalCleanUpExecuteQuery, this, table, time_column, max_age), PriorityLow, true);
911 void IdoPgsqlConnection::InternalCleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
918 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
919 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
920 " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ")");
923 void IdoPgsqlConnection::FillIDCache(const DbType::Ptr& type)
925 String query = "SELECT " + type->GetIDColumn() + " AS object_id, " + type->GetTable() + "_id, config_hash FROM " + GetTablePrefix() + type->GetTable() + "s";
926 IdoPgsqlResult result = Query(query);
931 while ((row = FetchRow(result, index))) {
933 DbReference dbref(row->Get("object_id"));
934 SetInsertID(type, dbref, DbReference(row->Get(type->GetTable() + "_id")));
935 SetConfigHash(type, dbref, row->Get("config_hash"));
939 int IdoPgsqlConnection::GetPendingQueryCount(void) const
941 return m_QueryQueue.GetLength();