GNUnet  0.11.x
Data Structures | Macros | Typedefs | Functions
gnunet_pq_lib.h File Reference

helper functions for Postgres DB interactions More...

#include <libpq-fe.h>
#include "gnunet_util_lib.h"
#include "gnunet_db_lib.h"
Include dependency graph for gnunet_pq_lib.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  GNUNET_PQ_QueryParam
 Description of a DB query parameter. More...
 
struct  GNUNET_PQ_ResultSpec
 Description of a DB result cell. More...
 
struct  GNUNET_PQ_PreparedStatement
 Information needed to prepare a list of SQL statements using GNUNET_PQ_prepare_statements(). More...
 
struct  GNUNET_PQ_ExecuteStatement
 Information needed to run a list of SQL statements using GNUNET_PQ_exec_statements(). More...
 
struct  GNUNET_PQ_EventHeaderP
 Header of a structure that describes an event channel we may subscribe to or notify on. More...
 

Macros

#define GNUNET_PQ_query_param_end
 End of query parameter specification. More...
 
#define GNUNET_PQ_query_param_auto_from_type(x)   GNUNET_PQ_query_param_fixed_size ((x), sizeof(*(x)))
 Generate fixed-size query parameter with size determined by variable type. More...
 
#define GNUNET_PQ_result_spec_end
 End of result parameter specification. More...
 
#define GNUNET_PQ_result_spec_auto_from_type(name, dst)   GNUNET_PQ_result_spec_fixed_size (name, (dst), sizeof(*(dst)))
 We expect a fixed-size result, with size determined by the type of * dst More...
 
#define GNUNET_PQ_PREPARED_STATEMENT_END
 Terminator for prepared statement list. More...
 
#define GNUNET_PQ_EXECUTE_STATEMENT_END
 Terminator for executable statement list. More...
 

Typedefs

typedef int(* GNUNET_PQ_QueryConverter) (void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
 Function called to convert input argument into SQL parameters. More...
 
typedef enum GNUNET_GenericReturnValue(* GNUNET_PQ_ResultConverter) (void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
 Extract data from a Postgres database result at row row. More...
 
typedef void(* GNUNET_PQ_ResultCleanup) (void *cls, void *rd)
 Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter. More...
 
typedef void(* GNUNET_PQ_PostgresResultHandler) (void *cls, PGresult *result, unsigned int num_results)
 Function to be called with the results of a SELECT statement that has returned num_results results. More...
 
typedef void(* GNUNET_PQ_SocketCallback) (void *cls, int fd)
 Function called whenever the socket needed for notifications from postgres changes. More...
 
typedef void(* GNUNET_PQ_EventCallback) (void *cls, const void *extra, size_t extra_size)
 Function called on events received from Postgres. More...
 

Functions

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_null (void)
 Generate query parameter to create a NULL value. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_fixed_size (const void *ptr, size_t ptr_size)
 Generate query parameter for a buffer ptr of ptr_size bytes. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_string (const char *ptr)
 Generate query parameter for a string. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x)
 Generate query parameter for an RSA public key. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x)
 Generate query parameter for an RSA signature. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_relative_time (const struct GNUNET_TIME_Relative *x)
 Generate query parameter for a relative time value. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x)
 Generate query parameter for an absolute time value. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_absolute_time_nbo (const struct GNUNET_TIME_AbsoluteNBO *x)
 Generate query parameter for an absolute time value. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint16 (const uint16_t *x)
 Generate query parameter for an uint16_t in host byte order. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint32 (const uint32_t *x)
 Generate query parameter for an uint32_t in host byte order. More...
 
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint64 (const uint64_t *x)
 Generate query parameter for an uint16_t in host byte order. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_allow_null (struct GNUNET_PQ_ResultSpec rs, bool *is_null)
 Allow NULL value to be found in the database for the given value. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_variable_size (const char *name, void **dst, size_t *sptr)
 Variable-size result expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_fixed_size (const char *name, void *dst, size_t dst_size)
 Fixed-size result expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_string (const char *name, char **dst)
 0-terminated string expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_rsa_public_key (const char *name, struct GNUNET_CRYPTO_RsaPublicKey **rsa)
 RSA public key expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_rsa_signature (const char *name, struct GNUNET_CRYPTO_RsaSignature **sig)
 RSA signature expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_absolute_time (const char *name, struct GNUNET_TIME_Absolute *at)
 Absolute time expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_relative_time (const char *name, struct GNUNET_TIME_Relative *rt)
 Relative time expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_absolute_time_nbo (const char *name, struct GNUNET_TIME_AbsoluteNBO *at)
 Absolute time expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint16 (const char *name, uint16_t *u16)
 uint16_t expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint32 (const char *name, uint32_t *u32)
 uint32_t expected. More...
 
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint64 (const char *name, uint64_t *u64)
 uint64_t expected. More...
 
PGresult * GNUNET_PQ_exec_prepared (struct GNUNET_PQ_Context *db, const char *name, const struct GNUNET_PQ_QueryParam *params)
 Execute a prepared statement. More...
 
enum GNUNET_GenericReturnValue GNUNET_PQ_extract_result (PGresult *result, struct GNUNET_PQ_ResultSpec *rs, int row)
 Extract results from a query result according to the given specification. More...
 
void GNUNET_PQ_cleanup_result (struct GNUNET_PQ_ResultSpec *rs)
 Free all memory that was allocated in rs during GNUNET_PQ_extract_result(). More...
 
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_result (struct GNUNET_PQ_Context *db, const char *statement_name, PGresult *result)
 Check the result's error code to see what happened. More...
 
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_non_select (struct GNUNET_PQ_Context *db, const char *statement_name, const struct GNUNET_PQ_QueryParam *params)
 Execute a named prepared statement that is NOT a SELECT statement in connection using the given params. More...
 
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_multi_select (struct GNUNET_PQ_Context *db, const char *statement_name, const struct GNUNET_PQ_QueryParam *params, GNUNET_PQ_PostgresResultHandler rh, void *rh_cls)
 Execute a named prepared statement that is a SELECT statement which may return multiple results in connection using the given params. More...
 
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_singleton_select (struct GNUNET_PQ_Context *db, const char *statement_name, const struct GNUNET_PQ_QueryParam *params, struct GNUNET_PQ_ResultSpec *rs)
 Execute a named prepared statement that is a SELECT statement which must return a single result in connection using the given params. More...
 
struct GNUNET_PQ_PreparedStatement GNUNET_PQ_make_prepare (const char *name, const char *sql, unsigned int num_args)
 Create a struct GNUNET_PQ_PreparedStatement. More...
 
int GNUNET_PQ_prepare_statements (struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_PreparedStatement *ps)
 Request creation of prepared statements ps from Postgres. More...
 
struct GNUNET_PQ_ExecuteStatement GNUNET_PQ_make_execute (const char *sql)
 Create a struct GNUNET_PQ_ExecuteStatement where errors are fatal. More...
 
struct GNUNET_PQ_ExecuteStatement GNUNET_PQ_make_try_execute (const char *sql)
 Create a struct GNUNET_PQ_ExecuteStatement where errors should be tolerated. More...
 
int GNUNET_PQ_exec_statements (struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_ExecuteStatement *es)
 Request execution of an array of statements es from Postgres. More...
 
struct GNUNET_PQ_ContextGNUNET_PQ_connect (const char *config_str, const char *load_path, const struct GNUNET_PQ_ExecuteStatement *es, const struct GNUNET_PQ_PreparedStatement *ps)
 Create a connection to the Postgres database using config_str for the configuration. More...
 
struct GNUNET_PQ_ContextGNUNET_PQ_connect_with_cfg (const struct GNUNET_CONFIGURATION_Handle *cfg, const char *section, const char *load_path_suffix, const struct GNUNET_PQ_ExecuteStatement *es, const struct GNUNET_PQ_PreparedStatement *ps)
 Connect to a postgres database using the configuration option "CONFIG" in section. More...
 
void GNUNET_PQ_reconnect_if_down (struct GNUNET_PQ_Context *db)
 Reinitialize the database db if the connection is down. More...
 
void GNUNET_PQ_reconnect (struct GNUNET_PQ_Context *db)
 Reinitialize the database db. More...
 
void GNUNET_PQ_event_set_socket_callback (struct GNUNET_PQ_Context *db, GNUNET_PQ_SocketCallback sc, void *sc_cls)
 Obtain the file descriptor to poll on for notifications. More...
 
void GNUNET_PQ_event_do_poll (struct GNUNET_PQ_Context *db)
 Poll for database events now. More...
 
void GNUNET_PQ_event_scheduler_start (struct GNUNET_PQ_Context *db)
 Run poll event loop using the GNUnet scheduler. More...
 
void GNUNET_PQ_event_scheduler_stop (struct GNUNET_PQ_Context *db)
 Stop running poll event loop using the GNUnet scheduler. More...
 
struct GNUNET_PQ_EventHandlerGNUNET_PQ_event_listen (struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_EventHeaderP *es, GNUNET_PQ_EventCallback cb, void *cb_cls)
 Register callback to be invoked on events of type es. More...
 
void GNUNET_PQ_event_listen_cancel (struct GNUNET_PQ_EventHandler *eh)
 Stop notifications. More...
 
void GNUNET_PQ_event_notify (struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_EventHeaderP *es, const void *extra, size_t extra_size)
 Notify all that listen on es of an event. More...
 
enum GNUNET_GenericReturnValue GNUNET_PQ_run_sql (struct GNUNET_PQ_Context *db, const char *load_path)
 Within the db context, run all the SQL files from the load_path from 0000-9999.sql (as long as the files exist contiguously). More...
 
void GNUNET_PQ_disconnect (struct GNUNET_PQ_Context *db)
 Disconnect from the database, destroying the prepared statements and releasing other associated resources. More...
 

Detailed Description

helper functions for Postgres DB interactions

Author
Christian Grothoff

Definition in file gnunet_pq_lib.h.

Macro Definition Documentation

◆ GNUNET_PQ_query_param_end

#define GNUNET_PQ_query_param_end

◆ GNUNET_PQ_query_param_auto_from_type

#define GNUNET_PQ_query_param_auto_from_type (   x)    GNUNET_PQ_query_param_fixed_size ((x), sizeof(*(x)))

◆ GNUNET_PQ_result_spec_end

#define GNUNET_PQ_result_spec_end
Value:
{ \
NULL, NULL, NULL, NULL, 0, NULL, NULL \
}

End of result parameter specification.

Returns
array last entry for the result specification to use

Definition at line 336 of file gnunet_pq_lib.h.

Referenced by extract_result_cb(), GNUNET_PQ_run_sql(), handle_results(), namecache_postgres_lookup_block(), parse_result_call_iterator(), postgres_plugin_del(), postgres_plugin_estimate_size(), postgres_plugin_get_random(), process_keys(), and process_result().

◆ GNUNET_PQ_result_spec_auto_from_type

#define GNUNET_PQ_result_spec_auto_from_type (   name,
  dst 
)    GNUNET_PQ_result_spec_fixed_size (name, (dst), sizeof(*(dst)))

We expect a fixed-size result, with size determined by the type of * dst

Parameters
namename of the field in the table
dstpoint to where to store the result, type fits expected result size
Returns
array entry for the result specification to use

Definition at line 390 of file gnunet_pq_lib.h.

Referenced by extract_result_cb(), GNUNET_PQ_result_spec_absolute_time_nbo(), parse_result_call_iterator(), postgres_plugin_del(), postgres_plugin_get_random(), process_keys(), and process_result().

◆ GNUNET_PQ_PREPARED_STATEMENT_END

#define GNUNET_PQ_PREPARED_STATEMENT_END
Value:
{ \
NULL, NULL, 0 \
}

Terminator for prepared statement list.

Definition at line 681 of file gnunet_pq_lib.h.

Referenced by database_setup(), and init_connection().

◆ GNUNET_PQ_EXECUTE_STATEMENT_END

#define GNUNET_PQ_EXECUTE_STATEMENT_END
Value:

Terminator for executable statement list.

Definition at line 739 of file gnunet_pq_lib.h.

Referenced by database_setup(), init_connection(), and postgres_plugin_drop().

Typedef Documentation

◆ GNUNET_PQ_QueryConverter

typedef int(* GNUNET_PQ_QueryConverter) (void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)

Function called to convert input argument into SQL parameters.

Parameters
clsclosure
datapointer to input argument
data_lennumber of bytes in data (if applicable)
[out]param_valuesSQL data to set
[out]param_lengthsSQL length data to set
[out]param_formatsSQL format data to set
param_lengthnumber of entries available in the param_values, param_lengths and param_formats arrays
[out]scratchbuffer for dynamic allocations (to be done via GNUNET_malloc()
scratch_lengthnumber of entries left in scratch
Returns
-1 on error, number of offsets used in scratch otherwise

Definition at line 50 of file gnunet_pq_lib.h.

◆ GNUNET_PQ_ResultConverter

typedef enum GNUNET_GenericReturnValue(* GNUNET_PQ_ResultConverter) (void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)

Extract data from a Postgres database result at row row.

Parameters
clsclosure
resultwhere to extract data from
introw to extract data from
fnamename (or prefix) of the fields to extract from
[in,out]dst_sizewhere to store size of result, may be NULL
[out]dstwhere to store the result
Returns
GNUNET_YES if all results could be extracted GNUNET_NO if the field was NULL GNUNET_SYSERR if a result was invalid (non-existing field)

Definition at line 252 of file gnunet_pq_lib.h.

◆ GNUNET_PQ_ResultCleanup

typedef void(* GNUNET_PQ_ResultCleanup) (void *cls, void *rd)

Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter.

Parameters
clsclosure
rdresult data to clean up

Definition at line 268 of file gnunet_pq_lib.h.

◆ GNUNET_PQ_PostgresResultHandler

typedef void(* GNUNET_PQ_PostgresResultHandler) (void *cls, PGresult *result, unsigned int num_results)

Function to be called with the results of a SELECT statement that has returned num_results results.

Parameters
clsclosure
resultthe postgres result
num_resultthe number of results in result

Definition at line 600 of file gnunet_pq_lib.h.

◆ GNUNET_PQ_SocketCallback

typedef void(* GNUNET_PQ_SocketCallback) (void *cls, int fd)

Function called whenever the socket needed for notifications from postgres changes.

Parameters
clsclosure
fdsocket to listen on, -1 for none

Definition at line 863 of file gnunet_pq_lib.h.

◆ GNUNET_PQ_EventCallback

typedef void(* GNUNET_PQ_EventCallback) (void *cls, const void *extra, size_t extra_size)

Function called on events received from Postgres.

Parameters
clsclosure
extraadditional event data provided
extra_sizenumber of bytes in extra

Definition at line 926 of file gnunet_pq_lib.h.

Function Documentation

◆ GNUNET_PQ_query_param_null()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_null ( void  )

Generate query parameter to create a NULL value.

Returns
query parameter to use to insert NULL into DB

Definition at line 70 of file pq_query_helper.c.

References qconv_null(), and res.

71 {
72  struct GNUNET_PQ_QueryParam res = {
73  &qconv_null, NULL, NULL, 0, 1
74  };
75 
76  return res;
77 }
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
static int qconv_null(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
Here is the call graph for this function:

◆ GNUNET_PQ_query_param_fixed_size()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_fixed_size ( const void *  ptr,
size_t  ptr_size 
)

Generate query parameter for a buffer ptr of ptr_size bytes.

Parameters
ptrpointer to the query parameter to pass ptr_size number of bytes in ptr
Returns
query parameter to use

Definition at line 118 of file pq_query_helper.c.

References qconv_fixed(), and res.

Referenced by GNUNET_PQ_query_param_string(), namecache_postgres_cache_block(), namestore_postgres_store_records(), postgres_plugin_put(), and postgres_plugin_remove_key().

120 {
121  struct GNUNET_PQ_QueryParam res = {
122  &qconv_fixed, NULL, ptr, ptr_size, 1
123  };
124 
125  return res;
126 }
static int qconv_fixed(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_query_param_string()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_string ( const char *  ptr)

Generate query parameter for a string.

Parameters
ptrpointer to the string query parameter to pass
Returns
query parameter to use

Definition at line 130 of file pq_query_helper.c.

References GNUNET_PQ_query_param_fixed_size().

Referenced by GNUNET_PQ_run_sql(), namestore_postgres_lookup_records(), and namestore_postgres_store_records().

131 {
133  strlen (ptr));
134 }
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_fixed_size(const void *ptr, size_t ptr_size)
Generate query parameter for a buffer ptr of ptr_size bytes.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_query_param_rsa_public_key()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_rsa_public_key ( const struct GNUNET_CRYPTO_RsaPublicKey x)

Generate query parameter for an RSA public key.

The database must contain a BLOB type in the respective position.

Parameters
xthe query parameter to pass.
Returns
query parameter to use

Definition at line 339 of file pq_query_helper.c.

References qconv_rsa_public_key(), and res.

341 {
342  struct GNUNET_PQ_QueryParam res =
343  { &qconv_rsa_public_key, NULL, (x), 0, 1 };
344 
345  return res;
346 }
static int qconv_rsa_public_key(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:

◆ GNUNET_PQ_query_param_rsa_signature()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_rsa_signature ( const struct GNUNET_CRYPTO_RsaSignature x)

Generate query parameter for an RSA signature.

The database must contain a BLOB type in the respective position.

Parameters
xthe query parameter to pass
Returns
query parameter to use

Definition at line 392 of file pq_query_helper.c.

References qconv_rsa_signature(), and res.

393 {
394  struct GNUNET_PQ_QueryParam res =
395  { &qconv_rsa_signature, NULL, (x), 0, 1 };
396 
397  return res;
398 }
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
static int qconv_rsa_signature(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
Here is the call graph for this function:

◆ GNUNET_PQ_query_param_relative_time()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_relative_time ( const struct GNUNET_TIME_Relative x)

Generate query parameter for a relative time value.

The database must store a 64-bit integer.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 447 of file pq_query_helper.c.

References qconv_rel_time(), and res.

448 {
449  struct GNUNET_PQ_QueryParam res =
450  { &qconv_rel_time, NULL, x, sizeof(*x), 1 };
451 
452  return res;
453 }
static int qconv_rel_time(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:

◆ GNUNET_PQ_query_param_absolute_time()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_absolute_time ( const struct GNUNET_TIME_Absolute x)

Generate query parameter for an absolute time value.

The database must store a 64-bit integer.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 502 of file pq_query_helper.c.

References qconv_abs_time(), and res.

Referenced by delete_old_block(), namecache_postgres_cache_block(), namecache_postgres_expire_blocks(), postgres_plugin_del(), postgres_plugin_get(), postgres_plugin_get_closest(), postgres_plugin_get_expiration(), postgres_plugin_get_random(), and postgres_plugin_put().

503 {
504  struct GNUNET_PQ_QueryParam res = {
505  &qconv_abs_time, NULL, x, sizeof(*x), 1
506  };
507 
508  return res;
509 }
static int qconv_abs_time(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_query_param_absolute_time_nbo()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_absolute_time_nbo ( const struct GNUNET_TIME_AbsoluteNBO x)

Generate query parameter for an absolute time value.

The database must store a 64-bit integer.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 513 of file pq_query_helper.c.

References GNUNET_PQ_query_param_auto_from_type.

515 {
517 }
#define GNUNET_PQ_query_param_auto_from_type(x)
Generate fixed-size query parameter with size determined by variable type.
uint64_t abs_value_us__
The actual value (in network byte order).

◆ GNUNET_PQ_query_param_uint16()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint16 ( const uint16_t *  x)

Generate query parameter for an uint16_t in host byte order.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 181 of file pq_query_helper.c.

References qconv_uint16(), and res.

Referenced by postgres_plugin_get_key().

182 {
183  struct GNUNET_PQ_QueryParam res =
184  { &qconv_uint16, NULL, x, sizeof(*x), 1 };
185 
186  return res;
187 }
static int qconv_uint16(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_query_param_uint32()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint32 ( const uint32_t *  x)

Generate query parameter for an uint32_t in host byte order.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 234 of file pq_query_helper.c.

References qconv_uint32(), and res.

Referenced by namestore_postgres_store_records(), postgres_plugin_del(), postgres_plugin_get(), postgres_plugin_get_closest(), postgres_plugin_get_key(), postgres_plugin_get_random(), postgres_plugin_get_zero_anonymity(), postgres_plugin_put(), process_result(), and repl_proc().

235 {
236  struct GNUNET_PQ_QueryParam res =
237  { &qconv_uint32, NULL, x, sizeof(*x), 1 };
238 
239  return res;
240 }
static int qconv_uint32(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_query_param_uint64()

struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_uint64 ( const uint64_t *  x)

Generate query parameter for an uint16_t in host byte order.

Parameters
xpointer to the query parameter to pass
Returns
query parameter to use

Definition at line 287 of file pq_query_helper.c.

References qconv_uint64(), and res.

Referenced by namestore_postgres_iterate_records(), namestore_postgres_store_records(), postgres_plugin_get_key(), postgres_plugin_get_zero_anonymity(), and postgres_plugin_put().

288 {
289  struct GNUNET_PQ_QueryParam res =
290  { &qconv_uint64, NULL, x, sizeof(*x), 1 };
291 
292  return res;
293 }
static int res
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
static int qconv_uint64(void *cls, const void *data, size_t data_len, void *param_values[], int param_lengths[], int param_formats[], unsigned int param_length, void *scratch[], unsigned int scratch_length)
Function called to convert input argument into SQL parameters.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_result_spec_allow_null()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_allow_null ( struct GNUNET_PQ_ResultSpec  rs,
bool *  is_null 
)

Allow NULL value to be found in the database for the given value.

Parameters
rsresult spec entry to modify
[out]is_nulllocation set to 'true' if the value was indeed NULL, set to 'false' if the value was non-NULL
Returns
array entry for the result specification to use

Definition at line 31 of file pq_result_helper.c.

References GNUNET_PQ_ResultSpec::is_null, and GNUNET_PQ_ResultSpec::is_nullable.

33 {
34  struct GNUNET_PQ_ResultSpec rsr;
35 
36  rsr = rs;
37  rsr.is_nullable = true;
38  rsr.is_null = is_null;
39  return rsr;
40 }
Description of a DB result cell.
bool is_nullable
True if NULL is allowed for a value in the database.
bool * is_null
Points to a location where we should store "true" if the result found is NULL, and otherwise "false"...

◆ GNUNET_PQ_result_spec_variable_size()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_variable_size ( const char *  name,
void **  dst,
size_t *  sptr 
)

Variable-size result expected.

Parameters
namename of the field in the table
[out]dstwhere to store the result, allocated
[out]sptrwhere to store the size of dst
Returns
array entry for the result specification to use

Definition at line 126 of file pq_result_helper.c.

References clean_varsize_blob(), GNUNET_PQ_ResultSpec::dst, extract_varsize_blob(), name, and res.

Referenced by extract_result_cb(), handle_results(), namecache_postgres_lookup_block(), parse_result_call_iterator(), postgres_plugin_get_random(), and process_result().

129 {
130  struct GNUNET_PQ_ResultSpec res =
132  &clean_varsize_blob, NULL,
133  (void *) (dst), 0, name, sptr };
134 
135  return res;
136 }
static enum GNUNET_GenericReturnValue extract_varsize_blob(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
Description of a DB result cell.
static int res
static void clean_varsize_blob(void *cls, void *rd)
Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter.
const char * name
void * dst
Destination for the data.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_result_spec_fixed_size()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_fixed_size ( const char *  name,
void *  dst,
size_t  dst_size 
)

Fixed-size result expected.

Parameters
namename of the field in the table
[out]dstwhere to store the result
dst_sizenumber of bytes in dst
Returns
array entry for the result specification to use

Definition at line 206 of file pq_result_helper.c.

References GNUNET_PQ_ResultSpec::dst, GNUNET_PQ_ResultSpec::dst_size, extract_fixed_blob(), and res.

209 {
210  struct GNUNET_PQ_ResultSpec res =
212  NULL, NULL,
213  (dst), dst_size, name, NULL };
214 
215  return res;
216 }
Description of a DB result cell.
static enum GNUNET_GenericReturnValue extract_fixed_blob(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
size_t dst_size
Allowed size for the data, 0 for variable-size (in this case, the type of dst is a void ** and we nee...
static int res
const char * name
void * dst
Destination for the data.
Here is the call graph for this function:

◆ GNUNET_PQ_result_spec_string()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_string ( const char *  name,
char **  dst 
)

0-terminated string expected.

Parameters
namename of the field in the table
[out]dstwhere to store the result, allocated
Returns
array entry for the result specification to use

Definition at line 489 of file pq_result_helper.c.

References clean_string(), GNUNET_PQ_ResultSpec::dst, extract_string(), and res.

Referenced by GNUNET_PQ_run_sql(), and parse_result_call_iterator().

491 {
492  struct GNUNET_PQ_ResultSpec res =
493  { &extract_string,
494  &clean_string,
495  NULL,
496  (void *) dst, 0, (name), NULL };
497 
498  return res;
499 }
static enum GNUNET_GenericReturnValue extract_string(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
static void clean_string(void *cls, void *rd)
Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter.
Description of a DB result cell.
static int res
const char * name
void * dst
Destination for the data.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_result_spec_rsa_public_key()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_rsa_public_key ( const char *  name,
struct GNUNET_CRYPTO_RsaPublicKey **  rsa 
)

RSA public key expected.

Parameters
namename of the field in the table
[out]rsawhere to store the result
Returns
array entry for the result specification to use

Definition at line 301 of file pq_result_helper.c.

References clean_rsa_public_key(), extract_rsa_public_key(), and res.

303 {
304  struct GNUNET_PQ_ResultSpec res =
307  NULL,
308  (void *) rsa, 0, name, NULL };
309 
310  return res;
311 }
Description of a DB result cell.
static int res
static void clean_rsa_public_key(void *cls, void *rd)
Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter.
static enum GNUNET_GenericReturnValue extract_rsa_public_key(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
const char * name
Here is the call graph for this function:

◆ GNUNET_PQ_result_spec_rsa_signature()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_rsa_signature ( const char *  name,
struct GNUNET_CRYPTO_RsaSignature **  sig 
)

RSA signature expected.

Parameters
namename of the field in the table
[out]sigwhere to store the result;
Returns
array entry for the result specification to use

Definition at line 395 of file pq_result_helper.c.

References clean_rsa_signature(), extract_rsa_signature(), and res.

397 {
398  struct GNUNET_PQ_ResultSpec res =
401  NULL,
402  (void *) sig, 0, (name), NULL };
403 
404  return res;
405 }
Description of a DB result cell.
static void clean_rsa_signature(void *cls, void *rd)
Function called to clean up memory allocated by a GNUNET_PQ_ResultConverter.
static int res
static enum GNUNET_GenericReturnValue extract_rsa_signature(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
const char * name
Here is the call graph for this function:

◆ GNUNET_PQ_result_spec_absolute_time()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_absolute_time ( const char *  name,
struct GNUNET_TIME_Absolute at 
)

Absolute time expected.

Parameters
namename of the field in the table
[out]atwhere to store the result
Returns
array entry for the result specification to use

Definition at line 645 of file pq_result_helper.c.

References extract_abs_time(), name, and res.

Referenced by extract_result_cb(), handle_results(), postgres_plugin_get_random(), and process_result().

647 {
648  struct GNUNET_PQ_ResultSpec res =
649  { &extract_abs_time,
650  NULL,
651  NULL,
652  (void *) at, sizeof(*at), (name), NULL };
653 
654  return res;
655 }
Description of a DB result cell.
static int res
static enum GNUNET_GenericReturnValue extract_abs_time(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
const char * name
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_result_spec_relative_time()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_relative_time ( const char *  name,
struct GNUNET_TIME_Relative rt 
)

Relative time expected.

Parameters
namename of the field in the table
[out]rtwhere to store the result
Returns
array entry for the result specification to use

Definition at line 565 of file pq_result_helper.c.

References extract_rel_time(), name, and res.

567 {
568  struct GNUNET_PQ_ResultSpec res = {
570  NULL,
571  NULL,
572  (void *) rt,
573  sizeof(*rt),
574  name,
575  NULL
576  };
577 
578  return res;
579 }
Description of a DB result cell.
static enum GNUNET_GenericReturnValue extract_rel_time(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
static int res
const char * name
Here is the call graph for this function:

◆ GNUNET_PQ_result_spec_absolute_time_nbo()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_absolute_time_nbo ( const char *  name,
struct GNUNET_TIME_AbsoluteNBO at 
)

Absolute time expected.

Parameters
namename of the field in the table
[out]atwhere to store the result
Returns
array entry for the result specification to use

Definition at line 659 of file pq_result_helper.c.

References GNUNET_PQ_result_spec_auto_from_type, and res.

661 {
662  struct GNUNET_PQ_ResultSpec res =
664 
665  return res;
666 }
Description of a DB result cell.
static int res
#define GNUNET_PQ_result_spec_auto_from_type(name, dst)
We expect a fixed-size result, with size determined by the type of * dst
const char * name
uint64_t abs_value_us__
The actual value (in network byte order).

◆ GNUNET_PQ_result_spec_uint16()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint16 ( const char *  name,
uint16_t *  u16 
)

uint16_t expected.

Parameters
namename of the field in the table
[out]u16where to store the result
Returns
array entry for the result specification to use

Definition at line 729 of file pq_result_helper.c.

References extract_uint16(), name, and res.

731 {
732  struct GNUNET_PQ_ResultSpec res =
733  { &extract_uint16,
734  NULL,
735  NULL,
736  (void *) u16, sizeof(*u16), (name), NULL };
737 
738  return res;
739 }
Description of a DB result cell.
static enum GNUNET_GenericReturnValue extract_uint16(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
static int res
const char * name
Here is the call graph for this function:

◆ GNUNET_PQ_result_spec_uint32()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint32 ( const char *  name,
uint32_t *  u32 
)

uint32_t expected.

Parameters
namename of the field in the table
[out]u32where to store the result
Returns
array entry for the result specification to use

Definition at line 802 of file pq_result_helper.c.

References extract_uint32(), name, and res.

Referenced by extract_result_cb(), handle_results(), parse_result_call_iterator(), postgres_plugin_del(), postgres_plugin_get_random(), and process_result().

804 {
805  struct GNUNET_PQ_ResultSpec res = {
807  NULL,
808  NULL,
809  (void *) u32,
810  sizeof(*u32),
811  (name),
812  NULL
813  };
814 
815  return res;
816 }
Description of a DB result cell.
static int res
const char * name
static enum GNUNET_GenericReturnValue extract_uint32(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_result_spec_uint64()

struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_uint64 ( const char *  name,
uint64_t *  u64 
)

uint64_t expected.

Parameters
namename of the field in the table
[out]u64where to store the result
Returns
array entry for the result specification to use

Definition at line 883 of file pq_result_helper.c.

References extract_uint64(), name, and res.

Referenced by parse_result_call_iterator(), and postgres_plugin_estimate_size().

885 {
886  struct GNUNET_PQ_ResultSpec res = {
888  NULL,
889  NULL,
890  (void *) u64,
891  sizeof(*u64),
892  (name),
893  NULL
894  };
895 
896  return res;
897 }
Description of a DB result cell.
static enum GNUNET_GenericReturnValue extract_uint64(void *cls, PGresult *result, int row, const char *fname, size_t *dst_size, void *dst)
Extract data from a Postgres database result at row row.
static int res
const char * name
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_exec_prepared()

PGresult* GNUNET_PQ_exec_prepared ( struct GNUNET_PQ_Context db,
const char *  name,
const struct GNUNET_PQ_QueryParam params 
)

Execute a prepared statement.

Parameters
dbdatabase context
namename of the prepared statement
paramsparameters to the statement
Returns
postgres result
Deprecated:
(should become an internal API)

Definition at line 32 of file pq.c.

References GNUNET_PQ_Context::conn, GNUNET_PQ_QueryParam::conv, GNUNET_PQ_QueryParam::conv_cls, GNUNET_PQ_QueryParam::data, GNUNET_assert, GNUNET_ERROR_TYPE_DEBUG, GNUNET_free, GNUNET_log, GNUNET_log_from, GNUNET_PQ_reconnect(), len, GNUNET_PQ_QueryParam::num_params, res, ret, GNUNET_PQ_QueryParam::size, and status.

Referenced by GNUNET_PQ_eval_prepared_multi_select(), GNUNET_PQ_eval_prepared_non_select(), and GNUNET_PQ_eval_prepared_singleton_select().

35 {
36  unsigned int len;
37 
39  "Running prepared statement `%s' on %p\n",
40  name,
41  db);
42  /* count the number of parameters */
43  len = 0;
44  for (unsigned int i = 0; 0 != params[i].num_params; i++)
45  len += params[i].num_params;
46 
47  /* new scope to allow stack allocation without alloca */
48  {
49  /* Scratch buffer for temporary storage */
50  void *scratch[len];
51  /* Parameter array we are building for the query */
52  void *param_values[len];
53  int param_lengths[len];
54  int param_formats[len];
55  unsigned int off;
56  /* How many entries in the scratch buffer are in use? */
57  unsigned int soff;
58  PGresult *res;
59  int ret;
60  ConnStatusType status;
61 
62  off = 0;
63  soff = 0;
64  for (unsigned int i = 0; 0 != params[i].num_params; i++)
65  {
66  const struct GNUNET_PQ_QueryParam *x = &params[i];
67 
68  ret = x->conv (x->conv_cls,
69  x->data,
70  x->size,
71  &param_values[off],
72  &param_lengths[off],
73  &param_formats[off],
74  x->num_params,
75  &scratch[soff],
76  len - soff);
77  if (ret < 0)
78  {
79  for (off = 0; off < soff; off++)
80  GNUNET_free (scratch[off]);
81  return NULL;
82  }
83  soff += ret;
84  off += x->num_params;
85  }
86  GNUNET_assert (off == len);
88  "pq",
89  "Executing prepared SQL statement `%s'\n",
90  name);
91  res = PQexecPrepared (db->conn,
92  name,
93  len,
94  (const char **) param_values,
95  param_lengths,
96  param_formats,
97  1);
98  if ( (PGRES_COMMAND_OK != PQresultStatus (res)) &&
99  (CONNECTION_OK != (status = PQstatus (db->conn))) )
100  {
102  "pq",
103  "Database disconnected on SQL statement `%s' (reconnecting)\n",
104  name);
105  GNUNET_PQ_reconnect (db);
106  res = NULL;
107  }
108 
109  for (off = 0; off < soff; off++)
110  GNUNET_free (scratch[off]);
111  return res;
112  }
113 }
GNUNET_PQ_QueryConverter conv
Function for how to handle this type of entry.
Definition: gnunet_pq_lib.h:69
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
void GNUNET_PQ_reconnect(struct GNUNET_PQ_Context *db)
Reinitialize the database db.
Definition: pq_connect.c:295
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
const void * data
Data or NULL.
Definition: gnunet_pq_lib.h:79
PGconn * conn
Actual connection.
Definition: pq.h:39
uint16_t status
See PRISM_STATUS_*-constants.
void * conv_cls
Closure for conv.
Definition: gnunet_pq_lib.h:74
static int res
unsigned int num_params
Number of parameters eaten by this operation.
Definition: gnunet_pq_lib.h:89
const char * name
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
#define GNUNET_log(kind,...)
size_t size
Size of data.
Definition: gnunet_pq_lib.h:84
#define GNUNET_log_from(kind, comp,...)
#define GNUNET_free(ptr)
Wrapper around free.
uint16_t len
length of data (which is always a uint32_t, but presumably this can be used to specify that fewer byt...
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_extract_result()

enum GNUNET_GenericReturnValue GNUNET_PQ_extract_result ( PGresult *  result,
struct GNUNET_PQ_ResultSpec rs,
int  row 
)

Extract results from a query result according to the given specification.

Parameters
resultresult to process
[in,out]rsresult specification to extract for
rowrow from the result to extract
Returns
GNUNET_YES if all results could be extracted GNUNET_SYSERR if a result was invalid (non-existing field)

Definition at line 127 of file pq.c.

References GNUNET_PQ_ResultSpec::cleaner, cleanup(), GNUNET_PQ_ResultSpec::cls, GNUNET_PQ_ResultSpec::conv, GNUNET_PQ_ResultSpec::dst, GNUNET_PQ_ResultSpec::dst_size, GNUNET_PQ_ResultSpec::fname, GNUNET_break, GNUNET_ERROR_TYPE_ERROR, GNUNET_log, GNUNET_NO, GNUNET_OK, GNUNET_SYSERR, GNUNET_PQ_ResultSpec::is_null, GNUNET_PQ_ResultSpec::is_nullable, GNUNET_PQ_ResultSpec::result_size, and ret.

Referenced by extract_result_cb(), GNUNET_PQ_eval_prepared_singleton_select(), handle_results(), parse_result_call_iterator(), process_keys(), and process_result().

130 {
131  unsigned int i;
132 
133  if (NULL == result)
134  return GNUNET_SYSERR;
135  for (i = 0; NULL != rs[i].conv; i++)
136  {
137  struct GNUNET_PQ_ResultSpec *spec;
139 
140  spec = &rs[i];
141  ret = spec->conv (spec->cls,
142  result,
143  row,
144  spec->fname,
145  &spec->dst_size,
146  spec->dst);
147  switch (ret)
148  {
149  case GNUNET_OK:
150  /* canonical case, continue below */
151  if (NULL != spec->is_null)
152  *spec->is_null = false;
153  break;
154  case GNUNET_NO:
155  if (spec->is_nullable)
156  {
157  if (NULL != spec->is_null)
158  *spec->is_null = true;
159  continue;
160  }
162  "NULL field encountered for `%s' where non-NULL was required\n",
163  spec->fname);
164  goto cleanup;
165  case GNUNET_SYSERR:
166  GNUNET_break (0);
167  goto cleanup;
168  }
169  if (NULL != spec->result_size)
170  *spec->result_size = spec->dst_size;
171  }
172  return GNUNET_OK;
173 cleanup:
174  for (unsigned int j = 0; j < i; j++)
175  if (NULL != rs[j].cleaner)
176  rs[j].cleaner (rs[j].cls,
177  rs[j].dst);
178  return GNUNET_SYSERR;
179 }
const char * fname
Field name of the desired result.
Description of a DB result cell.
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
GNUNET_GenericReturnValue
Named constants for return values.
Definition: gnunet_common.h:83
bool is_nullable
True if NULL is allowed for a value in the database.
#define GNUNET_break(cond)
Use this for internal assertion violations that are not fatal (can be handled) but should not occur...
void * cls
Closure for conv and cleaner.
static void cleanup(void *cls)
Function scheduled as very last function, cleans up after us.
static int result
Global testing status.
size_t dst_size
Allowed size for the data, 0 for variable-size (in this case, the type of dst is a void ** and we nee...
bool * is_null
Points to a location where we should store "true" if the result found is NULL, and otherwise "false"...
GNUNET_PQ_ResultCleanup cleaner
Function to clean up result data, NULL if cleanup is not necessary.
#define GNUNET_log(kind,...)
void * dst
Destination for the data.
size_t * result_size
Where to store actual size of the result.
GNUNET_PQ_ResultConverter conv
What is the format of the result?
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_cleanup_result()

void GNUNET_PQ_cleanup_result ( struct GNUNET_PQ_ResultSpec rs)

Free all memory that was allocated in rs during GNUNET_PQ_extract_result().

Parameters
rsreult specification to clean up

Definition at line 117 of file pq.c.

References GNUNET_PQ_ResultSpec::cleaner, and GNUNET_PQ_ResultSpec::conv.

Referenced by extract_result_cb(), GNUNET_PQ_run_sql(), handle_results(), namecache_postgres_lookup_block(), parse_result_call_iterator(), postgres_plugin_del(), postgres_plugin_get_random(), process_keys(), and process_result().

118 {
119  for (unsigned int i = 0; NULL != rs[i].conv; i++)
120  if (NULL != rs[i].cleaner)
121  rs[i].cleaner (rs[i].cls,
122  rs[i].dst);
123 }
void * cls
Closure for conv and cleaner.
GNUNET_PQ_ResultCleanup cleaner
Function to clean up result data, NULL if cleanup is not necessary.
void * dst
Destination for the data.
GNUNET_PQ_ResultConverter conv
What is the format of the result?
Here is the caller graph for this function:

◆ GNUNET_PQ_eval_result()

enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_result ( struct GNUNET_PQ_Context db,
const char *  statement_name,
PGresult *  result 
)

Check the result's error code to see what happened.

Also logs errors.

Parameters
dbdatabase to execute the statement in
statement_namename of the statement that created result
resultresult to check
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus. Never returns positive values as this function does not look at the result set.
Deprecated:
(low level, let's see if we can do with just the high-level functions)

Also logs errors.

Parameters
dbdatabase to execute the statement with
statement_namename of the statement that created result
resultresult to check
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus. Never returns positive values as this function does not look at the result set.
Deprecated:
(low level, let's see if we can do with just the high-level functions)

Definition at line 59 of file pq_eval.c.

References GNUNET_PQ_Context::conn, GNUNET_break, GNUNET_DB_STATUS_HARD_ERROR, GNUNET_DB_STATUS_SOFT_ERROR, GNUNET_DB_STATUS_SUCCESS_NO_RESULTS, GNUNET_ERROR_TYPE_DEBUG, GNUNET_ERROR_TYPE_ERROR, GNUNET_ERROR_TYPE_INFO, GNUNET_log_from, GNUNET_PQ_reconnect(), PQ_DIAG_SQLSTATE_DEADLOCK, PQ_DIAG_SQLSTATE_SERIALIZATION_FAILURE, PQ_DIAG_SQLSTATE_UNIQUE_VIOLATION, and status.

Referenced by GNUNET_PQ_eval_prepared_multi_select(), GNUNET_PQ_eval_prepared_non_select(), and GNUNET_PQ_eval_prepared_singleton_select().

62 {
63  ExecStatusType est;
64 
65  if (NULL == result)
67  est = PQresultStatus (result);
68  if ((PGRES_COMMAND_OK != est) &&
69  (PGRES_TUPLES_OK != est))
70  {
71  const char *sqlstate;
72  ConnStatusType status;
73 
74  if (CONNECTION_OK != (status = PQstatus (db->conn)))
75  {
77  "pq",
78  "Database connection failed during query `%s': %d (reconnecting)\n",
79  statement_name,
80  status);
83  }
84 
85  sqlstate = PQresultErrorField (result,
86  PG_DIAG_SQLSTATE);
87  if (NULL == sqlstate)
88  {
89  /* very unexpected... */
90  GNUNET_break (0);
92  }
93  if ((0 == strcmp (sqlstate,
95  (0 == strcmp (sqlstate,
97  {
98  /* These two can be retried and have a fair chance of working
99  the next time */
101  "pq",
102  "Query `%s' failed with result: %s/%s/%s/%s/%s\n",
103  statement_name,
104  PQresultErrorField (result,
105  PG_DIAG_MESSAGE_PRIMARY),
106  PQresultErrorField (result,
107  PG_DIAG_MESSAGE_DETAIL),
108  PQresultErrorMessage (result),
109  PQresStatus (PQresultStatus (result)),
110  PQerrorMessage (db->conn));
112  }
113  if (0 == strcmp (sqlstate,
115  {
116  /* Likely no need to retry, INSERT of "same" data. */
118  "pq",
119  "Query `%s' failed with unique violation: %s/%s/%s/%s/%s\n",
120  statement_name,
121  PQresultErrorField (result,
122  PG_DIAG_MESSAGE_PRIMARY),
123  PQresultErrorField (result,
124  PG_DIAG_MESSAGE_DETAIL),
125  PQresultErrorMessage (result),
126  PQresStatus (PQresultStatus (result)),
127  PQerrorMessage (db->conn));
129  }
131  "pq",
132  "Query `%s' failed with result: %s/%s/%s/%s/%s\n",
133  statement_name,
134  PQresultErrorField (result,
135  PG_DIAG_MESSAGE_PRIMARY),
136  PQresultErrorField (result,
137  PG_DIAG_MESSAGE_DETAIL),
138  PQresultErrorMessage (result),
139  PQresStatus (PQresultStatus (result)),
140  PQerrorMessage (db->conn));
142  }
144 }
#define PQ_DIAG_SQLSTATE_SERIALIZATION_FAILURE
Error code returned by Postgres on serialization failure.
Definition: pq_eval.c:42
void GNUNET_PQ_reconnect(struct GNUNET_PQ_Context *db)
Reinitialize the database db.
Definition: pq_connect.c:295
A soft error occurred, retrying the transaction may succeed.
Definition: gnunet_db_lib.h:45
A hard error occurred, retrying will not help.
Definition: gnunet_db_lib.h:39
#define GNUNET_break(cond)
Use this for internal assertion violations that are not fatal (can be handled) but should not occur...
PGconn * conn
Actual connection.
Definition: pq.h:39
#define PQ_DIAG_SQLSTATE_DEADLOCK
Error code returned by Postgres for deadlock.
Definition: pq_eval.c:32
#define PQ_DIAG_SQLSTATE_UNIQUE_VIOLATION
Error code returned by Postgres for uniqueness violation.
Definition: pq_eval.c:37
uint16_t status
See PRISM_STATUS_*-constants.
static int result
Global testing status.
#define GNUNET_log_from(kind, comp,...)
The transaction succeeded, but yielded zero results.
Definition: gnunet_db_lib.h:53
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_eval_prepared_non_select()

enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_non_select ( struct GNUNET_PQ_Context db,
const char *  statement_name,
const struct GNUNET_PQ_QueryParam params 
)

Execute a named prepared statement that is NOT a SELECT statement in connection using the given params.

Returns the resulting session state.

Parameters
dbdatabase to execute the statement with
statement_namename of the statement
paramsparameters to give to the statement (GNUNET_PQ_query_param_end-terminated)
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus. If the statement was a DELETE or UPDATE statement, the number of affected rows is returned; if the statement was an INSERT statement, and no row was added due to a UNIQUE violation, we return zero; if INSERT was successful, we return one.

Returns the resulting session state.

Parameters
dbdatabase to execute the statement with
statement_namename of the statement
paramsparameters to give to the statement (GNUNET_PQ_query_param_end-terminated)
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus. If the statement was a DELETE or UPDATE statement, the number of affected rows is returned.; if the statement was an INSERT statement, and no row was added due to a UNIQUE violation, we return zero; if INSERT was successful, we return one.

Definition at line 164 of file pq_eval.c.

References GNUNET_DB_STATUS_SOFT_ERROR, GNUNET_DB_STATUS_SUCCESS_NO_RESULTS, GNUNET_PQ_eval_result(), GNUNET_PQ_exec_prepared(), and result.

Referenced by delete_old_block(), namecache_postgres_cache_block(), namecache_postgres_expire_blocks(), namestore_postgres_store_records(), postgres_plugin_del(), postgres_plugin_put(), postgres_plugin_remove_key(), process_result(), and repl_proc().

167 {
168  PGresult *result;
169  enum GNUNET_DB_QueryStatus qs;
170 
171  result = GNUNET_PQ_exec_prepared (db,
172  statement_name,
173  params);
174  if (NULL == result)
176  qs = GNUNET_PQ_eval_result (db,
177  statement_name,
178  result);
180  {
181  const char *tuples;
182 
183  /* What an awful API, this function really does return a string */
184  tuples = PQcmdTuples (result);
185  if (NULL != tuples)
186  qs = strtol (tuples, NULL, 10);
187  }
188  PQclear (result);
189  return qs;
190 }
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_result(struct GNUNET_PQ_Context *db, const char *statement_name, PGresult *result)
Check the result&#39;s error code to see what happened.
Definition: pq_eval.c:59
PGresult * GNUNET_PQ_exec_prepared(struct GNUNET_PQ_Context *db, const char *name, const struct GNUNET_PQ_QueryParam *params)
Execute a prepared statement.
Definition: pq.c:32
A soft error occurred, retrying the transaction may succeed.
Definition: gnunet_db_lib.h:45
static int result
Global testing status.
GNUNET_DB_QueryStatus
Status code returned from functions running database commands.
Definition: gnunet_db_lib.h:34
The transaction succeeded, but yielded zero results.
Definition: gnunet_db_lib.h:53
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_eval_prepared_multi_select()

enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_multi_select ( struct GNUNET_PQ_Context db,
const char *  statement_name,
const struct GNUNET_PQ_QueryParam params,
GNUNET_PQ_PostgresResultHandler  rh,
void *  rh_cls 
)

Execute a named prepared statement that is a SELECT statement which may return multiple results in connection using the given params.

Call rh with the results. Returns the query status including the number of results given to rh (possibly zero). rh will not have been called if the return value is negative.

Parameters
dbdatabase to execute the statement with
statement_namename of the statement
paramsparameters to give to the statement (GNUNET_PQ_query_param_end-terminated)
rhfunction to call with the result set, NULL to ignore
rh_clsclosure to pass to rh
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus.

Definition at line 209 of file pq_eval.c.

References GNUNET_DB_STATUS_SOFT_ERROR, GNUNET_PQ_eval_result(), GNUNET_PQ_exec_prepared(), result, and ret.

Referenced by namestore_postgres_iterate_records(), namestore_postgres_lookup_records(), namestore_postgres_zone_to_name(), postgres_plugin_get(), postgres_plugin_get_closest(), postgres_plugin_get_expiration(), postgres_plugin_get_key(), postgres_plugin_get_keys(), postgres_plugin_get_replication(), and postgres_plugin_get_zero_anonymity().

214 {
215  PGresult *result;
216  enum GNUNET_DB_QueryStatus qs;
217  unsigned int ret;
218 
219  result = GNUNET_PQ_exec_prepared (db,
220  statement_name,
221  params);
222  if (NULL == result)
224  qs = GNUNET_PQ_eval_result (db,
225  statement_name,
226  result);
227  if (qs < 0)
228  {
229  PQclear (result);
230  return qs;
231  }
232  ret = PQntuples (result);
233  if (NULL != rh)
234  rh (rh_cls,
235  result,
236  ret);
237  PQclear (result);
238  return ret;
239 }
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_result(struct GNUNET_PQ_Context *db, const char *statement_name, PGresult *result)
Check the result&#39;s error code to see what happened.
Definition: pq_eval.c:59
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
PGresult * GNUNET_PQ_exec_prepared(struct GNUNET_PQ_Context *db, const char *name, const struct GNUNET_PQ_QueryParam *params)
Execute a prepared statement.
Definition: pq.c:32
A soft error occurred, retrying the transaction may succeed.
Definition: gnunet_db_lib.h:45
static int result
Global testing status.
GNUNET_DB_QueryStatus
Status code returned from functions running database commands.
Definition: gnunet_db_lib.h:34
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_eval_prepared_singleton_select()

enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_singleton_select ( struct GNUNET_PQ_Context db,
const char *  statement_name,
const struct GNUNET_PQ_QueryParam params,
struct GNUNET_PQ_ResultSpec rs 
)

Execute a named prepared statement that is a SELECT statement which must return a single result in connection using the given params.

Stores the result (if any) in rs, which the caller must then clean up using GNUNET_PQ_cleanup_result() if the return value was GNUNET_DB_STATUS_SUCCESS_ONE_RESULT. Returns the resulting session status.

Parameters
dbdatabase to execute the statement with
statement_namename of the statement
paramsparameters to give to the statement (GNUNET_PQ_query_param_end-terminated)
[in,out]rsresult specification to use for storing the result of the query
Returns
status code from the result, mapping PQ status codes to enum GNUNET_DB_QueryStatus.

Definition at line 258 of file pq_eval.c.

References GNUNET_break, GNUNET_DB_STATUS_HARD_ERROR, GNUNET_DB_STATUS_SOFT_ERROR, GNUNET_DB_STATUS_SUCCESS_NO_RESULTS, GNUNET_DB_STATUS_SUCCESS_ONE_RESULT, GNUNET_OK, GNUNET_PQ_eval_result(), GNUNET_PQ_exec_prepared(), GNUNET_PQ_extract_result(), and result.

Referenced by GNUNET_PQ_run_sql(), namecache_postgres_lookup_block(), postgres_plugin_del(), postgres_plugin_estimate_size(), and postgres_plugin_get_random().

263 {
264  PGresult *result;
265  enum GNUNET_DB_QueryStatus qs;
266  int ntuples;
267 
268  result = GNUNET_PQ_exec_prepared (db,
269  statement_name,
270  params);
271  if (NULL == result)
273  qs = GNUNET_PQ_eval_result (db,
274  statement_name,
275  result);
276  if (qs < 0)
277  {
278  PQclear (result);
279  return qs;
280  }
281  ntuples = PQntuples (result);
282  if (0 == ntuples)
283  {
284  PQclear (result);
286  }
287  if (1 != ntuples)
288  {
289  /* more than one result, but there must be at most one */
290  GNUNET_break (0);
291  PQclear (result);
293  }
294  if (GNUNET_OK !=
295  GNUNET_PQ_extract_result (result,
296  rs,
297  0))
298  {
299  PQclear (result);
301  }
302  PQclear (result);
304 }
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_result(struct GNUNET_PQ_Context *db, const char *statement_name, PGresult *result)
Check the result&#39;s error code to see what happened.
Definition: pq_eval.c:59
PGresult * GNUNET_PQ_exec_prepared(struct GNUNET_PQ_Context *db, const char *name, const struct GNUNET_PQ_QueryParam *params)
Execute a prepared statement.
Definition: pq.c:32
A soft error occurred, retrying the transaction may succeed.
Definition: gnunet_db_lib.h:45
A hard error occurred, retrying will not help.
Definition: gnunet_db_lib.h:39
#define GNUNET_break(cond)
Use this for internal assertion violations that are not fatal (can be handled) but should not occur...
static int result
Global testing status.
enum GNUNET_GenericReturnValue GNUNET_PQ_extract_result(PGresult *result, struct GNUNET_PQ_ResultSpec *rs, int row)
Extract results from a query result according to the given specification.
Definition: pq.c:127
The transaction succeeded, and yielded one result.
Definition: gnunet_db_lib.h:58
GNUNET_DB_QueryStatus
Status code returned from functions running database commands.
Definition: gnunet_db_lib.h:34
The transaction succeeded, but yielded zero results.
Definition: gnunet_db_lib.h:53
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_make_prepare()

struct GNUNET_PQ_PreparedStatement GNUNET_PQ_make_prepare ( const char *  name,
const char *  sql,
unsigned int  num_args 
)

Create a struct GNUNET_PQ_PreparedStatement.

Parameters
namename of the statement
sqlactual SQL statement
num_argsnumber of arguments in the statement
Returns
initialized struct

Definition at line 38 of file pq_prepare.c.

References name, GNUNET_PQ_PreparedStatement::name, and GNUNET_PQ_PreparedStatement::sql.

Referenced by database_setup(), and init_connection().

41 {
42  struct GNUNET_PQ_PreparedStatement ps = {
43  .name = name,
44  .sql = sql,
45  .num_arguments = num_args
46  };
47 
48  return ps;
49 }
Information needed to prepare a list of SQL statements using GNUNET_PQ_prepare_statements().
const char * name
Name of the statement.
const char * sql
Actual SQL statement.
const char * name
Here is the caller graph for this function:

◆ GNUNET_PQ_prepare_statements()

int GNUNET_PQ_prepare_statements ( struct GNUNET_PQ_Context db,
const struct GNUNET_PQ_PreparedStatement ps 
)

Request creation of prepared statements ps from Postgres.

Parameters
dbdatabase to prepare the statements for
psGNUNET_PQ_PREPARED_STATEMENT_END-terminated array of prepared statements.
Returns
GNUNET_OK on success, GNUNET_SYSERR on error

Definition at line 62 of file pq_prepare.c.

References _, GNUNET_PQ_Context::conn, GNUNET_ERROR_TYPE_BULK, GNUNET_ERROR_TYPE_DEBUG, GNUNET_ERROR_TYPE_ERROR, GNUNET_free, GNUNET_log_from, GNUNET_new_array, GNUNET_OK, GNUNET_SYSERR, GNUNET_PQ_PreparedStatement::name, GNUNET_PQ_PreparedStatement::num_arguments, GNUNET_PQ_Context::ps, ret, and GNUNET_PQ_PreparedStatement::sql.

Referenced by GNUNET_PQ_reconnect().

64 {
65  if (db->ps != ps)
66  {
67  /* add 'ps' to list db->ps of prepared statements to run on reconnect! */
68  unsigned int olen = 0; /* length of existing 'db->ps' array */
69  unsigned int nlen = 0; /* length of 'ps' array */
70  struct GNUNET_PQ_PreparedStatement *rps; /* combined array */
71 
72  if (NULL != db->ps)
73  while (NULL != db->ps[olen].name)
74  olen++;
75  while (NULL != ps[nlen].name)
76  nlen++;
77  rps = GNUNET_new_array (olen + nlen + 1,
79  if (NULL != db->ps)
80  memcpy (rps,
81  db->ps,
82  olen * sizeof (struct GNUNET_PQ_PreparedStatement));
83  memcpy (&rps[olen],
84  ps,
85  nlen * sizeof (struct GNUNET_PQ_PreparedStatement));
86  GNUNET_free (db->ps);
87  db->ps = rps;
88  }
89 
90  /* actually prepare statements */
91  for (unsigned int i = 0; NULL != ps[i].name; i++)
92  {
93  PGresult *ret;
94 
96  "pq",
97  "Preparing SQL statement `%s' as `%s'\n",
98  ps[i].sql,
99  ps[i].name);
100  ret = PQprepare (db->conn,
101  ps[i].name,
102  ps[i].sql,
103  ps[i].num_arguments,
104  NULL);
105  if (PGRES_COMMAND_OK != PQresultStatus (ret))
106  {
108  "pq",
109  _ ("PQprepare (`%s' as `%s') failed with error: %s\n"),
110  ps[i].sql,
111  ps[i].name,
112  PQerrorMessage (db->conn));
113  PQclear (ret);
114  return GNUNET_SYSERR;
115  }
116  PQclear (ret);
117  }
118  return GNUNET_OK;
119 }
struct GNUNET_PQ_PreparedStatement * ps
Prepared statements.
Definition: pq.h:49
Information needed to prepare a list of SQL statements using GNUNET_PQ_prepare_statements().
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
const char * name
Name of the statement.
#define _(String)
GNU gettext support macro.
Definition: platform.h:178
PGconn * conn
Actual connection.
Definition: pq.h:39
#define GNUNET_new_array(n, type)
Allocate a size n array with structs or unions of the given type.
const char * sql
Actual SQL statement.
const char * name
unsigned int num_arguments
Number of arguments included in sql.
#define GNUNET_log_from(kind, comp,...)
#define GNUNET_free(ptr)
Wrapper around free.
Here is the caller graph for this function:

◆ GNUNET_PQ_make_execute()

struct GNUNET_PQ_ExecuteStatement GNUNET_PQ_make_execute ( const char *  sql)

Create a struct GNUNET_PQ_ExecuteStatement where errors are fatal.

Parameters
sqlactual SQL statement
Returns
initialized struct

Definition at line 36 of file pq_exec.c.

References GNUNET_NO, and GNUNET_PQ_ExecuteStatement::sql.

Referenced by database_setup(), init_connection(), and postgres_plugin_drop().

37 {
38  struct GNUNET_PQ_ExecuteStatement es = {
39  .sql = sql,
40  .ignore_errors = GNUNET_NO
41  };
42 
43  return es;
44 }
Information needed to run a list of SQL statements using GNUNET_PQ_exec_statements().
const char * sql
Actual SQL statement.
Here is the caller graph for this function:

◆ GNUNET_PQ_make_try_execute()

struct GNUNET_PQ_ExecuteStatement GNUNET_PQ_make_try_execute ( const char *  sql)

Create a struct GNUNET_PQ_ExecuteStatement where errors should be tolerated.

Parameters
sqlactual SQL statement
Returns
initialized struct

Definition at line 55 of file pq_exec.c.

References GNUNET_YES, and GNUNET_PQ_ExecuteStatement::sql.

Referenced by database_setup(), and init_connection().

56 {
57  struct GNUNET_PQ_ExecuteStatement es = {
58  .sql = sql,
59  .ignore_errors = GNUNET_YES
60  };
61 
62  return es;
63 }
Information needed to run a list of SQL statements using GNUNET_PQ_exec_statements().
const char * sql
Actual SQL statement.
Here is the caller graph for this function:

◆ GNUNET_PQ_exec_statements()

int GNUNET_PQ_exec_statements ( struct GNUNET_PQ_Context db,
const struct GNUNET_PQ_ExecuteStatement es 
)

Request execution of an array of statements es from Postgres.

Parameters
pqdatabase to execute the statements in
esGNUNET_PQ_PREPARED_STATEMENT_END-terminated array of prepared statements.
Returns
GNUNET_OK on success (modulo statements where errors can be ignored) GNUNET_SYSERR on error
Parameters
dbdatabase to execute the statements with
esGNUNET_PQ_PREPARED_STATEMENT_END-terminated array of prepared statements.
Returns
GNUNET_OK on success (modulo statements where errors can be ignored) GNUNET_SYSERR on error

Definition at line 76 of file pq_exec.c.

References GNUNET_PQ_Context::conn, GNUNET_ERROR_TYPE_DEBUG, GNUNET_ERROR_TYPE_ERROR, GNUNET_log, GNUNET_log_from, GNUNET_NO, GNUNET_OK, GNUNET_SYSERR, GNUNET_PQ_ExecuteStatement::ignore_errors, result, and GNUNET_PQ_ExecuteStatement::sql.

Referenced by GNUNET_PQ_reconnect(), and postgres_plugin_drop().

78 {
79  for (unsigned int i = 0; NULL != es[i].sql; i++)
80  {
81  PGresult *result;
82 
84  "Running statement `%s' on %p\n",
85  es[i].sql,
86  db);
87  result = PQexec (db->conn,
88  es[i].sql);
89  if ((GNUNET_NO == es[i].ignore_errors) &&
90  (PGRES_COMMAND_OK != PQresultStatus (result)))
91  {
93  "pq",
94  "Failed to execute `%s': %s/%s/%s/%s/%s",
95  es[i].sql,
96  PQresultErrorField (result,
97  PG_DIAG_MESSAGE_PRIMARY),
98  PQresultErrorField (result,
99  PG_DIAG_MESSAGE_DETAIL),
100  PQresultErrorMessage (result),
101  PQresStatus (PQresultStatus (result)),
102  PQerrorMessage (db->conn));
103  PQclear (result);
104  return GNUNET_SYSERR;
105  }
106  PQclear (result);
107  }
108  return GNUNET_OK;
109 }
int ignore_errors
Should we ignore errors?
PGconn * conn
Actual connection.
Definition: pq.h:39
static int result
Global testing status.
#define GNUNET_log(kind,...)
#define GNUNET_log_from(kind, comp,...)
const char * sql
Actual SQL statement.
Here is the caller graph for this function:

◆ GNUNET_PQ_connect()

struct GNUNET_PQ_Context* GNUNET_PQ_connect ( const char *  config_str,
const char *  load_path,
const struct GNUNET_PQ_ExecuteStatement es,
const struct GNUNET_PQ_PreparedStatement ps 
)

Create a connection to the Postgres database using config_str for the configuration.

Initialize logging via GNUnet's log routines and disable Postgres's logger. Also ensures that the statements in load_path and es are executed whenever we (re)connect to the database, and that the prepared statements in ps are "ready". If statements in fail that were created with GNUNET_PQ_make_execute(), then the entire operation fails.

In load_path, a list of "$XXXX.sql" files is expected where $XXXX must be a sequence of contiguous integer values starting at 0000. These files are then loaded in sequence using "psql $config_str" before running statements from es. The directory is inspected again on reconnect.

Parameters
config_strconfiguration to use
load_pathpath to directory with SQL transactions to run, can be NULL
esGNUNET_PQ_PREPARED_STATEMENT_END-terminated array of statements to execute upon EACH connection, can be NULL
psarray of prepared statements to prepare, can be NULL
Returns
NULL on error

Definition at line 68 of file pq_connect.c.

References GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::config_str, GNUNET_PQ_Context::conn, db, GNUNET_PQ_Context::es, GNUNET_assert, GNUNET_CONTAINER_multishortmap_create(), GNUNET_free, GNUNET_new, GNUNET_new_array, GNUNET_PQ_reconnect(), GNUNET_strdup, GNUNET_YES, GNUNET_PQ_Context::load_path, name, GNUNET_PQ_Context::notify_lock, and GNUNET_PQ_Context::ps.

Referenced by GNUNET_PQ_connect_with_cfg().

72 {
73  struct GNUNET_PQ_Context *db;
74  unsigned int elen = 0;
75  unsigned int plen = 0;
76 
77  if (NULL != es)
78  while (NULL != es[elen].sql)
79  elen++;
80  if (NULL != ps)
81  while (NULL != ps[plen].name)
82  plen++;
83 
84  db = GNUNET_new (struct GNUNET_PQ_Context);
86  if (NULL != load_path)
88  if (0 != elen)
89  {
90  db->es = GNUNET_new_array (elen + 1,
92  memcpy (db->es,
93  es,
94  elen * sizeof (struct GNUNET_PQ_ExecuteStatement));
95  }
96  if (0 != plen)
97  {
98  db->ps = GNUNET_new_array (plen + 1,
100  memcpy (db->ps,
101  ps,
102  plen * sizeof (struct GNUNET_PQ_PreparedStatement));
103  }
105  GNUNET_YES);
106  GNUNET_assert (0 ==
107  pthread_mutex_init (&db->notify_lock,
108  NULL));
109  GNUNET_PQ_reconnect (db);
110  if (NULL == db->conn)
111  {
112  GNUNET_free (db->load_path);
113  GNUNET_free (db->config_str);
114  GNUNET_free (db);
115  return NULL;
116  }
117  return db;
118 }
void GNUNET_PQ_reconnect(struct GNUNET_PQ_Context *db)
Reinitialize the database db.
Definition: pq_connect.c:295
struct GNUNET_PQ_PreparedStatement * ps
Prepared statements.
Definition: pq.h:49
char * load_path
Path to load SQL files from.
Definition: pq.h:59
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
Information needed to run a list of SQL statements using GNUNET_PQ_exec_statements().
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
Information needed to prepare a list of SQL statements using GNUNET_PQ_prepare_statements().
struct GNUNET_PQ_ExecuteStatement * es
Statements to execute upon connection.
Definition: pq.h:44
#define GNUNET_new(type)
Allocate a struct or union of the given type.
#define GNUNET_strdup(a)
Wrapper around GNUNET_xstrdup_.
PGconn * conn
Actual connection.
Definition: pq.h:39
char * config_str
Configuration to use to connect to the DB.
Definition: pq.h:54
#define GNUNET_new_array(n, type)
Allocate a size n array with structs or unions of the given type.
struct GNUNET_CONTAINER_MultiShortmap * GNUNET_CONTAINER_multishortmap_create(unsigned int len, int do_not_copy_keys)
Create a multi peer map (hash map for public keys of peers).
static struct GNUNET_FS_DirectoryBuilder * db
Definition: gnunet-search.c:41
const char * name
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
Handle to Postgres database.
Definition: pq.h:34
#define GNUNET_free(ptr)
Wrapper around free.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_connect_with_cfg()

struct GNUNET_PQ_Context* GNUNET_PQ_connect_with_cfg ( const struct GNUNET_CONFIGURATION_Handle cfg,
const char *  section,
const char *  load_path_suffix,
const struct GNUNET_PQ_ExecuteStatement es,
const struct GNUNET_PQ_PreparedStatement ps 
)

Connect to a postgres database using the configuration option "CONFIG" in section.

Also ensures that the statements in es are executed whenever we (re)connect to the database, and that the prepared statements in ps are "ready".

The caller does not have to ensure that es and ps remain allocated and initialized in memory until GNUNET_PQ_disconnect() is called, as a copy will be made.

Parameters
cfgconfiguration
sectionconfiguration section to use to get Postgres configuration options
load_path_suffixsuffix to append to the SQL_DIR in the configuration
esGNUNET_PQ_PREPARED_STATEMENT_END-terminated array of statements to execute upon EACH connection, can be NULL
psarray of prepared statements to prepare, can be NULL
Returns
the postgres handle, NULL on error

Definition at line 428 of file pq_connect.c.

References db, GNUNET_asprintf(), GNUNET_CONFIGURATION_get_value_filename(), GNUNET_CONFIGURATION_get_value_string(), GNUNET_free, GNUNET_OK, GNUNET_PQ_connect(), and GNUNET_PQ_Context::load_path.

Referenced by database_setup(), and init_connection().

433 {
434  struct GNUNET_PQ_Context *db;
435  char *conninfo;
436  char *load_path;
437  char *sp;
438 
439  if (GNUNET_OK !=
441  section,
442  "CONFIG",
443  &conninfo))
444  conninfo = NULL;
445  load_path = NULL;
446  sp = NULL;
447  if ( (NULL != load_path_suffix) &&
448  (GNUNET_OK ==
450  section,
451  "SQL_DIR",
452  &sp)) )
453  GNUNET_asprintf (&load_path,
454  "%s%s",
455  sp,
456  load_path_suffix);
457  db = GNUNET_PQ_connect (conninfo == NULL ? "" : conninfo,
458  load_path,
459  es,
460  ps);
461  GNUNET_free (load_path);
462  GNUNET_free (sp);
463  GNUNET_free (conninfo);
464  return db;
465 }
char * load_path
Path to load SQL files from.
Definition: pq.h:59
enum GNUNET_GenericReturnValue GNUNET_CONFIGURATION_get_value_filename(const struct GNUNET_CONFIGURATION_Handle *cfg, const char *section, const char *option, char **value)
Get a configuration value that should be the name of a file or directory.
enum GNUNET_GenericReturnValue GNUNET_CONFIGURATION_get_value_string(const struct GNUNET_CONFIGURATION_Handle *cfg, const char *section, const char *option, char **value)
Get a configuration value that should be a string.
static char * section
Name of the section.
Definition: gnunet-config.c:33
struct GNUNET_PQ_Context * GNUNET_PQ_connect(const char *config_str, const char *load_path, const struct GNUNET_PQ_ExecuteStatement *es, const struct GNUNET_PQ_PreparedStatement *ps)
Create a connection to the Postgres database using config_str for the configuration.
Definition: pq_connect.c:68
int int GNUNET_asprintf(char **buf, const char *format,...) __attribute__((format(printf
Like asprintf, just portable.
static struct GNUNET_FS_DirectoryBuilder * db
Definition: gnunet-search.c:41
Handle to Postgres database.
Definition: pq.h:34
#define GNUNET_free(ptr)
Wrapper around free.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_reconnect_if_down()

void GNUNET_PQ_reconnect_if_down ( struct GNUNET_PQ_Context db)

Reinitialize the database db if the connection is down.

Parameters
dbdatabase connection to reinitialize

Definition at line 283 of file pq_connect.c.

References GNUNET_PQ_Context::conn, and GNUNET_PQ_reconnect().

284 {
285  if (1 ==
286  PQconsumeInput (db->conn))
287  return;
288  if (CONNECTION_BAD != PQstatus (db->conn))
289  return;
290  GNUNET_PQ_reconnect (db);
291 }
void GNUNET_PQ_reconnect(struct GNUNET_PQ_Context *db)
Reinitialize the database db.
Definition: pq_connect.c:295
PGconn * conn
Actual connection.
Definition: pq.h:39
Here is the call graph for this function:

◆ GNUNET_PQ_reconnect()

void GNUNET_PQ_reconnect ( struct GNUNET_PQ_Context db)

Reinitialize the database db.

Parameters
dbdatabase connection to reinitialize

Definition at line 295 of file pq_connect.c.

References apply_patch(), GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::config_str, GNUNET_PQ_Context::conn, GNUNET_PQ_Context::es, GNUNET_CONTAINER_multishortmap_size(), GNUNET_ERROR_TYPE_ERROR, GNUNET_ERROR_TYPE_INFO, GNUNET_ERROR_TYPE_WARNING, GNUNET_log, GNUNET_log_from, GNUNET_NO, GNUNET_OK, GNUNET_PQ_event_reconnect_(), GNUNET_PQ_exec_statements(), GNUNET_PQ_prepare_statements(), GNUNET_PQ_run_sql(), GNUNET_SYSERR, GNUNET_PQ_Context::load_path, pq_notice_processor_cb(), pq_notice_receiver_cb(), GNUNET_PQ_Context::ps, res, ret, GNUNET_PQ_Context::sc, and GNUNET_PQ_Context::sc_cls.

Referenced by GNUNET_PQ_connect(), GNUNET_PQ_eval_result(), GNUNET_PQ_exec_prepared(), and GNUNET_PQ_reconnect_if_down().

296 {
297  if (NULL != db->sc)
298  db->sc (db->sc_cls,
299  -1);
300  if (NULL != db->conn)
301  PQfinish (db->conn);
302  db->conn = PQconnectdb (db->config_str);
303  if ( (NULL == db->conn) ||
304  (CONNECTION_OK != PQstatus (db->conn)) )
305  {
307  "pq",
308  "Database connection to '%s' failed: %s\n",
309  db->config_str,
310  (NULL != db->conn) ?
311  PQerrorMessage (db->conn)
312  : "PQconnectdb returned NULL");
313  if (NULL != db->conn)
314  {
315  PQfinish (db->conn);
316  db->conn = NULL;
317  }
318  return;
319  }
320  PQsetNoticeReceiver (db->conn,
322  db);
323  PQsetNoticeProcessor (db->conn,
325  db);
326  if (NULL != db->load_path)
327  {
328  PGresult *res;
329 
330  res = PQprepare (db->conn,
331  "gnunet_pq_check_patch",
332  "SELECT"
333  " applied_by"
334  " FROM _v.patches"
335  " WHERE patch_name = $1"
336  " LIMIT 1",
337  1,
338  NULL);
339  if (PGRES_COMMAND_OK != PQresultStatus (res))
340  {
341  int ret;
342 
343  PQclear (res);
345  "Failed to prepare statement to check patch level. Likely versioning schema does not exist yet, loading patch level 0000!\n");
346  ret = apply_patch (db,
347  db->load_path,
348  0);
349  if (GNUNET_NO == ret)
350  {
352  "Failed to find SQL file to load database versioning logic\n");
353  PQfinish (db->conn);
354  db->conn = NULL;
355  return;
356  }
357  if (GNUNET_SYSERR == ret)
358  {
360  "Failed to run SQL logic to setup database versioning logic\n");
361  PQfinish (db->conn);
362  db->conn = NULL;
363  return;
364  }
365  /* try again to prepare our statement! */
366  res = PQprepare (db->conn,
367  "gnunet_pq_check_patch",
368  "SELECT"
369  " applied_by"
370  " FROM _v.patches"
371  " WHERE patch_name = $1"
372  " LIMIT 1",
373  1,
374  NULL);
375  if (PGRES_COMMAND_OK != PQresultStatus (res))
376  {
378  "Failed to run SQL logic to setup database versioning logic: %s/%s\n",
379  PQresultErrorMessage (res),
380  PQerrorMessage (db->conn));
381  PQclear (res);
382  PQfinish (db->conn);
383  db->conn = NULL;
384  return;
385  }
386  }
387  PQclear (res);
388 
389  if (GNUNET_SYSERR ==
390  GNUNET_PQ_run_sql (db,
391  db->load_path))
392  {
394  "Failed to load SQL statements from `%s*'\n",
395  db->load_path);
396  PQfinish (db->conn);
397  db->conn = NULL;
398  return;
399  }
400  }
401  if ( (NULL != db->es) &&
402  (GNUNET_OK !=
404  db->es)) )
405  {
406  PQfinish (db->conn);
407  db->conn = NULL;
408  return;
409  }
410  if ( (NULL != db->ps) &&
411  (GNUNET_OK !=
413  db->ps)) )
414  {
415  PQfinish (db->conn);
416  db->conn = NULL;
417  return;
418  }
420  if ( (NULL != db->sc) &&
422  db->sc (db->sc_cls,
423  PQsocket (db->conn));
424 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
void GNUNET_PQ_event_reconnect_(struct GNUNET_PQ_Context *db)
Internal API.
Definition: pq_event.c:392
struct GNUNET_PQ_PreparedStatement * ps
Prepared statements.
Definition: pq.h:49
unsigned int GNUNET_CONTAINER_multishortmap_size(const struct GNUNET_CONTAINER_MultiShortmap *map)
Get the number of key-value pairs in the map.
char * load_path
Path to load SQL files from.
Definition: pq.h:59
struct GNUNET_PQ_ExecuteStatement * es
Statements to execute upon connection.
Definition: pq.h:44
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
int GNUNET_PQ_prepare_statements(struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_PreparedStatement *ps)
Request creation of prepared statements ps from Postgres.
Definition: pq_prepare.c:62
PGconn * conn
Actual connection.
Definition: pq.h:39
int GNUNET_PQ_exec_statements(struct GNUNET_PQ_Context *db, const struct GNUNET_PQ_ExecuteStatement *es)
Request execution of an array of statements es from Postgres.
Definition: pq_exec.c:76
char * config_str
Configuration to use to connect to the DB.
Definition: pq.h:54
void * sc_cls
Closure for sc.
Definition: pq.h:69
static int res
static enum GNUNET_GenericReturnValue apply_patch(struct GNUNET_PQ_Context *db, const char *load_path, unsigned int i)
Apply patch number from path load_path.
Definition: pq_connect.c:130
enum GNUNET_GenericReturnValue GNUNET_PQ_run_sql(struct GNUNET_PQ_Context *db, const char *load_path)
Within the db context, run all the SQL files from the load_path from 0000-9999.sql (as long as the fi...
Definition: pq_connect.c:188
#define GNUNET_log(kind,...)
static void pq_notice_receiver_cb(void *arg, const PGresult *res)
Function called by libpq whenever it wants to log something.
Definition: pq_connect.c:39
static void pq_notice_processor_cb(void *arg, const char *message)
Function called by libpq whenever it wants to log something.
Definition: pq_connect.c:56
#define GNUNET_log_from(kind, comp,...)
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_event_set_socket_callback()

void GNUNET_PQ_event_set_socket_callback ( struct GNUNET_PQ_Context db,
GNUNET_PQ_SocketCallback  sc,
void *  sc_cls 
)

Obtain the file descriptor to poll on for notifications.

Useful if the GNUnet scheduler is NOT to be used for such notifications.

Parameters
dbdatabase handle
scfunction to call with the socket
sc_clsclosure for sc

Definition at line 168 of file pq_event.c.

References GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::conn, GNUNET_assert, GNUNET_CONTAINER_multishortmap_size(), GNUNET_PQ_Context::notify_lock, sc, GNUNET_PQ_Context::sc, and GNUNET_PQ_Context::sc_cls.

171 {
172  int fd;
173 
174  db->sc = sc;
175  db->sc_cls = sc_cls;
176  if (NULL == sc)
177  return;
178  GNUNET_assert (0 ==
179  pthread_mutex_lock (&db->notify_lock));
180  fd = PQsocket (db->conn);
181  if ( (-1 != fd) &&
183  sc (sc_cls,
184  fd);
185  GNUNET_assert (0 ==
186  pthread_mutex_unlock (&db->notify_lock));
187 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
unsigned int GNUNET_CONTAINER_multishortmap_size(const struct GNUNET_CONTAINER_MultiShortmap *map)
Get the number of key-value pairs in the map.
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
PGconn * conn
Actual connection.
Definition: pq.h:39
void * sc_cls
Closure for sc.
Definition: pq.h:69
static struct GNUNET_FS_SearchContext * sc
Definition: gnunet-search.c:37
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
Here is the call graph for this function:

◆ GNUNET_PQ_event_do_poll()

void GNUNET_PQ_event_do_poll ( struct GNUNET_PQ_Context db)

Poll for database events now.

Used if the event FD is ready and the application wants to trigger applicable events. Useful if the GNUnet scheduler is NOT to be used for such notifications.

Parameters
dbdatabase handle

Definition at line 191 of file pq_event.c.

References GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::conn, do_notify(), NotifyContext::extra, NotifyContext::extra_size, GNUNET_assert, GNUNET_CONTAINER_multishortmap_iterate(), GNUNET_ERROR_TYPE_WARNING, GNUNET_free, GNUNET_log, GNUNET_OK, GNUNET_STRINGS_string_to_data(), GNUNET_STRINGS_string_to_data_alloc(), GNUNET_PQ_Context::notify_lock, and scheduler_fd_cb().

Referenced by do_scheduler_notify().

192 {
193  PGnotify *n;
194 
195  GNUNET_assert (0 ==
196  pthread_mutex_lock (&db->notify_lock));
197  while (NULL != (n = PQnotifies (db->conn)))
198  {
199  struct GNUNET_ShortHashCode sh;
200  struct NotifyContext ctx = {
201  .extra = NULL
202  };
203 
204  if (GNUNET_OK !=
205  GNUNET_STRINGS_string_to_data (n->relname,
206  strlen (n->relname),
207  &sh,
208  sizeof (sh)))
209  {
211  "Ignoring notification for unsupported channel identifier `%s'\n",
212  n->relname);
213  continue;
214  }
215  if ( (NULL != n->extra) &&
216  (GNUNET_OK !=
218  strlen (n->extra),
219  &ctx.extra,
220  &ctx.extra_size)))
221  {
223  "Ignoring notification for unsupported extra data `%s' on channel `%s'\n",
224  n->extra,
225  n->relname);
226  continue;
227  }
229  &do_notify,
230  &ctx);
231  GNUNET_free (ctx.extra);
232  }
233  GNUNET_assert (0 ==
234  pthread_mutex_unlock (&db->notify_lock));
235 }
static int do_notify(void *cls, const struct GNUNET_ShortHashCode *sh, void *value)
Function called on every event handler that needs to be triggered.
Definition: pq_event.c:153
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
Closure for do_notify().
Definition: pq_event.c:129
static struct GNUNET_DNSSTUB_Context * ctx
Context for DNS resolution.
A 256-bit hashcode.
PGconn * conn
Actual connection.
Definition: pq.h:39
size_t extra_size
Number of bytes in extra.
Definition: pq_event.c:139
int GNUNET_CONTAINER_multishortmap_iterate(struct GNUNET_CONTAINER_MultiShortmap *map, GNUNET_CONTAINER_ShortmapIterator it, void *it_cls)
Iterate over all entries in the map.
static struct SolverHandle * sh
enum GNUNET_GenericReturnValue GNUNET_STRINGS_string_to_data(const char *enc, size_t enclen, void *out, size_t out_size)
Convert CrockfordBase32 encoding back to data.
Definition: strings.c:775
void * extra
Extra argument of the notification, or NULL.
Definition: pq_event.c:134
enum GNUNET_GenericReturnValue GNUNET_STRINGS_string_to_data_alloc(const char *enc, size_t enclen, void **out, size_t *out_size)
Convert CrockfordBase32 encoding back to data.
Definition: strings.c:841
#define GNUNET_log(kind,...)
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
#define GNUNET_free(ptr)
Wrapper around free.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_event_scheduler_start()

void GNUNET_PQ_event_scheduler_start ( struct GNUNET_PQ_Context db)

Run poll event loop using the GNUnet scheduler.

Parameters
dbdatabase handle

Definition at line 305 of file pq_event.c.

References GNUNET_PQ_Context::conn, GNUNET_PQ_EventHandler::db, GNUNET_assert, GNUNET_PQ_Context::sc, GNUNET_PQ_Context::sc_cls, scheduler_fd_cb(), and GNUNET_PQ_Context::scheduler_on.

306 {
307  int fd;
308 
309  GNUNET_assert (! db->scheduler_on);
310  GNUNET_assert (NULL == db->sc);
311  db->scheduler_on = true;
312  db->sc = &scheduler_fd_cb;
313  db->sc_cls = db;
314  fd = PQsocket (db->conn);
315  scheduler_fd_cb (db,
316  fd);
317 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
PGconn * conn
Actual connection.
Definition: pq.h:39
void * sc_cls
Closure for sc.
Definition: pq.h:69
bool scheduler_on
Is scheduling via the GNUnet scheduler desired?
Definition: pq.h:94
static struct GNUNET_FS_DirectoryBuilder * db
Definition: gnunet-search.c:41
static void scheduler_fd_cb(void *cls, int fd)
Function called when the Postgres FD changes and we need to update the scheduler event loop task...
Definition: pq_event.c:280
Here is the call graph for this function:

◆ GNUNET_PQ_event_scheduler_stop()

void GNUNET_PQ_event_scheduler_stop ( struct GNUNET_PQ_Context db)

Stop running poll event loop using the GNUnet scheduler.

Parameters
dbdatabase handle

Definition at line 321 of file pq_event.c.

References GNUNET_PQ_Context::event_task, GNUNET_assert, GNUNET_free, GNUNET_SCHEDULER_cancel(), GNUNET_PQ_Context::rfd, GNUNET_PQ_Context::sc, and GNUNET_PQ_Context::scheduler_on.

322 {
324  GNUNET_free (db->rfd);
325  db->sc = NULL;
326  db->scheduler_on = false;
327  if (NULL != db->event_task)
328  {
330  db->event_task = NULL;
331  }
332 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
struct GNUNET_SCHEDULER_Task * event_task
Task responsible for processing events.
Definition: pq.h:84
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
struct GNUNET_NETWORK_Handle * rfd
File descriptor wrapper for event_task.
Definition: pq.h:89
bool scheduler_on
Is scheduling via the GNUnet scheduler desired?
Definition: pq.h:94
#define GNUNET_free(ptr)
Wrapper around free.
void * GNUNET_SCHEDULER_cancel(struct GNUNET_SCHEDULER_Task *task)
Cancel the task with the specified identifier.
Definition: scheduler.c:972
Here is the call graph for this function:

◆ GNUNET_PQ_event_listen()

struct GNUNET_PQ_EventHandler* GNUNET_PQ_event_listen ( struct GNUNET_PQ_Context db,
const struct GNUNET_PQ_EventHeaderP es,
GNUNET_PQ_EventCallback  cb,
void *  cb_cls 
)

Register callback to be invoked on events of type es.

Unlike many other calls, this function is thread-safe and may be called from threads that are different from the one that setup db. However, the cb will always be called from the thread that runs GNUNET_PQ_event_do_poll() or the GNUnet scheduler.

Parameters
dbdatabase context to use
esspecification of the event to listen for
cbfunction to call when the event happens, possibly multiple times (until GNUNET_PQ_event_listen_cancel() is invoked)
cb_clsclosure for cb
Returns
handle useful to cancel the listener

Definition at line 405 of file pq_event.c.

References GNUNET_PQ_EventHandler::cb, GNUNET_PQ_EventHandler::cb_cls, GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::conn, GNUNET_PQ_EventHandler::db, es_to_sh(), GNUNET_assert, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE, GNUNET_CONTAINER_multishortmap_put(), GNUNET_CONTAINER_multishortmap_size(), GNUNET_new, GNUNET_OK, manage_subscribe(), GNUNET_PQ_Context::notify_lock, GNUNET_PQ_Context::sc, GNUNET_PQ_Context::sc_cls, and GNUNET_PQ_EventHandler::sh.

409 {
410  struct GNUNET_PQ_EventHandler *eh;
411  bool was_zero;
412 
413  eh = GNUNET_new (struct GNUNET_PQ_EventHandler);
414  eh->db = db;
415  es_to_sh (es,
416  &eh->sh);
417  eh->cb = cb;
418  eh->cb_cls = cb_cls;
419  GNUNET_assert (0 ==
420  pthread_mutex_lock (&db->notify_lock));
421  was_zero = (0 == GNUNET_CONTAINER_multishortmap_size (db->channel_map));
424  &eh->sh,
425  eh,
427  if ( (NULL != db->sc) &&
428  was_zero)
429  {
430  int fd = PQsocket (db->conn);
431 
432  if (-1 != fd)
433  db->sc (db->sc_cls,
434  fd);
435  }
436  manage_subscribe (db,
437  "LISTEN ",
438  eh);
439  GNUNET_assert (0 ==
440  pthread_mutex_unlock (&db->notify_lock));
441  return eh;
442 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
GNUNET_PQ_EventCallback cb
Function to call on events.
Definition: pq_event.c:43
unsigned int GNUNET_CONTAINER_multishortmap_size(const struct GNUNET_CONTAINER_MultiShortmap *map)
Get the number of key-value pairs in the map.
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
#define GNUNET_new(type)
Allocate a struct or union of the given type.
PGconn * conn
Actual connection.
Definition: pq.h:39
void * cb_cls
Closure for cb.
Definition: pq_event.c:48
static void es_to_sh(const struct GNUNET_PQ_EventHeaderP *es, struct GNUNET_ShortHashCode *sh)
Convert es to a short hash.
Definition: pq_event.c:66
int GNUNET_CONTAINER_multishortmap_put(struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, void *value, enum GNUNET_CONTAINER_MultiHashMapOption opt)
Store a key-value pair in the map.
static void manage_subscribe(struct GNUNET_PQ_Context *db, const char *cmd, struct GNUNET_PQ_EventHandler *eh)
Definition: pq_event.c:336
void * sc_cls
Closure for sc.
Definition: pq.h:69
struct GNUNET_ShortHashCode sh
Channel name.
Definition: pq_event.c:38
Allow multiple values with the same key.
static struct GNUNET_FS_DirectoryBuilder * db
Definition: gnunet-search.c:41
Handle for an active LISTENer to the database.
Definition: pq_event.c:33
struct GNUNET_PQ_Context * db
Database context this event handler is with.
Definition: pq_event.c:53
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
Here is the call graph for this function:

◆ GNUNET_PQ_event_listen_cancel()

void GNUNET_PQ_event_listen_cancel ( struct GNUNET_PQ_EventHandler eh)

Stop notifications.

Unlike many other calls, this function is thread-safe and may be called from threads that are different from the one that setup db. However, the cb will always be called from the thread that runs GNUNET_PQ_event_do_poll() or the GNUnet scheduler.

Parameters
ehhandle to unregister.

Definition at line 446 of file pq_event.c.

References GNUNET_PQ_Context::channel_map, GNUNET_PQ_EventHandler::db, GNUNET_assert, GNUNET_CONTAINER_multishortmap_remove(), GNUNET_CONTAINER_multishortmap_size(), GNUNET_free, GNUNET_OK, manage_subscribe(), GNUNET_PQ_Context::notify_lock, GNUNET_PQ_Context::sc, GNUNET_PQ_Context::sc_cls, and GNUNET_PQ_EventHandler::sh.

447 {
448  struct GNUNET_PQ_Context *db = eh->db;
449 
450  GNUNET_assert (0 ==
451  pthread_mutex_lock (&db->notify_lock));
454  &eh->sh,
455  eh));
456 
457  manage_subscribe (db,
458  "UNLISTEN ",
459  eh);
460  if ( (NULL != db->sc) &&
462  {
463  db->sc (db->sc_cls,
464  -1);
465  }
466  GNUNET_assert (0 ==
467  pthread_mutex_unlock (&db->notify_lock));
468  GNUNET_free (eh);
469 }
GNUNET_PQ_SocketCallback sc
Function to call on Postgres FDs.
Definition: pq.h:64
unsigned int GNUNET_CONTAINER_multishortmap_size(const struct GNUNET_CONTAINER_MultiShortmap *map)
Get the number of key-value pairs in the map.
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
int GNUNET_CONTAINER_multishortmap_remove(struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, const void *value)
Remove the given key-value pair from the map.
static void manage_subscribe(struct GNUNET_PQ_Context *db, const char *cmd, struct GNUNET_PQ_EventHandler *eh)
Definition: pq_event.c:336
void * sc_cls
Closure for sc.
Definition: pq.h:69
struct GNUNET_ShortHashCode sh
Channel name.
Definition: pq_event.c:38
static struct GNUNET_FS_DirectoryBuilder * db
Definition: gnunet-search.c:41
struct GNUNET_PQ_Context * db
Database context this event handler is with.
Definition: pq_event.c:53
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
Handle to Postgres database.
Definition: pq.h:34
#define GNUNET_free(ptr)
Wrapper around free.
Here is the call graph for this function:

◆ GNUNET_PQ_event_notify()

void GNUNET_PQ_event_notify ( struct GNUNET_PQ_Context db,
const struct GNUNET_PQ_EventHeaderP es,
const void *  extra,
size_t  extra_size 
)

Notify all that listen on es of an event.

Unlike many other calls, this function is thread-safe and may be called from threads that are different from the one that setup db. However, the cb will always be called from the thread that runs GNUNET_PQ_event_do_poll() or the GNUnet scheduler.

Parameters
dbdatabase context to use
esspecification of the event to generate
extraadditional event data provided
extra_sizenumber of bytes in extra

Definition at line 473 of file pq_event.c.

References GNUNET_PQ_Context::conn, end, es_to_channel(), GNUNET_assert, GNUNET_ERROR_TYPE_ERROR, GNUNET_log_from, GNUNET_STRINGS_data_to_string(), and result.

477 {
478  char sql[16 + 64 + extra_size * 8 / 5 + 8];
479  char *end;
480  PGresult *result;
481 
482  end = stpcpy (sql,
483  "NOTIFY ");
484  end = es_to_channel (es,
485  end);
486  end = stpcpy (end,
487  ", '");
488  end = GNUNET_STRINGS_data_to_string (extra,
489  extra_size,
490  end,
491  sizeof (sql) - (end - sql) - 1);
492  GNUNET_assert (NULL != end);
493  *end = '\0';
494  end = stpcpy (end,
495  "'");
496  result = PQexec (db->conn,
497  sql);
498  if (PGRES_COMMAND_OK != PQresultStatus (result))
499  {
501  "pq",
502  "Failed to execute `%s': %s/%s/%s/%s/%s",
503  sql,
504  PQresultErrorField (result,
505  PG_DIAG_MESSAGE_PRIMARY),
506  PQresultErrorField (result,
507  PG_DIAG_MESSAGE_DETAIL),
508  PQresultErrorMessage (result),
509  PQresStatus (PQresultStatus (result)),
510  PQerrorMessage (db->conn));
511  }
512  PQclear (result);
513 }
static int end
Set if we are to shutdown all services (including ARM).
Definition: gnunet-arm.c:34
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
static char * es_to_channel(const struct GNUNET_PQ_EventHeaderP *es, char identifier[64])
Convert es to a Postgres identifier.
Definition: pq_event.c:114
PGconn * conn
Actual connection.
Definition: pq.h:39
static int result
Global testing status.
#define GNUNET_log_from(kind, comp,...)
char * GNUNET_STRINGS_data_to_string(const void *data, size_t size, char *out, size_t out_size)
Convert binary data to ASCII encoding using CrockfordBase32.
Definition: strings.c:695
Here is the call graph for this function:

◆ GNUNET_PQ_run_sql()

enum GNUNET_GenericReturnValue GNUNET_PQ_run_sql ( struct GNUNET_PQ_Context db,
const char *  load_path 
)

Within the db context, run all the SQL files from the load_path from 0000-9999.sql (as long as the files exist contiguously).

Parameters
dbdatabase context to use
load_pathwhere to find the XXXX.sql files
Returns
GNUNET_OK on success

Definition at line 188 of file pq_connect.c.

References apply_patch(), buf, GNUNET_break, GNUNET_DB_STATUS_HARD_ERROR, GNUNET_DB_STATUS_SUCCESS_ONE_RESULT, GNUNET_DISK_file_test(), GNUNET_ERROR_TYPE_DEBUG, GNUNET_ERROR_TYPE_INFO, GNUNET_log, GNUNET_NO, GNUNET_OK, GNUNET_PQ_cleanup_result(), GNUNET_PQ_eval_prepared_singleton_select(), GNUNET_PQ_query_param_end, GNUNET_PQ_query_param_string(), GNUNET_PQ_result_spec_end, GNUNET_PQ_result_spec_string(), GNUNET_snprintf(), GNUNET_SYSERR, GNUNET_YES, and ret.

Referenced by GNUNET_PQ_reconnect().

190 {
191  const char *load_path_suffix;
192  size_t slen = strlen (load_path) + 10;
193 
194  load_path_suffix = strrchr (load_path, '/');
195  if (NULL == load_path_suffix)
196  {
197  GNUNET_break (0);
198  return GNUNET_SYSERR;
199  }
200  load_path_suffix++; /* skip '/' */
202  "Loading SQL resources from `%s'\n",
203  load_path);
204  for (unsigned int i = 1; i<10000; i++)
205  {
206  enum GNUNET_DB_QueryStatus qs;
207  {
208  char buf[slen];
209 
210  /* First, check patch actually exists */
211  GNUNET_snprintf (buf,
212  sizeof (buf),
213  "%s%04u.sql",
214  load_path,
215  i);
216  if (GNUNET_YES !=
217  GNUNET_DISK_file_test (buf))
218  return GNUNET_OK; /* We are done */
219  }
220 
221  /* Second, check with DB versioning schema if this patch was already applied,
222  if so, skip it. */
223  {
224  char patch_name[slen];
225 
226  GNUNET_snprintf (patch_name,
227  sizeof (patch_name),
228  "%s%04u",
229  load_path_suffix,
230  i);
231  {
232  char *applied_by;
233  struct GNUNET_PQ_QueryParam params[] = {
234  GNUNET_PQ_query_param_string (patch_name),
236  };
237  struct GNUNET_PQ_ResultSpec rs[] = {
238  GNUNET_PQ_result_spec_string ("applied_by",
239  &applied_by),
241  };
242 
244  "gnunet_pq_check_patch",
245  params,
246  rs);
248  {
250  "Database version %s already applied by %s, skipping\n",
251  patch_name,
252  applied_by);
254  }
255  if (GNUNET_DB_STATUS_HARD_ERROR == qs)
256  {
257  GNUNET_break (0);
258  return GNUNET_SYSERR;
259  }
260  }
261  }
263  continue; /* patch already applied, skip it */
264 
265  /* patch not yet applied, run it! */
266  {
267  int ret;
268 
269  ret = apply_patch (db,
270  load_path,
271  i);
272  if (GNUNET_NO == ret)
273  break;
274  if (GNUNET_SYSERR == ret)
275  return GNUNET_SYSERR;
276  }
277  }
278  return GNUNET_OK;
279 }
struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_string(const char *ptr)
Generate query parameter for a string.
char * load_path
Path to load SQL files from.
Definition: pq.h:59
Description of a DB result cell.
static int ret
Return value of the commandline.
Definition: gnunet-abd.c:81
A hard error occurred, retrying will not help.
Definition: gnunet_db_lib.h:39
#define GNUNET_break(cond)
Use this for internal assertion violations that are not fatal (can be handled) but should not occur...
int GNUNET_snprintf(char *buf, size_t size, const char *format,...) __attribute__((format(printf
Like snprintf, just aborts if the buffer is of insufficient size.
struct GNUNET_PQ_ResultSpec GNUNET_PQ_result_spec_string(const char *name, char **dst)
0-terminated string expected.
#define GNUNET_PQ_result_spec_end
End of result parameter specification.
#define GNUNET_PQ_query_param_end
End of query parameter specification.
Definition: gnunet_pq_lib.h:97
enum GNUNET_DB_QueryStatus GNUNET_PQ_eval_prepared_singleton_select(struct GNUNET_PQ_Context *db, const char *statement_name, const struct GNUNET_PQ_QueryParam *params, struct GNUNET_PQ_ResultSpec *rs)
Execute a named prepared statement that is a SELECT statement which must return a single result in co...
Definition: pq_eval.c:258
static char buf[2048]
static enum GNUNET_GenericReturnValue apply_patch(struct GNUNET_PQ_Context *db, const char *load_path, unsigned int i)
Apply patch number from path load_path.
Definition: pq_connect.c:130
The transaction succeeded, and yielded one result.
Definition: gnunet_db_lib.h:58
Description of a DB query parameter.
Definition: gnunet_pq_lib.h:64
#define GNUNET_log(kind,...)
GNUNET_DB_QueryStatus
Status code returned from functions running database commands.
Definition: gnunet_db_lib.h:34
enum GNUNET_GenericReturnValue GNUNET_DISK_file_test(const char *fil)
Check that fil corresponds to a filename (of a file that exists and that is not a directory)...
Definition: disk.c:437
void GNUNET_PQ_cleanup_result(struct GNUNET_PQ_ResultSpec *rs)
Free all memory that was allocated in rs during GNUNET_PQ_extract_result().
Definition: pq.c:117
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GNUNET_PQ_disconnect()

void GNUNET_PQ_disconnect ( struct GNUNET_PQ_Context db)

Disconnect from the database, destroying the prepared statements and releasing other associated resources.

Parameters
dbdatabase handle to disconnect (will be free'd)

Definition at line 469 of file pq_connect.c.

References GNUNET_PQ_Context::channel_map, GNUNET_PQ_Context::config_str, GNUNET_PQ_Context::conn, GNUNET_PQ_Context::es, GNUNET_assert, GNUNET_CONTAINER_multishortmap_destroy(), GNUNET_CONTAINER_multishortmap_size(), GNUNET_free, GNUNET_PQ_Context::load_path, GNUNET_PQ_Context::notify_lock, and GNUNET_PQ_Context::ps.

Referenced by database_shutdown(), libgnunet_plugin_datacache_postgres_done(), and libgnunet_plugin_datastore_postgres_done().

470 {
471  GNUNET_assert (0 ==
474  GNUNET_assert (0 ==
475  pthread_mutex_destroy (&db->notify_lock));
476  GNUNET_free (db->es);
477  GNUNET_free (db->ps);
478  GNUNET_free (db->load_path);
479  GNUNET_free (db->config_str);
480  PQfinish (db->conn);
481  GNUNET_free (db);
482 }
struct GNUNET_PQ_PreparedStatement * ps
Prepared statements.
Definition: pq.h:49
unsigned int GNUNET_CONTAINER_multishortmap_size(const struct GNUNET_CONTAINER_MultiShortmap *map)
Get the number of key-value pairs in the map.
char * load_path
Path to load SQL files from.
Definition: pq.h:59
#define GNUNET_assert(cond)
Use this for fatal errors that cannot be handled.
pthread_mutex_t notify_lock
Lock to access channel_map.
Definition: pq.h:79
struct GNUNET_PQ_ExecuteStatement * es
Statements to execute upon connection.
Definition: pq.h:44
PGconn * conn
Actual connection.
Definition: pq.h:39
char * config_str
Configuration to use to connect to the DB.
Definition: pq.h:54
void GNUNET_CONTAINER_multishortmap_destroy(struct GNUNET_CONTAINER_MultiShortmap *map)
Destroy a hash map.
struct GNUNET_CONTAINER_MultiShortmap * channel_map
Map managing event subscriptions.
Definition: pq.h:74
#define GNUNET_free(ptr)
Wrapper around free.
Here is the call graph for this function:
Here is the caller graph for this function: