Various plugins: Use the global GAUGE_FORMAT.
[collectd.git] / src / postgresql.c
index fce3588..c240e54 100644 (file)
@@ -1,22 +1,35 @@
 /**
  * collectd - src/postgresql.c
- * Copyright (C) 2008, 2009  Sebastian Harl
+ * Copyright (C) 2008-2012  Sebastian Harl
+ * Copyright (C) 2009       Florian Forster
+ * All rights reserved.
  *
- * 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 the
- * Free Software Foundation; only version 2 of the License is applicable.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
  *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
  *
- * Author:
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Authors:
  *   Sebastian Harl <sh at tokkee.org>
+ *   Florian Forster <octo at verplant.org>
  **/
 
 /*
 #include "configfile.h"
 #include "plugin.h"
 
+#include "utils_cache.h"
+#include "utils_db_query.h"
 #include "utils_complain.h"
 
+#if HAVE_PTHREAD_H
+# include <pthread.h>
+#endif
+
 #include <pg_config_manual.h>
 #include <libpq-fe.h>
 
 #define log_err(...) ERROR ("postgresql: " __VA_ARGS__)
 #define log_warn(...) WARNING ("postgresql: " __VA_ARGS__)
 #define log_info(...) INFO ("postgresql: " __VA_ARGS__)
+#define log_debug(...) DEBUG ("postgresql: " __VA_ARGS__)
 
 #ifndef C_PSQL_DEFAULT_CONF
 # define C_PSQL_DEFAULT_CONF PKGDATADIR "/postgresql_default.conf"
@@ -81,47 +101,46 @@ typedef enum {
        C_PSQL_PARAM_DB,
        C_PSQL_PARAM_USER,
        C_PSQL_PARAM_INTERVAL,
+       C_PSQL_PARAM_INSTANCE,
 } c_psql_param_t;
 
+/* Parameter configuration. Stored as `user data' in the query objects. */
 typedef struct {
-       char  *type;
-       char  *instance_prefix;
-       char **instances_str;
-       int   *instances;
-       int    instances_num;
-       char **values_str; /* may be NULL, even if values_num != 0 in
-                             case the "Column" option has been used */
-       int   *values;
-       int   *ds_types;
-       int    values_num;
-} c_psql_result_t;
-
-typedef struct {
-       char *name;
-       char *stmt;
-
        c_psql_param_t *params;
        int             params_num;
+} c_psql_user_data_t;
 
-       c_psql_result_t *results;
-       int              results_num;
-
-       int min_pg_version;
-       int max_pg_version;
-} c_psql_query_t;
+typedef struct {
+       char *name;
+       char *statement;
+       _Bool store_rates;
+} c_psql_writer_t;
 
 typedef struct {
        PGconn      *conn;
        c_complain_t conn_complaint;
 
        int proto_version;
+       int server_version;
 
        int max_params_num;
 
        /* user configuration */
-       c_psql_query_t **queries;
-       int             *hidden_queries;
-       int              queries_num;
+       udb_query_preparation_area_t **q_prep_areas;
+       udb_query_t    **queries;
+       size_t           queries_num;
+
+       c_psql_writer_t **writers;
+       size_t            writers_num;
+
+       /* make sure we don't access the database object in parallel */
+       pthread_mutex_t   db_lock;
+
+       cdtime_t interval;
+
+       /* writer "caching" settings */
+       cdtime_t commit_interval;
+       cdtime_t next_commit;
 
        char *host;
        char *port;
@@ -129,11 +148,15 @@ typedef struct {
        char *user;
        char *password;
 
+       char *instance;
+
        char *sslmode;
 
        char *krbsrvname;
 
        char *service;
+
+       int ref_cnt;
 } c_psql_database_t;
 
 static char *def_queries[] = {
@@ -147,374 +170,216 @@ static char *def_queries[] = {
 };
 static int def_queries_num = STATIC_ARRAY_SIZE (def_queries);
 
-static c_psql_query_t *queries          = NULL;
-static int             queries_num      = 0;
+static c_psql_database_t **databases     = NULL;
+static size_t              databases_num = 0;
 
-static c_psql_database_t *databases     = NULL;
-static int                databases_num = 0;
+static udb_query_t       **queries       = NULL;
+static size_t              queries_num   = 0;
 
-static c_psql_result_t *c_psql_result_new (c_psql_query_t *query)
-{
-       c_psql_result_t *res;
-
-       ++query->results_num;
-       if (NULL == (query->results = (c_psql_result_t *)realloc (query->results,
-                                       query->results_num * sizeof (*query->results)))) {
-               log_err ("Out of memory.");
-               exit (5);
-       }
-       res = query->results + query->results_num - 1;
+static c_psql_writer_t    *writers       = NULL;
+static size_t              writers_num   = 0;
 
-       res->type    = NULL;
-
-       res->instance_prefix = NULL;
-       res->instances_str   = NULL;
-       res->instances       = NULL;
-       res->instances_num   = 0;
-
-       res->values_str = NULL;
-       res->values     = NULL;
-       res->ds_types   = NULL;
-       res->values_num = 0;
-       return res;
-} /* c_psql_result_new */
-
-static void c_psql_result_delete (c_psql_result_t *res)
+static int c_psql_begin (c_psql_database_t *db)
 {
-       int i;
-
-       sfree (res->type);
-
-       sfree (res->instance_prefix);
+       PGresult *r = PQexec (db->conn, "BEGIN");
 
-       for (i = 0; i < res->instances_num; ++i)
-               sfree (res->instances_str[i]);
-       sfree (res->instances_str);
-       sfree (res->instances);
-       res->instances_num = 0;
+       int status = 1;
 
-       for (i = 0; (NULL != res->values_str) && (i < res->values_num); ++i)
-               sfree (res->values_str[i]);
-       sfree (res->values_str);
-       sfree (res->values);
-       sfree (res->ds_types);
-       res->values_num = 0;
-} /* c_psql_result_delete */
-
-static c_psql_query_t *c_psql_query_new (const char *name)
-{
-       c_psql_query_t *query;
-
-       ++queries_num;
-       if (NULL == (queries = (c_psql_query_t *)realloc (queries,
-                               queries_num * sizeof (*queries)))) {
-               log_err ("Out of memory.");
-               exit (5);
+       if (r != NULL) {
+               if (PGRES_COMMAND_OK == PQresultStatus (r)) {
+                       db->next_commit = cdtime() + db->commit_interval;
+                       status = 0;
+               }
+               else
+                       log_warn ("Failed to initiate ('BEGIN') transaction: %s",
+                                       PQerrorMessage (db->conn));
+               PQclear (r);
        }
-       query = queries + queries_num - 1;
-
-       query->name = sstrdup (name);
-       query->stmt = NULL;
+       return status;
+} /* c_psql_begin */
 
-       query->params     = NULL;
-       query->params_num = 0;
-
-       query->results     = NULL;
-       query->results_num = 0;
-
-       query->min_pg_version = 0;
-       query->max_pg_version = INT_MAX;
-       return query;
-} /* c_psql_query_new */
-
-static int c_psql_query_init (c_psql_query_t *query)
+static int c_psql_commit (c_psql_database_t *db)
 {
-       int i;
-
-       /* Get the data set definitions for each query definition. */
-       for (i = 0; i < query->results_num; ++i) {
-               c_psql_result_t  *res = query->results + i;
-               const data_set_t *ds;
-
-               int j;
+       PGresult *r = PQexec (db->conn, "COMMIT");
 
-               ds = plugin_get_ds (res->type);
-               if (NULL == ds) {
-                       log_err ("Result: Unknown type \"%s\".", res->type);
-                       return -1;
-               }
+       int status = 1;
 
-               if (res->values_num != ds->ds_num) {
-                       log_err ("Result: Invalid type \"%s\" - "
-                                       "expected %i data source%s, got %i.",
-                                       res->type, res->values_num,
-                                       (1 == res->values_num) ? "" : "s",
-                                       ds->ds_num);
-                       return -1;
+       if (r != NULL) {
+               if (PGRES_COMMAND_OK == PQresultStatus (r)) {
+                       db->next_commit = 0;
+                       log_debug ("Successfully committed transaction.");
+                       status = 0;
                }
-
-               for (j = 0; j < res->values_num; ++j)
-                       res->ds_types[j] = ds->ds[j].type;
+               else
+                       log_warn ("Failed to commit transaction: %s",
+                                       PQerrorMessage (db->conn));
+               PQclear (r);
        }
-       return 0;
-} /* c_psql_query_init */
-
-static void c_psql_query_delete (c_psql_query_t *query)
-{
-       int i;
-
-       sfree (query->name);
-       sfree (query->stmt);
-
-       sfree (query->params);
-       query->params_num = 0;
-
-       for (i = 0; i < query->results_num; ++i)
-               c_psql_result_delete (query->results + i);
-       sfree (query->results);
-       query->results_num = 0;
-       return;
-} /* c_psql_query_delete */
-
-static c_psql_query_t *c_psql_query_get (const char *name, int server_version)
-{
-       int i;
-
-       for (i = 0; i < queries_num; ++i)
-               if (0 == strcasecmp (name, queries[i].name)
-                               && ((-1 == server_version)
-                                       || ((queries[i].min_pg_version <= server_version)
-                                               && (server_version <= queries[i].max_pg_version))))
-                       return queries + i;
-       return NULL;
-} /* c_psql_query_get */
+       return status;
+} /* c_psql_commit */
 
 static c_psql_database_t *c_psql_database_new (const char *name)
 {
-       c_psql_database_t *db;
+       c_psql_database_t **tmp;
+       c_psql_database_t  *db;
 
-       ++databases_num;
-       if (NULL == (databases = (c_psql_database_t *)realloc (databases,
-                               databases_num * sizeof (*databases)))) {
+       db = (c_psql_database_t *)malloc (sizeof(*db));
+       if (NULL == db) {
                log_err ("Out of memory.");
-               exit (5);
+               return NULL;
        }
 
-       db = databases + (databases_num - 1);
+       tmp = (c_psql_database_t **)realloc (databases,
+                       (databases_num + 1) * sizeof (*databases));
+       if (NULL == tmp) {
+               log_err ("Out of memory.");
+               sfree (db);
+               return NULL;
+       }
+
+       databases = tmp;
+       databases[databases_num] = db;
+       ++databases_num;
 
        db->conn = NULL;
 
        C_COMPLAIN_INIT (&db->conn_complaint);
 
        db->proto_version = 0;
+       db->server_version = 0;
 
        db->max_params_num = 0;
 
+       db->q_prep_areas   = NULL;
        db->queries        = NULL;
-       db->hidden_queries = NULL;
        db->queries_num    = 0;
 
+       db->writers        = NULL;
+       db->writers_num    = 0;
+
+       pthread_mutex_init (&db->db_lock, /* attrs = */ NULL);
+
+       db->interval   = 0;
+
+       db->commit_interval = 0;
+       db->next_commit     = 0;
+
        db->database   = sstrdup (name);
        db->host       = NULL;
        db->port       = NULL;
        db->user       = NULL;
        db->password   = NULL;
 
+       db->instance   = sstrdup (name);
+
        db->sslmode    = NULL;
 
        db->krbsrvname = NULL;
 
        db->service    = NULL;
+
+       db->ref_cnt    = 0;
        return db;
 } /* c_psql_database_new */
 
-static void c_psql_database_init (c_psql_database_t *db, int server_version)
+static void c_psql_database_delete (void *data)
 {
-       int i;
+       size_t i;
 
-       /* Get the right version of each query definition. */
-       for (i = 0; i < db->queries_num; ++i) {
-               c_psql_query_t *tmp;
+       c_psql_database_t *db = data;
 
-               tmp = c_psql_query_get (db->queries[i]->name, server_version);
+       --db->ref_cnt;
+       /* readers and writers may access this database */
+       if (db->ref_cnt > 0)
+               return;
 
-               if (tmp == db->queries[i])
-                       continue;
+       /* wait for the lock to be released by the last writer */
+       pthread_mutex_lock (&db->db_lock);
 
-               if (NULL == tmp) {
-                       log_err ("Query \"%s\" not found for server version %i - "
-                                       "please check your configuration.",
-                                       db->queries[i]->name, server_version);
-                       /* By hiding the query (rather than removing it from the list) we
-                        * don't lose it in case a reconnect to an available version
-                        * happens at a later time. */
-                       db->hidden_queries[i] = 1;
-                       continue;
-               }
+       if (db->next_commit > 0)
+               c_psql_commit (db);
 
-               db->hidden_queries[i] = 0;
-               db->queries[i] = tmp;
-       }
-} /* c_psql_database_init */
-
-static void c_psql_database_delete (c_psql_database_t *db)
-{
        PQfinish (db->conn);
        db->conn = NULL;
 
+       if (db->q_prep_areas)
+               for (i = 0; i < db->queries_num; ++i)
+                       udb_query_delete_preparation_area (db->q_prep_areas[i]);
+       free (db->q_prep_areas);
+
        sfree (db->queries);
-       sfree (db->hidden_queries);
        db->queries_num = 0;
 
+       sfree (db->writers);
+       db->writers_num = 0;
+
+       pthread_mutex_unlock (&db->db_lock);
+
+       pthread_mutex_destroy (&db->db_lock);
+
        sfree (db->database);
        sfree (db->host);
        sfree (db->port);
        sfree (db->user);
        sfree (db->password);
 
+       sfree (db->instance);
+
        sfree (db->sslmode);
 
        sfree (db->krbsrvname);
 
        sfree (db->service);
+
+       /* don't care about freeing or reordering the 'databases' array
+        * this is done in 'shutdown'; also, don't free the database instance
+        * object just to make sure that in case anybody accesses it before
+        * shutdown won't segfault */
        return;
 } /* c_psql_database_delete */
 
-static void submit (const c_psql_database_t *db, const c_psql_result_t *res,
-               char **instances, value_t *values)
+static int c_psql_connect (c_psql_database_t *db)
 {
-       value_list_t vl = VALUE_LIST_INIT;
-
-       int instances_num = res->instances_num;
+       char  conninfo[4096];
+       char *buf     = conninfo;
+       int   buf_len = sizeof (conninfo);
+       int   status;
 
-       if (NULL != res->instance_prefix)
-               ++instances_num;
-
-       vl.values     = values;
-       vl.values_len = res->values_num;
-
-       if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
-                       || (0 == strcmp (db->host, "localhost")))
-               sstrncpy (vl.host, hostname_g, sizeof (vl.host));
-       else
-               sstrncpy (vl.host, db->host, sizeof (vl.host));
-
-       sstrncpy (vl.plugin, "postgresql", sizeof (vl.plugin));
-       sstrncpy (vl.plugin_instance, db->database, sizeof (vl.plugin_instance));
-
-       sstrncpy (vl.type, res->type, sizeof (vl.type));
-
-       if (0 < instances_num) {
-               vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
-               strjoin (vl.type_instance, sizeof (vl.type_instance),
-                               instances, instances_num, "-");
+       if ((! db) || (! db->database))
+               return -1;
 
-               if ('\0' != vl.type_instance[sizeof (vl.type_instance) - 1]) {
-                       vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
-                       log_warn ("Truncated type instance: %s.", vl.type_instance);
-               }
+       status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
+       if (0 < status) {
+               buf     += status;
+               buf_len -= status;
        }
 
-       plugin_dispatch_values (&vl);
-       return;
-} /* submit */
-
-static int c_psql_get_colnum (PGresult *pgres,
-               char **strings, int *numbers, int idx)
-{
-       int colnum;
+       C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
+       C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
+       C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
+       C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
+       C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
+       C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
+       C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
 
-       if (0 <= numbers[idx])
-               return numbers[idx];
-
-       colnum = PQfnumber (pgres, strings[idx]);
-       if (0 > colnum)
-               log_err ("No such column: %s.", strings[idx]);
-
-       numbers[idx] = colnum;
-       return colnum;
-} /* c_psql_get_colnum */
+       db->conn = PQconnectdb (conninfo);
+       db->proto_version = PQprotocolVersion (db->conn);
+       return 0;
+} /* c_psql_connect */
 
-static void c_psql_dispatch_row (c_psql_database_t *db, c_psql_query_t *query,
-               PGresult *pgres, int row)
+static int c_psql_check_connection (c_psql_database_t *db)
 {
-       int i;
-
-       for (i = 0; i < query->results_num; ++i) {
-               c_psql_result_t *res = query->results + i;
-
-               char   *instances[res->instances_num + 1];
-               value_t values[res->values_num];
-
-               int offset = 0, status = 0, j;
-
-               /* get the instance name */
-               if (NULL != res->instance_prefix) {
-                       instances[0] = res->instance_prefix;
-                       offset = 1;
-               }
-
-               for (j = 0; (0 == status) && (j < res->instances_num); ++j) {
-                       int col = c_psql_get_colnum (pgres,
-                                       res->instances_str, res->instances, j);
-
-                       if (0 > col) {
-                               status = -1;
-                               break;
-                       }
-
-                       instances[j + offset] = PQgetvalue (pgres, row, col);
-                       if (NULL == instances[j + offset])
-                               instances[j + offset] = "";
-               }
-
-               /* get the values */
-               for (j = 0; (0 == status) && (j < res->values_num); ++j) {
-                       int col = c_psql_get_colnum (pgres,
-                                       res->values_str, res->values, j);
-
-                       char *value_str;
-                       char *endptr = NULL;
-
-                       if (0 > col) {
-                               status = -1;
-                               break;
-                       }
-
-                       value_str = PQgetvalue (pgres, row, col);
-                       if ((NULL == value_str) || ('\0' == *value_str))
-                               value_str = "0";
-
-                       if (res->ds_types[j] == DS_TYPE_COUNTER)
-                               values[j].counter = (counter_t)strtoll (value_str, &endptr, 0);
-                       else if (res->ds_types[j] == DS_TYPE_GAUGE)
-                               values[j].gauge = (gauge_t)strtod (value_str, &endptr);
-                       else {
-                               log_err ("Invalid type \"%s\" (%i).",
-                                               res->type, res->ds_types[j]);
-                       }
+       _Bool init = 0;
 
-                       if (value_str == endptr) {
-                               log_err ("Failed to parse string as number: %s.", value_str);
-                               status = -1;
-                               break;
-                       }
-                       else if ((NULL != endptr) && ('\0' != *endptr))
-                               log_warn ("Ignoring trailing garbage after number: %s.",
-                                               endptr);
-               }
+       if (! db->conn) {
+               init = 1;
 
-               if (0 != status)
-                       continue;
+               /* trigger c_release() */
+               if (0 == db->conn_complaint.interval)
+                       db->conn_complaint.interval = 1;
 
-               submit (db, res, instances, values);
+               c_psql_connect (db);
        }
-} /* c_psql_dispatch_row */
-
-static int c_psql_check_connection (c_psql_database_t *db)
-{
-       /* "ping" */
-       PQclear (PQexec (db->conn, "SELECT 42;"));
 
        if (CONNECTION_OK != PQstatus (db->conn)) {
                PQreset (db->conn);
@@ -525,38 +390,60 @@ static int c_psql_check_connection (c_psql_database_t *db)
 
                if (CONNECTION_OK != PQstatus (db->conn)) {
                        c_complain (LOG_ERR, &db->conn_complaint,
-                                       "Failed to connect to database %s: %s",
-                                       db->database, PQerrorMessage (db->conn));
+                                       "Failed to connect to database %s (%s): %s",
+                                       db->database, db->instance,
+                                       PQerrorMessage (db->conn));
                        return -1;
                }
 
                db->proto_version = PQprotocolVersion (db->conn);
+       }
+
+       db->server_version = PQserverVersion (db->conn);
+
+       if (c_would_release (&db->conn_complaint)) {
+               char *server_host;
+               int   server_version;
+
+               server_host    = PQhost (db->conn);
+               server_version = PQserverVersion (db->conn);
+
+               c_do_release (LOG_INFO, &db->conn_complaint,
+                               "Successfully %sconnected to database %s (user %s) "
+                               "at server %s%s%s (server version: %d.%d.%d, "
+                               "protocol version: %d, pid: %d)", init ? "" : "re",
+                               PQdb (db->conn), PQuser (db->conn),
+                               C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
+                               C_PSQL_SERVER_VERSION3 (server_version),
+                               db->proto_version, PQbackendPID (db->conn));
+
                if (3 > db->proto_version)
                        log_warn ("Protocol version %d does not support parameters.",
                                        db->proto_version);
        }
-
-       /* We might have connected to a different PostgreSQL version, so we
-        * need to reinitialize stuff. */
-       if (c_would_release (&db->conn_complaint))
-               c_psql_database_init (db, PQserverVersion (db->conn));
-
-       c_release (LOG_INFO, &db->conn_complaint,
-                       "Successfully reconnected to database %s", PQdb (db->conn));
        return 0;
 } /* c_psql_check_connection */
 
+static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
+               udb_query_t *q)
+{
+       return PQexec (db->conn, udb_query_get_statement (q));
+} /* c_psql_exec_query_noparams */
+
 static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
-               c_psql_query_t *query)
+               udb_query_t *q, c_psql_user_data_t *data)
 {
        char *params[db->max_params_num];
        char  interval[64];
        int   i;
 
-       assert (db->max_params_num >= query->params_num);
+       if ((data == NULL) || (data->params_num == 0))
+               return (c_psql_exec_query_noparams (db, q));
+
+       assert (db->max_params_num >= data->params_num);
 
-       for (i = 0; i < query->params_num; ++i) {
-               switch (query->params[i]) {
+       for (i = 0; i < data->params_num; ++i) {
+               switch (data->params[i]) {
                        case C_PSQL_PARAM_HOST:
                                params[i] = C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
                                        ? "localhost" : db->host;
@@ -568,503 +455,749 @@ static PGresult *c_psql_exec_query_params (c_psql_database_t *db,
                                params[i] = db->user;
                                break;
                        case C_PSQL_PARAM_INTERVAL:
-                               ssnprintf (interval, sizeof (interval), "%i", interval_g);
+                               ssnprintf (interval, sizeof (interval), "%.3f",
+                                               (db->interval > 0)
+                                               ? CDTIME_T_TO_DOUBLE (db->interval)
+                                               : plugin_get_interval ());
                                params[i] = interval;
                                break;
+                       case C_PSQL_PARAM_INSTANCE:
+                               params[i] = db->instance;
+                               break;
                        default:
                                assert (0);
                }
        }
 
-       return PQexecParams (db->conn, query->stmt, query->params_num, NULL,
-                       (const char *const *)((0 == query->params_num) ? NULL : params),
+       return PQexecParams (db->conn, udb_query_get_statement (q),
+                       data->params_num, NULL,
+                       (const char *const *) params,
                        NULL, NULL, /* return text data */ 0);
 } /* c_psql_exec_query_params */
 
-static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
-               c_psql_query_t *query)
+/* db->db_lock must be locked when calling this function */
+static int c_psql_exec_query (c_psql_database_t *db, udb_query_t *q,
+               udb_query_preparation_area_t *prep_area)
 {
-       return PQexec (db->conn, query->stmt);
-} /* c_psql_exec_query_noparams */
+       PGresult *res;
 
-static int c_psql_exec_query (c_psql_database_t *db, int idx)
-{
-       c_psql_query_t *query;
-       PGresult       *res;
+       c_psql_user_data_t *data;
 
-       int rows, cols;
-       int i;
+       const char *host;
 
-       if (idx >= db->queries_num)
-               return -1;
+       char **column_names;
+       char **column_values;
+       int    column_num;
 
-       if (0 != db->hidden_queries[idx])
-               return 0;
+       int rows_num;
+       int status;
+       int row, col;
 
-       query = db->queries[idx];
+       /* The user data may hold parameter information, but may be NULL. */
+       data = udb_query_get_user_data (q);
 
+       /* Versions up to `3' don't know how to handle parameters. */
        if (3 <= db->proto_version)
-               res = c_psql_exec_query_params (db, query);
-       else if (0 == query->params_num)
-               res = c_psql_exec_query_noparams (db, query);
+               res = c_psql_exec_query_params (db, q, data);
+       else if ((NULL == data) || (0 == data->params_num))
+               res = c_psql_exec_query_noparams (db, q);
        else {
-               log_err ("Connection to database \"%s\" does not support parameters "
-                               "(protocol version %d) - cannot execute query \"%s\".",
-                               db->database, db->proto_version, query->name);
+               log_err ("Connection to database \"%s\" (%s) does not support "
+                               "parameters (protocol version %d) - "
+                               "cannot execute query \"%s\".",
+                               db->database, db->instance, db->proto_version,
+                               udb_query_get_name (q));
                return -1;
        }
 
+       /* give c_psql_write() a chance to acquire the lock if called recursively
+        * through dispatch_values(); this will happen if, both, queries and
+        * writers are configured for a single connection */
+       pthread_mutex_unlock (&db->db_lock);
+
+       column_names = NULL;
+       column_values = NULL;
+
        if (PGRES_TUPLES_OK != PQresultStatus (res)) {
+               pthread_mutex_lock (&db->db_lock);
+
+               if ((CONNECTION_OK != PQstatus (db->conn))
+                               && (0 == c_psql_check_connection (db))) {
+                       PQclear (res);
+                       return c_psql_exec_query (db, q, prep_area);
+               }
+
                log_err ("Failed to execute SQL query: %s",
                                PQerrorMessage (db->conn));
-               log_info ("SQL query was: %s", query->stmt);
+               log_info ("SQL query was: %s",
+                               udb_query_get_statement (q));
                PQclear (res);
                return -1;
        }
 
-       rows = PQntuples (res);
-       if (1 > rows) {
-               PQclear (res);
-               return 0;
+#define BAIL_OUT(status) \
+       sfree (column_names); \
+       sfree (column_values); \
+       PQclear (res); \
+       pthread_mutex_lock (&db->db_lock); \
+       return status
+
+       rows_num = PQntuples (res);
+       if (1 > rows_num) {
+               BAIL_OUT (0);
        }
 
-       cols = PQnfields (res);
+       column_num = PQnfields (res);
+       column_names = (char **) calloc (column_num, sizeof (char *));
+       if (NULL == column_names) {
+               log_err ("calloc failed.");
+               BAIL_OUT (-1);
+       }
 
-       for (i = 0; i < rows; ++i)
-               c_psql_dispatch_row (db, query, res, i);
-       PQclear (res);
-       return 0;
+       column_values = (char **) calloc (column_num, sizeof (char *));
+       if (NULL == column_values) {
+               log_err ("calloc failed.");
+               BAIL_OUT (-1);
+       }
+       
+       for (col = 0; col < column_num; ++col) {
+               /* Pointers returned by `PQfname' are freed by `PQclear' via
+                * `BAIL_OUT'. */
+               column_names[col] = PQfname (res, col);
+               if (NULL == column_names[col]) {
+                       log_err ("Failed to resolve name of column %i.", col);
+                       BAIL_OUT (-1);
+               }
+       }
+
+       if (C_PSQL_IS_UNIX_DOMAIN_SOCKET (db->host)
+                       || (0 == strcmp (db->host, "localhost")))
+               host = hostname_g;
+       else
+               host = db->host;
+
+       status = udb_query_prepare_result (q, prep_area, host, "postgresql",
+                       db->instance, column_names, (size_t) column_num, db->interval);
+       if (0 != status) {
+               log_err ("udb_query_prepare_result failed with status %i.",
+                               status);
+               BAIL_OUT (-1);
+       }
+
+       for (row = 0; row < rows_num; ++row) {
+               for (col = 0; col < column_num; ++col) {
+                       /* Pointers returned by `PQgetvalue' are freed by `PQclear' via
+                        * `BAIL_OUT'. */
+                       column_values[col] = PQgetvalue (res, row, col);
+                       if (NULL == column_values[col]) {
+                               log_err ("Failed to get value at (row = %i, col = %i).",
+                                               row, col);
+                               break;
+                       }
+               }
+
+               /* check for an error */
+               if (col < column_num)
+                       continue;
+
+               status = udb_query_handle_result (q, prep_area, column_values);
+               if (status != 0) {
+                       log_err ("udb_query_handle_result failed with status %i.",
+                                       status);
+               }
+       } /* for (row = 0; row < rows_num; ++row) */
+
+       udb_query_finish_result (q, prep_area);
+
+       BAIL_OUT (0);
+#undef BAIL_OUT
 } /* c_psql_exec_query */
 
-static int c_psql_read (void)
+static int c_psql_read (user_data_t *ud)
 {
+       c_psql_database_t *db;
+
        int success = 0;
        int i;
 
-       for (i = 0; i < databases_num; ++i) {
-               c_psql_database_t *db = databases + i;
+       if ((ud == NULL) || (ud->data == NULL)) {
+               log_err ("c_psql_read: Invalid user data.");
+               return -1;
+       }
 
-               int j;
+       db = ud->data;
 
-               assert (NULL != db->database);
+       assert (NULL != db->database);
+       assert (NULL != db->instance);
+       assert (NULL != db->queries);
 
-               if (0 != c_psql_check_connection (db))
-                       continue;
+       pthread_mutex_lock (&db->db_lock);
+
+       if (0 != c_psql_check_connection (db)) {
+               pthread_mutex_unlock (&db->db_lock);
+               return -1;
+       }
+
+       for (i = 0; i < db->queries_num; ++i)
+       {
+               udb_query_preparation_area_t *prep_area;
+               udb_query_t *q;
 
-               for (j = 0; j < db->queries_num; ++j)
-                       c_psql_exec_query (db, j);
+               prep_area = db->q_prep_areas[i];
+               q = db->queries[i];
 
-               ++success;
+               if ((0 != db->server_version)
+                               && (udb_query_check_version (q, db->server_version) <= 0))
+                       continue;
+
+               if (0 == c_psql_exec_query (db, q, prep_area))
+                       success = 1;
        }
 
+       pthread_mutex_unlock (&db->db_lock);
+
        if (! success)
                return -1;
        return 0;
 } /* c_psql_read */
 
-static int c_psql_shutdown (void)
+static char *values_name_to_sqlarray (const data_set_t *ds,
+               char *string, size_t string_len)
 {
+       char  *str_ptr;
+       size_t str_len;
+
        int i;
 
-       if ((NULL == databases) || (0 == databases_num))
-               return 0;
+       str_ptr = string;
+       str_len = string_len;
 
-       plugin_unregister_read ("postgresql");
-       plugin_unregister_shutdown ("postgresql");
+       for (i = 0; i < ds->ds_num; ++i) {
+               int status = ssnprintf (str_ptr, str_len, ",'%s'", ds->ds[i].name);
 
-       for (i = 0; i < databases_num; ++i) {
-               c_psql_database_t *db = databases + i;
-               c_psql_database_delete (db);
+               if (status < 1)
+                       return NULL;
+               else if ((size_t)status >= str_len) {
+                       str_len = 0;
+                       break;
+               }
+               else {
+                       str_ptr += status;
+                       str_len -= (size_t)status;
+               }
        }
 
-       sfree (databases);
-       databases_num = 0;
-
-       for (i = 0; i < queries_num; ++i) {
-               c_psql_query_t *query = queries + i;
-               c_psql_query_delete (query);
+       if (str_len <= 2) {
+               log_err ("c_psql_write: Failed to stringify value names");
+               return NULL;
        }
 
-       sfree (queries);
-       queries_num = 0;
-       return 0;
-} /* c_psql_shutdown */
+       /* overwrite the first comma */
+       string[0] = '{';
+       str_ptr[0] = '}';
+       str_ptr[1] = '\0';
 
-static int c_psql_init (void)
+       return string;
+} /* values_name_to_sqlarray */
+
+static char *values_type_to_sqlarray (const data_set_t *ds,
+               char *string, size_t string_len, _Bool store_rates)
 {
+       char  *str_ptr;
+       size_t str_len;
+
        int i;
 
-       if ((NULL == databases) || (0 == databases_num))
-               return 0;
+       str_ptr = string;
+       str_len = string_len;
 
-       for (i = 0; i < queries_num; ++i)
-               if (0 != c_psql_query_init (queries + i)) {
-                       c_psql_shutdown ();
-                       return -1;
+       for (i = 0; i < ds->ds_num; ++i) {
+               int status;
+
+               if (store_rates)
+                       status = ssnprintf(str_ptr, str_len, ",'gauge'");
+               else
+                       status = ssnprintf(str_ptr, str_len, ",'%s'",
+                                       DS_TYPE_TO_STRING (ds->ds[i].type));
+
+               if (status < 1) {
+                       str_len = 0;
+                       break;
+               }
+               else if ((size_t)status >= str_len) {
+                       str_len = 0;
+                       break;
+               }
+               else {
+                       str_ptr += status;
+                       str_len -= (size_t)status;
                }
+       }
 
-       for (i = 0; i < databases_num; ++i) {
-               c_psql_database_t *db = databases + i;
+       if (str_len <= 2) {
+               log_err ("c_psql_write: Failed to stringify value types");
+               return NULL;
+       }
 
-               char  conninfo[4096];
-               char *buf     = conninfo;
-               int   buf_len = sizeof (conninfo);
-               int   status;
+       /* overwrite the first comma */
+       string[0] = '{';
+       str_ptr[0] = '}';
+       str_ptr[1] = '\0';
 
-               char *server_host;
-               int   server_version;
+       return string;
+} /* values_type_to_sqlarray */
 
-               /* this will happen during reinitialization */
-               if (NULL != db->conn) {
-                       c_psql_check_connection (db);
-                       continue;
-               }
+static char *values_to_sqlarray (const data_set_t *ds, const value_list_t *vl,
+               char *string, size_t string_len, _Bool store_rates)
+{
+       char  *str_ptr;
+       size_t str_len;
 
-               status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database);
-               if (0 < status) {
-                       buf     += status;
-                       buf_len -= status;
-               }
+       gauge_t *rates = NULL;
 
-               C_PSQL_PAR_APPEND (buf, buf_len, "host",       db->host);
-               C_PSQL_PAR_APPEND (buf, buf_len, "port",       db->port);
-               C_PSQL_PAR_APPEND (buf, buf_len, "user",       db->user);
-               C_PSQL_PAR_APPEND (buf, buf_len, "password",   db->password);
-               C_PSQL_PAR_APPEND (buf, buf_len, "sslmode",    db->sslmode);
-               C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname);
-               C_PSQL_PAR_APPEND (buf, buf_len, "service",    db->service);
+       int i;
 
-               db->conn = PQconnectdb (conninfo);
-               if (0 != c_psql_check_connection (db))
-                       continue;
+       str_ptr = string;
+       str_len = string_len;
 
-               db->proto_version = PQprotocolVersion (db->conn);
+       for (i = 0; i < vl->values_len; ++i) {
+               int status = 0;
 
-               server_host    = PQhost (db->conn);
-               server_version = PQserverVersion (db->conn);
-               log_info ("Sucessfully connected to database %s (user %s) "
-                               "at server %s%s%s (server version: %d.%d.%d, "
-                               "protocol version: %d, pid: %d)",
-                               PQdb (db->conn), PQuser (db->conn),
-                               C_PSQL_SOCKET3 (server_host, PQport (db->conn)),
-                               C_PSQL_SERVER_VERSION3 (server_version),
-                               db->proto_version, PQbackendPID (db->conn));
+               if ((ds->ds[i].type != DS_TYPE_GAUGE)
+                               && (ds->ds[i].type != DS_TYPE_COUNTER)
+                               && (ds->ds[i].type != DS_TYPE_DERIVE)
+                               && (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
+                       log_err ("c_psql_write: Unknown data source type: %i",
+                                       ds->ds[i].type);
+                       sfree (rates);
+                       return NULL;
+               }
 
-               if (3 > db->proto_version)
-                       log_warn ("Protocol version %d does not support parameters.",
-                                       db->proto_version);
+               if (ds->ds[i].type == DS_TYPE_GAUGE)
+                       status = ssnprintf (str_ptr, str_len,
+                                       ","GAUGE_FORMAT, vl->values[i].gauge);
+               else if (store_rates) {
+                       if (rates == NULL)
+                               rates = uc_get_rate (ds, vl);
+
+                       if (rates == NULL) {
+                               log_err ("c_psql_write: Failed to determine rate");
+                               return NULL;
+                       }
 
-               c_psql_database_init (db, server_version);
+                       status = ssnprintf (str_ptr, str_len,
+                                       ",%lf", rates[i]);
+               }
+               else if (ds->ds[i].type == DS_TYPE_COUNTER)
+                       status = ssnprintf (str_ptr, str_len,
+                                       ",%llu", vl->values[i].counter);
+               else if (ds->ds[i].type == DS_TYPE_DERIVE)
+                       status = ssnprintf (str_ptr, str_len,
+                                       ",%"PRIi64, vl->values[i].derive);
+               else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
+                       status = ssnprintf (str_ptr, str_len,
+                                       ",%"PRIu64, vl->values[i].absolute);
+
+               if (status < 1) {
+                       str_len = 0;
+                       break;
+               }
+               else if ((size_t)status >= str_len) {
+                       str_len = 0;
+                       break;
+               }
+               else {
+                       str_ptr += status;
+                       str_len -= (size_t)status;
+               }
        }
 
-       plugin_register_read ("postgresql", c_psql_read);
-       plugin_register_shutdown ("postgresql", c_psql_shutdown);
-       return 0;
-} /* c_psql_init */
+       sfree (rates);
 
-static int config_set_s (char *name, char **var, const oconfig_item_t *ci)
-{
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
-               log_err ("%s expects a single string argument.", name);
-               return 1;
+       if (str_len <= 2) {
+               log_err ("c_psql_write: Failed to stringify value list");
+               return NULL;
        }
 
-       sfree (*var);
-       *var = sstrdup (ci->values[0].value.string);
-       return 0;
-} /* config_set_s */
+       /* overwrite the first comma */
+       string[0] = '{';
+       str_ptr[0] = '}';
+       str_ptr[1] = '\0';
 
-static int config_set_i (char *name, int *var, const oconfig_item_t *ci)
+       return string;
+} /* values_to_sqlarray */
+
+static int c_psql_write (const data_set_t *ds, const value_list_t *vl,
+               user_data_t *ud)
 {
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_NUMBER != ci->values[0].type)) {
-               log_err ("%s expects a single number argument.", name);
-               return 1;
-       }
+       c_psql_database_t *db;
 
-       *var = (int)ci->values[0].value.number;
-       return 0;
-} /* config_set_i */
+       char time_str[32];
+       char values_name_str[1024];
+       char values_type_str[1024];
+       char values_str[1024];
 
-static int config_append_array_s (char *name, char ***var, int *len,
-               const oconfig_item_t *ci)
-{
+       const char *params[9];
+
+       int success = 0;
        int i;
 
-       if ((0 != ci->children_num) || (1 > ci->values_num)) {
-               log_err ("%s expects at least one argument.", name);
-               return 1;
+       if ((ud == NULL) || (ud->data == NULL)) {
+               log_err ("c_psql_write: Invalid user data.");
+               return -1;
        }
 
-       for (i = 0; i < ci->values_num; ++i) {
-               if (OCONFIG_TYPE_STRING != ci->values[i].type) {
-                       log_err ("%s expects string arguments.", name);
-                       return 1;
-               }
-       }
+       db = ud->data;
+       assert (db->database != NULL);
+       assert (db->writers != NULL);
 
-       *len += ci->values_num;
-       if (NULL == (*var = (char **)realloc (*var, *len * sizeof (**var)))) {
-               log_err ("Out of memory.");
-               exit (5);
+       if (cdtime_to_iso8601 (time_str, sizeof (time_str), vl->time) == 0) {
+               log_err ("c_psql_write: Failed to convert time to ISO 8601 format");
+               return -1;
        }
 
-       for (i = *len - ci->values_num; i < *len; ++i)
-               (*var)[i] = sstrdup (ci->values[i].value.string);
-       return 0;
-} /* config_append_array_s */
+       if (values_name_to_sqlarray (ds,
+                               values_name_str, sizeof (values_name_str)) == NULL)
+               return -1;
 
-static int config_set_param (c_psql_query_t *query, const oconfig_item_t *ci)
-{
-       c_psql_param_t param;
-       char          *param_str;
+#define VALUE_OR_NULL(v) ((((v) == NULL) || (*(v) == '\0')) ? NULL : (v))
 
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
-               log_err ("Param expects a single string argument.");
-               return 1;
-       }
+       params[0] = time_str;
+       params[1] = vl->host;
+       params[2] = vl->plugin;
+       params[3] = VALUE_OR_NULL(vl->plugin_instance);
+       params[4] = vl->type;
+       params[5] = VALUE_OR_NULL(vl->type_instance);
+       params[6] = values_name_str;
 
-       param_str = ci->values[0].value.string;
-       if (0 == strcasecmp (param_str, "hostname"))
-               param = C_PSQL_PARAM_HOST;
-       else if (0 == strcasecmp (param_str, "database"))
-               param = C_PSQL_PARAM_DB;
-       else if (0 == strcasecmp (param_str, "username"))
-               param = C_PSQL_PARAM_USER;
-       else if (0 == strcasecmp (param_str, "interval"))
-               param = C_PSQL_PARAM_INTERVAL;
-       else {
-               log_err ("Invalid parameter \"%s\".", param_str);
-               return 1;
-       }
+#undef VALUE_OR_NULL
 
-       ++query->params_num;
-       if (NULL == (query->params = (c_psql_param_t *)realloc (query->params,
-                               query->params_num * sizeof (*query->params)))) {
-               log_err ("Out of memory.");
-               exit (5);
+       pthread_mutex_lock (&db->db_lock);
+
+       if (0 != c_psql_check_connection (db)) {
+               pthread_mutex_unlock (&db->db_lock);
+               return -1;
        }
 
-       query->params[query->params_num - 1] = param;
-       return 0;
-} /* config_set_param */
+       if ((db->commit_interval > 0)
+                       && (db->next_commit == 0))
+               c_psql_begin (db);
 
-static int config_set_result (c_psql_query_t *query, const oconfig_item_t *ci)
-{
-       c_psql_result_t *res;
+       for (i = 0; i < db->writers_num; ++i) {
+               c_psql_writer_t *writer;
+               PGresult *res;
 
-       int status = 0, i;
+               writer = db->writers[i];
 
-       if (0 != ci->values_num) {
-               log_err ("<Result> does not expect any arguments.");
-               return 1;
-       }
+               if (values_type_to_sqlarray (ds,
+                                       values_type_str, sizeof (values_type_str),
+                                       writer->store_rates) == NULL) {
+                       pthread_mutex_unlock (&db->db_lock);
+                       return -1;
+               }
 
-       res = c_psql_result_new (query);
+               if (values_to_sqlarray (ds, vl,
+                                       values_str, sizeof (values_str),
+                                       writer->store_rates) == NULL) {
+                       pthread_mutex_unlock (&db->db_lock);
+                       return -1;
+               }
 
-       for (i = 0; i < ci->children_num; ++i) {
-               oconfig_item_t *c = ci->children + i;
+               params[7] = values_type_str;
+               params[8] = values_str;
+
+               res = PQexecParams (db->conn, writer->statement,
+                               STATIC_ARRAY_SIZE (params), NULL,
+                               (const char *const *)params,
+                               NULL, NULL, /* return text data */ 0);
+
+               if ((PGRES_COMMAND_OK != PQresultStatus (res))
+                               && (PGRES_TUPLES_OK != PQresultStatus (res))) {
+                       PQclear (res);
+
+                       if ((CONNECTION_OK != PQstatus (db->conn))
+                                       && (0 == c_psql_check_connection (db))) {
+                               /* try again */
+                               res = PQexecParams (db->conn, writer->statement,
+                                               STATIC_ARRAY_SIZE (params), NULL,
+                                               (const char *const *)params,
+                                               NULL, NULL, /* return text data */ 0);
+
+                               if ((PGRES_COMMAND_OK == PQresultStatus (res))
+                                               || (PGRES_TUPLES_OK == PQresultStatus (res))) {
+                                       PQclear (res);
+                                       success = 1;
+                                       continue;
+                               }
+                       }
 
-               if (0 == strcasecmp (c->key, "Type"))
-                       config_set_s ("Type", &res->type, c);
-               else if (0 == strcasecmp (c->key, "InstancePrefix"))
-                       config_set_s ("InstancePrefix", &res->instance_prefix, c);
-               else if (0 == strcasecmp (c->key, "InstancesFrom"))
-                       config_append_array_s ("InstancesFrom",
-                                       &res->instances_str, &res->instances_num, c);
-               else if (0 == strcasecmp (c->key, "ValuesFrom"))
-                       config_append_array_s ("ValuesFrom",
-                                       &res->values_str, &res->values_num, c);
-               else
-                       log_warn ("Ignoring unknown config key \"%s\".", c->key);
-       }
+                       log_err ("Failed to execute SQL query: %s",
+                                       PQerrorMessage (db->conn));
+                       log_info ("SQL query was: '%s', "
+                                       "params: %s, %s, %s, %s, %s, %s, %s, %s",
+                                       writer->statement,
+                                       params[0], params[1], params[2], params[3],
+                                       params[4], params[5], params[6], params[7]);
 
-       if (NULL == res->type) {
-               log_warn ("Query \"%s\": Missing Type option in <Result> block.",
-                               query->name);
-               status = 1;
-       }
+                       /* this will abort any current transaction -> restart */
+                       if (db->next_commit > 0)
+                               c_psql_commit (db);
 
-       if (NULL == res->values_str) {
-               log_warn ("Query \"%s\": Missing ValuesFrom option in <Result> block.",
-                               query->name);
-               status = 1;
-       }
+                       pthread_mutex_unlock (&db->db_lock);
+                       return -1;
+               }
 
-       if (0 != status) {
-               c_psql_result_delete (res);
-               --query->results_num;
-               return status;
+               PQclear (res);
+               success = 1;
        }
 
-       /* preallocate memory to cache the column numbers and data types */
-       res->values = (int *)smalloc (res->values_num * sizeof (*res->values));
-       for (i = 0; i < res->values_num; ++i)
-               res->values[i] = -1;
+       if ((db->next_commit > 0)
+                       && (cdtime () > db->next_commit))
+               c_psql_commit (db);
+
+       pthread_mutex_unlock (&db->db_lock);
+
+       if (! success)
+               return -1;
+       return 0;
+} /* c_psql_write */
+
+/* We cannot flush single identifiers as all we do is to commit the currently
+ * running transaction, thus making sure that all written data is actually
+ * visible to everybody. */
+static int c_psql_flush (cdtime_t timeout,
+               __attribute__((unused)) const char *ident,
+               user_data_t *ud)
+{
+       c_psql_database_t **dbs = databases;
+       size_t dbs_num = databases_num;
+       size_t i;
 
-       res->instances = (int *)smalloc (res->instances_num
-                       * sizeof (*res->instances));
-       for (i = 0; i < res->instances_num; ++i)
-               res->instances[i] = -1;
+       if ((ud != NULL) && (ud->data != NULL)) {
+               dbs = (void *)&ud->data;
+               dbs_num = 1;
+       }
+
+       for (i = 0; i < dbs_num; ++i) {
+               c_psql_database_t *db = dbs[i];
 
-       res->ds_types = (int *)smalloc (res->values_num
-                       * sizeof (*res->ds_types));
-       for (i = 0; i < res->values_num; ++i)
-               res->ds_types[i] = -1;
+               /* don't commit if the timeout is larger than the regular commit
+                * interval as in that case all requested data has already been
+                * committed */
+               if ((db->next_commit > 0) && (db->commit_interval > timeout))
+                       c_psql_commit (db);
+       }
        return 0;
-} /* config_set_result */
+} /* c_psql_flush */
 
-static int config_set_column (c_psql_query_t *query, int col_num,
-               const oconfig_item_t *ci)
+static int c_psql_shutdown (void)
 {
-       c_psql_result_t *res;
+       size_t i = 0;
 
-       int i;
+       _Bool had_flush = 0;
 
-       if ((0 != ci->children_num)
-                       || (1 > ci->values_num) || (2 < ci->values_num)) {
-               log_err ("Column expects either one or two arguments.");
-               return 1;
-       }
+       plugin_unregister_read_group ("postgresql");
+
+       for (i = 0; i < databases_num; ++i) {
+               c_psql_database_t *db = databases[i];
 
-       for (i = 0; i < ci->values_num; ++i) {
-               if (OCONFIG_TYPE_STRING != ci->values[i].type) {
-                       log_err ("Column expects either one or two string arguments.");
-                       return 1;
+               if (db->writers_num > 0) {
+                       char cb_name[DATA_MAX_NAME_LEN];
+                       ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s",
+                                       db->database);
+
+                       if (! had_flush) {
+                               plugin_unregister_flush ("postgresql");
+                               had_flush = 1;
+                       }
+
+                       plugin_unregister_flush (cb_name);
+                       plugin_unregister_write (cb_name);
                }
+
+               sfree (db);
        }
 
-       res = c_psql_result_new (query);
+       udb_query_free (queries, queries_num);
+       queries = NULL;
+       queries_num = 0;
 
-       res->type = sstrdup (ci->values[0].value.string);
+       sfree (writers);
+       writers = NULL;
+       writers_num = 0;
 
-       if (2 == ci->values_num)
-               res->instance_prefix = sstrdup (ci->values[1].value.string);
+       sfree (databases);
+       databases = NULL;
+       databases_num = 0;
 
-       res->values     = (int *)smalloc (sizeof (*res->values));
-       res->values[0]  = col_num;
-       res->ds_types   = (int *)smalloc (sizeof (*res->ds_types));
-       res->values_num = 1;
        return 0;
-} /* config_set_column */
+} /* c_psql_shutdown */
 
-static int set_query (c_psql_database_t *db, const char *name)
+static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci)
 {
-       c_psql_query_t *query;
+       c_psql_user_data_t *data;
+       const char *param_str;
 
-       query = c_psql_query_get (name, -1);
-       if (NULL == query) {
-               log_err ("Query \"%s\" not found - please check your configuration.",
-                               name);
-               return 1;
+       c_psql_param_t *tmp;
+
+       data = udb_query_get_user_data (q);
+       if (NULL == data) {
+               data = (c_psql_user_data_t *) smalloc (sizeof (*data));
+               if (NULL == data) {
+                       log_err ("Out of memory.");
+                       return -1;
+               }
+               memset (data, 0, sizeof (*data));
+               data->params = NULL;
        }
 
-       ++db->queries_num;
-       if (NULL == (db->queries = (c_psql_query_t **)realloc (db->queries,
-                               db->queries_num * sizeof (*db->queries)))) {
+       tmp = (c_psql_param_t *) realloc (data->params,
+                       (data->params_num + 1) * sizeof (c_psql_param_t));
+       if (NULL == tmp) {
                log_err ("Out of memory.");
-               exit (5);
+               return -1;
        }
+       data->params = tmp;
 
-       if (query->params_num > db->max_params_num)
-               db->max_params_num = query->params_num;
+       param_str = ci->values[0].value.string;
+       if (0 == strcasecmp (param_str, "hostname"))
+               data->params[data->params_num] = C_PSQL_PARAM_HOST;
+       else if (0 == strcasecmp (param_str, "database"))
+               data->params[data->params_num] = C_PSQL_PARAM_DB;
+       else if (0 == strcasecmp (param_str, "username"))
+               data->params[data->params_num] = C_PSQL_PARAM_USER;
+       else if (0 == strcasecmp (param_str, "interval"))
+               data->params[data->params_num] = C_PSQL_PARAM_INTERVAL;
+       else if (0 == strcasecmp (param_str, "instance"))
+               data->params[data->params_num] = C_PSQL_PARAM_INSTANCE;
+       else {
+               log_err ("Invalid parameter \"%s\".", param_str);
+               return 1;
+       }
 
-       db->queries[db->queries_num - 1] = query;
-       return 0;
-} /* set_query */
+       data->params_num++;
+       udb_query_set_user_data (q, data);
 
-static int config_set_query (c_psql_database_t *db, const oconfig_item_t *ci)
+       return (0);
+} /* config_query_param_add */
+
+static int config_query_callback (udb_query_t *q, oconfig_item_t *ci)
 {
-       if ((0 != ci->children_num) || (1 != ci->values_num)
-                       || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
-               log_err ("Query expects a single string argument.");
-               return 1;
-       }
-       return set_query (db, ci->values[0].value.string);
-} /* config_set_query */
+       if (0 == strcasecmp ("Param", ci->key))
+               return config_query_param_add (q, ci);
+
+       log_err ("Option not allowed within a Query block: `%s'", ci->key);
 
-static int c_psql_config_query (oconfig_item_t *ci)
+       return (-1);
+} /* config_query_callback */
+
+static int config_add_writer (oconfig_item_t *ci,
+               c_psql_writer_t *src_writers, size_t src_writers_num,
+               c_psql_writer_t ***dst_writers, size_t *dst_writers_num)
 {
-       c_psql_query_t *query;
+       char *name;
 
-       int status = 0, col_num = 0, i;
+       size_t i;
 
-       if ((1 != ci->values_num)
-                       || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
-               log_err ("<Query> expects a single string argument.");
+       if ((ci == NULL) || (dst_writers == NULL) || (dst_writers_num == NULL))
+               return -1;
+
+       if ((ci->values_num != 1)
+                       || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
+               log_err ("`Writer' expects a single string argument.");
                return 1;
        }
 
-       query = c_psql_query_new (ci->values[0].value.string);
+       name = ci->values[0].value.string;
 
-       for (i = 0; i < ci->children_num; ++i) {
-               oconfig_item_t *c = ci->children + i;
+       for (i = 0; i < src_writers_num; ++i) {
+               c_psql_writer_t **tmp;
 
-               if (0 == strcasecmp (c->key, "Statement"))
-                       config_set_s ("Statement", &query->stmt, c);
-               /* backwards compat for versions < 4.6 */
-               else if (0 == strcasecmp (c->key, "Query")) {
-                       log_warn ("<Query>: 'Query' is deprecated - use 'Statement' instead.");
-                       config_set_s ("Query", &query->stmt, c);
-               }
-               else if (0 == strcasecmp (c->key, "Param"))
-                       config_set_param (query, c);
-               else if (0 == strcasecmp (c->key, "Result"))
-                       config_set_result (query, c);
-               /* backwards compat for versions < 4.6 */
-               else if (0 == strcasecmp (c->key, "Column")) {
-                       log_warn ("<Query>: 'Column' is deprecated - "
-                                       "use a <Result> block instead.");
-                       config_set_column (query, col_num, c);
-                       ++col_num;
+               if (strcasecmp (name, src_writers[i].name) != 0)
+                       continue;
+
+               tmp = (c_psql_writer_t **)realloc (*dst_writers,
+                               sizeof (**dst_writers) * (*dst_writers_num + 1));
+               if (tmp == NULL) {
+                       log_err ("Out of memory.");
+                       return -1;
                }
-               else if (0 == strcasecmp (c->key, "MinPGVersion"))
-                       config_set_i ("MinPGVersion", &query->min_pg_version, c);
-               else if (0 == strcasecmp (c->key, "MaxPGVersion"))
-                       config_set_i ("MaxPGVersion", &query->max_pg_version, c);
-               else
-                       log_warn ("Ignoring unknown config key \"%s\".", c->key);
+
+               tmp[*dst_writers_num] = src_writers + i;
+
+               *dst_writers = tmp;
+               ++(*dst_writers_num);
+               break;
        }
 
-       for (i = 0; i < queries_num - 1; ++i) {
-               c_psql_query_t *q = queries + i;
+       if (i >= src_writers_num) {
+               log_err ("No such writer: `%s'", name);
+               return -1;
+       }
 
-               if ((0 == strcasecmp (q->name, query->name))
-                               && (q->min_pg_version <= query->max_pg_version)
-                               && (query->min_pg_version <= q->max_pg_version)) {
-                       log_err ("Ignoring redefinition (with overlapping version ranges) "
-                                       "of query \"%s\".", query->name);
-                       status = 1;
-                       break;
-               }
+       return 0;
+} /* config_add_writer */
+
+static int c_psql_config_writer (oconfig_item_t *ci)
+{
+       c_psql_writer_t *writer;
+       c_psql_writer_t *tmp;
+
+       int status = 0;
+       int i;
+
+       if ((ci->values_num != 1)
+                       || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
+               log_err ("<Writer> expects a single string argument.");
+               return 1;
        }
 
-       if (query->min_pg_version > query->max_pg_version) {
-               log_err ("Query \"%s\": MinPGVersion > MaxPGVersion.",
-                               query->name);
-               status = 1;
+       tmp = (c_psql_writer_t *)realloc (writers,
+                       sizeof (*writers) * (writers_num + 1));
+       if (tmp == NULL) {
+               log_err ("Out of memory.");
+               return -1;
        }
 
-       if (NULL == query->stmt) {
-               log_err ("Query \"%s\" does not include an SQL query statement - "
-                               "please check your configuration.", query->name);
-               status = 1;
+       writers = tmp;
+       writer  = writers + writers_num;
+       ++writers_num;
+
+       writer->name = sstrdup (ci->values[0].value.string);
+       writer->statement = NULL;
+       writer->store_rates = 1;
+
+       for (i = 0; i < ci->children_num; ++i) {
+               oconfig_item_t *c = ci->children + i;
+
+               if (strcasecmp ("Statement", c->key) == 0)
+                       status = cf_util_get_string (c, &writer->statement);
+               else if (strcasecmp ("StoreRates", c->key) == 0)
+                       status = cf_util_get_boolean (c, &writer->store_rates);
+               else
+                       log_warn ("Ignoring unknown config key \"%s\".", c->key);
        }
 
-       if (0 != status) {
-               c_psql_query_delete (query);
-               --queries_num;
+       if (status != 0) {
+               sfree (writer->statement);
+               sfree (writer->name);
+               sfree (writer);
                return status;
        }
+
        return 0;
-} /* c_psql_config_query */
+} /* c_psql_config_writer */
 
 static int c_psql_config_database (oconfig_item_t *ci)
 {
        c_psql_database_t *db;
 
+       char cb_name[DATA_MAX_NAME_LEN];
+       struct timespec cb_interval = { 0, 0 };
+       user_data_t ud;
+
+       static _Bool have_flush = 0;
+
        int i;
 
        if ((1 != ci->values_num)
@@ -1073,41 +1206,112 @@ static int c_psql_config_database (oconfig_item_t *ci)
                return 1;
        }
 
+       memset (&ud, 0, sizeof (ud));
+
        db = c_psql_database_new (ci->values[0].value.string);
+       if (db == NULL)
+               return -1;
 
        for (i = 0; i < ci->children_num; ++i) {
                oconfig_item_t *c = ci->children + i;
 
                if (0 == strcasecmp (c->key, "Host"))
-                       config_set_s ("Host", &db->host, c);
+                       cf_util_get_string (c, &db->host);
                else if (0 == strcasecmp (c->key, "Port"))
-                       config_set_s ("Port", &db->port, c);
+                       cf_util_get_service (c, &db->port);
                else if (0 == strcasecmp (c->key, "User"))
-                       config_set_s ("User", &db->user, c);
+                       cf_util_get_string (c, &db->user);
                else if (0 == strcasecmp (c->key, "Password"))
-                       config_set_s ("Password", &db->password, c);
+                       cf_util_get_string (c, &db->password);
+               else if (0 == strcasecmp (c->key, "Instance"))
+                       cf_util_get_string (c, &db->instance);
                else if (0 == strcasecmp (c->key, "SSLMode"))
-                       config_set_s ("SSLMode", &db->sslmode, c);
+                       cf_util_get_string (c, &db->sslmode);
                else if (0 == strcasecmp (c->key, "KRBSrvName"))
-                       config_set_s ("KRBSrvName", &db->krbsrvname, c);
+                       cf_util_get_string (c, &db->krbsrvname);
                else if (0 == strcasecmp (c->key, "Service"))
-                       config_set_s ("Service", &db->service, c);
+                       cf_util_get_string (c, &db->service);
                else if (0 == strcasecmp (c->key, "Query"))
-                       config_set_query (db, c);
+                       udb_query_pick_from_list (c, queries, queries_num,
+                                       &db->queries, &db->queries_num);
+               else if (0 == strcasecmp (c->key, "Writer"))
+                       config_add_writer (c, writers, writers_num,
+                                       &db->writers, &db->writers_num);
+               else if (0 == strcasecmp (c->key, "Interval"))
+                       cf_util_get_cdtime (c, &db->interval);
+               else if (strcasecmp ("CommitInterval", c->key) == 0)
+                       cf_util_get_cdtime (c, &db->commit_interval);
                else
                        log_warn ("Ignoring unknown config key \"%s\".", c->key);
        }
 
-       if (NULL == db->queries) {
-               for (i = 0; i < def_queries_num; ++i)
-                       set_query (db, def_queries[i]);
+       /* If no `Query' options were given, add the default queries.. */
+       if ((db->queries_num == 0) && (db->writers_num == 0)){
+               for (i = 0; i < def_queries_num; i++)
+                       udb_query_pick_from_list_by_name (def_queries[i],
+                                       queries, queries_num,
+                                       &db->queries, &db->queries_num);
        }
 
-       db->hidden_queries = (int *)calloc (db->queries_num,
-                       sizeof (*db->hidden_queries));
-       if (NULL == db->hidden_queries) {
-               log_err ("Out of memory.");
-               exit (5);
+       if (db->queries_num > 0) {
+               db->q_prep_areas = (udb_query_preparation_area_t **) calloc (
+                               db->queries_num, sizeof (*db->q_prep_areas));
+
+               if (db->q_prep_areas == NULL) {
+                       log_err ("Out of memory.");
+                       c_psql_database_delete (db);
+                       return -1;
+               }
+       }
+
+       for (i = 0; (size_t)i < db->queries_num; ++i) {
+               c_psql_user_data_t *data;
+               data = udb_query_get_user_data (db->queries[i]);
+               if ((data != NULL) && (data->params_num > db->max_params_num))
+                       db->max_params_num = data->params_num;
+
+               db->q_prep_areas[i]
+                       = udb_query_allocate_preparation_area (db->queries[i]);
+
+               if (db->q_prep_areas[i] == NULL) {
+                       log_err ("Out of memory.");
+                       c_psql_database_delete (db);
+                       return -1;
+               }
+       }
+
+       ud.data = db;
+       ud.free_func = c_psql_database_delete;
+
+       ssnprintf (cb_name, sizeof (cb_name), "postgresql-%s", db->instance);
+
+       if (db->queries_num > 0) {
+               CDTIME_T_TO_TIMESPEC (db->interval, &cb_interval);
+
+               ++db->ref_cnt;
+               plugin_register_complex_read ("postgresql", cb_name, c_psql_read,
+                               /* interval = */ (db->interval > 0) ? &cb_interval : NULL,
+                               &ud);
+       }
+       if (db->writers_num > 0) {
+               ++db->ref_cnt;
+               plugin_register_write (cb_name, c_psql_write, &ud);
+
+               if (! have_flush) {
+                       /* flush all */
+                       plugin_register_flush ("postgresql",
+                                       c_psql_flush, /* user data = */ NULL);
+                       have_flush = 1;
+               }
+
+               /* flush this connection only */
+               ++db->ref_cnt;
+               plugin_register_flush (cb_name, c_psql_flush, &ud);
+       }
+       else if (db->commit_interval > 0) {
+               log_warn ("Database '%s': You do not have any writers assigned to "
+                               "this database connection. Setting 'CommitInterval' does "
+                               "not have any effect.", db->database);
        }
        return 0;
 } /* c_psql_config_database */
@@ -1138,7 +1342,10 @@ static int c_psql_config (oconfig_item_t *ci)
                oconfig_item_t *c = ci->children + i;
 
                if (0 == strcasecmp (c->key, "Query"))
-                       c_psql_config_query (c);
+                       udb_query_create (&queries, &queries_num, c,
+                                       /* callback = */ config_query_callback);
+               else if (0 == strcasecmp (c->key, "Writer"))
+                       c_psql_config_writer (c);
                else if (0 == strcasecmp (c->key, "Database"))
                        c_psql_config_database (c);
                else
@@ -1150,8 +1357,7 @@ static int c_psql_config (oconfig_item_t *ci)
 void module_register (void)
 {
        plugin_register_complex_config ("postgresql", c_psql_config);
-       plugin_register_init ("postgresql", c_psql_init);
+       plugin_register_shutdown ("postgresql", c_psql_shutdown);
 } /* module_register */
 
 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
-