uncrustify as demanded.
[oweals/gnunet.git] / src / include / gnunet_pq_lib.h
1 /*
2    This file is part of GNUnet
3    Copyright (C) 2016, 2017 GNUnet e.V.
4
5    GNUnet is free software: you can redistribute it and/or modify it
6    under the terms of the GNU Affero General Public License as published
7    by the Free Software Foundation, either version 3 of the License,
8    or (at your option) any later version.
9
10    GNUnet is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Affero General Public License for more details.
14
15    You should have received a copy of the GNU Affero General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20 /**
21  * @file include/gnunet_pq_lib.h
22  * @brief helper functions for Postgres DB interactions
23  * @author Christian Grothoff
24  */
25 #ifndef GNUNET_PQ_LIB_H
26 #define GNUNET_PQ_LIB_H
27
28 #include <libpq-fe.h>
29 #include "gnunet_util_lib.h"
30 #include "gnunet_db_lib.h"
31
32 /* ************************* pq_query_helper.c functions ************************ */
33
34
35 /**
36  * Function called to convert input argument into SQL parameters.
37  *
38  * @param cls closure
39  * @param data pointer to input argument
40  * @param data_len number of bytes in @a data (if applicable)
41  * @param[out] param_values SQL data to set
42  * @param[out] param_lengths SQL length data to set
43  * @param[out] param_formats SQL format data to set
44  * @param param_length number of entries available in the @a param_values, @a param_lengths and @a param_formats arrays
45  * @param[out] scratch buffer for dynamic allocations (to be done via #GNUNET_malloc()
46  * @param scratch_length number of entries left in @a scratch
47  * @return -1 on error, number of offsets used in @a scratch otherwise
48  */
49 typedef int (*GNUNET_PQ_QueryConverter) (void *cls,
50                                          const void *data,
51                                          size_t data_len,
52                                          void *param_values[],
53                                          int param_lengths[],
54                                          int param_formats[],
55                                          unsigned int param_length,
56                                          void *scratch[],
57                                          unsigned int scratch_length);
58
59
60 /**
61  * @brief Description of a DB query parameter.
62  */
63 struct GNUNET_PQ_QueryParam {
64   /**
65    * Function for how to handle this type of entry.
66    */
67   GNUNET_PQ_QueryConverter conv;
68
69   /**
70    * Closure for @e conv.
71    */
72   void *conv_cls;
73
74   /**
75    * Data or NULL.
76    */
77   const void *data;
78
79   /**
80    * Size of @e data
81    */
82   size_t size;
83
84   /**
85    * Number of parameters eaten by this operation.
86    */
87   unsigned int num_params;
88 };
89
90
91 /**
92  * End of query parameter specification.
93  */
94 #define GNUNET_PQ_query_param_end \
95   {                               \
96     NULL, NULL, NULL, 0, 0        \
97   }
98
99
100 /**
101  * Generate query parameter for a buffer @a ptr of
102  * @a ptr_size bytes.
103  *
104  * @param ptr pointer to the query parameter to pass
105  * @oaran ptr_size number of bytes in @a ptr
106  */
107 struct GNUNET_PQ_QueryParam
108 GNUNET_PQ_query_param_fixed_size(const void *ptr, size_t ptr_size);
109
110
111 /**
112  * Generate query parameter for a string.
113  *
114  * @param ptr pointer to the string query parameter to pass
115  */
116 struct GNUNET_PQ_QueryParam
117 GNUNET_PQ_query_param_string(const char *ptr);
118
119
120 /**
121  * Generate fixed-size query parameter with size determined
122  * by variable type.
123  *
124  * @param x pointer to the query parameter to pass.
125  */
126 #define GNUNET_PQ_query_param_auto_from_type(x) \
127   GNUNET_PQ_query_param_fixed_size((x), sizeof(*(x)))
128
129
130 /**
131  * Generate query parameter for an RSA public key.  The
132  * database must contain a BLOB type in the respective position.
133  *
134  * @param x the query parameter to pass.
135  */
136 struct GNUNET_PQ_QueryParam
137 GNUNET_PQ_query_param_rsa_public_key(
138   const struct GNUNET_CRYPTO_RsaPublicKey *x);
139
140
141 /**
142  * Generate query parameter for an RSA signature.  The
143  * database must contain a BLOB type in the respective position.
144  *
145  * @param x the query parameter to pass
146  */
147 struct GNUNET_PQ_QueryParam
148 GNUNET_PQ_query_param_rsa_signature(
149   const struct GNUNET_CRYPTO_RsaSignature *x);
150
151
152 /**
153  * Generate query parameter for an absolute time value.
154  * The database must store a 64-bit integer.
155  *
156  * @param x pointer to the query parameter to pass
157  */
158 struct GNUNET_PQ_QueryParam
159 GNUNET_PQ_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x);
160
161
162 /**
163  * Generate query parameter for an absolute time value.
164  * The database must store a 64-bit integer.
165  *
166  * @param x pointer to the query parameter to pass
167  */
168 struct GNUNET_PQ_QueryParam
169 GNUNET_PQ_query_param_absolute_time_nbo(
170   const struct GNUNET_TIME_AbsoluteNBO *x);
171
172
173 /**
174  * Generate query parameter for an uint16_t in host byte order.
175  *
176  * @param x pointer to the query parameter to pass
177  */
178 struct GNUNET_PQ_QueryParam
179 GNUNET_PQ_query_param_uint16(const uint16_t *x);
180
181
182 /**
183  * Generate query parameter for an uint32_t in host byte order.
184  *
185  * @param x pointer to the query parameter to pass
186  */
187 struct GNUNET_PQ_QueryParam
188 GNUNET_PQ_query_param_uint32(const uint32_t *x);
189
190
191 /**
192  * Generate query parameter for an uint16_t in host byte order.
193  *
194  * @param x pointer to the query parameter to pass
195  */
196 struct GNUNET_PQ_QueryParam
197 GNUNET_PQ_query_param_uint64(const uint64_t *x);
198
199
200 /* ************************* pq_result_helper.c functions ************************ */
201
202
203 /**
204  * Extract data from a Postgres database @a result at row @a row.
205  *
206  * @param cls closure
207  * @param result where to extract data from
208  * @param int row to extract data from
209  * @param fname name (or prefix) of the fields to extract from
210  * @param[in,out] dst_size where to store size of result, may be NULL
211  * @param[out] dst where to store the result
212  * @return
213  *   #GNUNET_YES if all results could be extracted
214  *   #GNUNET_SYSERR if a result was invalid (non-existing field or NULL)
215  */
216 typedef int (*GNUNET_PQ_ResultConverter) (void *cls,
217                                           PGresult *result,
218                                           int row,
219                                           const char *fname,
220                                           size_t *dst_size,
221                                           void *dst);
222
223
224 /**
225  * Function called to clean up memory allocated
226  * by a #GNUNET_PQ_ResultConverter.
227  *
228  * @param cls closure
229  * @param rd result data to clean up
230  */
231 typedef void (*GNUNET_PQ_ResultCleanup) (void *cls, void *rd);
232
233
234 /**
235  * @brief Description of a DB result cell.
236  */
237 struct GNUNET_PQ_ResultSpec {
238   /**
239    * What is the format of the result?
240    */
241   GNUNET_PQ_ResultConverter conv;
242
243   /**
244    * Function to clean up result data, NULL if cleanup is
245    * not necessary.
246    */
247   GNUNET_PQ_ResultCleanup cleaner;
248
249   /**
250    * Closure for @e conv and @e cleaner.
251    */
252   void *cls;
253
254   /**
255    * Destination for the data.
256    */
257   void *dst;
258
259   /**
260    * Allowed size for the data, 0 for variable-size
261    * (in this case, the type of @e dst is a `void **`
262    * and we need to allocate a buffer of the right size).
263    */
264   size_t dst_size;
265
266   /**
267    * Field name of the desired result.
268    */
269   const char *fname;
270
271   /**
272    * Where to store actual size of the result.
273    */
274   size_t *result_size;
275 };
276
277
278 /**
279  * End of result parameter specification.
280  *
281  * @return array last entry for the result specification to use
282  */
283 #define GNUNET_PQ_result_spec_end         \
284   {                                       \
285     NULL, NULL, NULL, NULL, 0, NULL, NULL \
286   }
287
288
289 /**
290  * Variable-size result expected.
291  *
292  * @param name name of the field in the table
293  * @param[out] dst where to store the result, allocated
294  * @param[out] sptr where to store the size of @a dst
295  * @return array entry for the result specification to use
296  */
297 struct GNUNET_PQ_ResultSpec
298 GNUNET_PQ_result_spec_variable_size(const char *name,
299                                     void **dst,
300                                     size_t *sptr);
301
302
303 /**
304  * Fixed-size result expected.
305  *
306  * @param name name of the field in the table
307  * @param[out] dst where to store the result
308  * @param dst_size number of bytes in @a dst
309  * @return array entry for the result specification to use
310  */
311 struct GNUNET_PQ_ResultSpec
312 GNUNET_PQ_result_spec_fixed_size(const char *name, void *dst, size_t dst_size);
313
314
315 /**
316  * We expect a fixed-size result, with size determined by the type of `* dst`
317  *
318  * @param name name of the field in the table
319  * @param dst point to where to store the result, type fits expected result size
320  * @return array entry for the result specification to use
321  */
322 #define GNUNET_PQ_result_spec_auto_from_type(name, dst) \
323   GNUNET_PQ_result_spec_fixed_size(name, (dst), sizeof(*(dst)))
324
325
326 /**
327  * 0-terminated string expected.
328  *
329  * @param name name of the field in the table
330  * @param[out] dst where to store the result, allocated
331  * @return array entry for the result specification to use
332  */
333 struct GNUNET_PQ_ResultSpec
334 GNUNET_PQ_result_spec_string(const char *name, char **dst);
335
336
337 /**
338  * RSA public key expected.
339  *
340  * @param name name of the field in the table
341  * @param[out] rsa where to store the result
342  * @return array entry for the result specification to use
343  */
344 struct GNUNET_PQ_ResultSpec
345 GNUNET_PQ_result_spec_rsa_public_key(const char *name,
346                                      struct GNUNET_CRYPTO_RsaPublicKey **rsa);
347
348
349 /**
350  * RSA signature expected.
351  *
352  * @param name name of the field in the table
353  * @param[out] sig where to store the result;
354  * @return array entry for the result specification to use
355  */
356 struct GNUNET_PQ_ResultSpec
357 GNUNET_PQ_result_spec_rsa_signature(const char *name,
358                                     struct GNUNET_CRYPTO_RsaSignature **sig);
359
360
361 /**
362  * Absolute time expected.
363  *
364  * @param name name of the field in the table
365  * @param[out] at where to store the result
366  * @return array entry for the result specification to use
367  */
368 struct GNUNET_PQ_ResultSpec
369 GNUNET_PQ_result_spec_absolute_time(const char *name,
370                                     struct GNUNET_TIME_Absolute *at);
371
372
373 /**
374  * Absolute time expected.
375  *
376  * @param name name of the field in the table
377  * @param[out] at where to store the result
378  * @return array entry for the result specification to use
379  */
380 struct GNUNET_PQ_ResultSpec
381 GNUNET_PQ_result_spec_absolute_time_nbo(const char *name,
382                                         struct GNUNET_TIME_AbsoluteNBO *at);
383
384
385 /**
386  * uint16_t expected.
387  *
388  * @param name name of the field in the table
389  * @param[out] u16 where to store the result
390  * @return array entry for the result specification to use
391  */
392 struct GNUNET_PQ_ResultSpec
393 GNUNET_PQ_result_spec_uint16(const char *name, uint16_t *u16);
394
395
396 /**
397  * uint32_t expected.
398  *
399  * @param name name of the field in the table
400  * @param[out] u32 where to store the result
401  * @return array entry for the result specification to use
402  */
403 struct GNUNET_PQ_ResultSpec
404 GNUNET_PQ_result_spec_uint32(const char *name, uint32_t *u32);
405
406
407 /**
408  * uint64_t expected.
409  *
410  * @param name name of the field in the table
411  * @param[out] u64 where to store the result
412  * @return array entry for the result specification to use
413  */
414 struct GNUNET_PQ_ResultSpec
415 GNUNET_PQ_result_spec_uint64(const char *name, uint64_t *u64);
416
417
418 /* ************************* pq.c functions ************************ */
419
420 /**
421  * Execute a prepared statement.
422  *
423  * @param db_conn database connection
424  * @param name name of the prepared statement
425  * @param params parameters to the statement
426  * @return postgres result
427  * @deprecated (should become an internal API)
428  */
429 PGresult *
430 GNUNET_PQ_exec_prepared(PGconn *db_conn,
431                         const char *name,
432                         const struct GNUNET_PQ_QueryParam *params);
433
434
435 /**
436  * Extract results from a query result according to the given specification.
437  *
438  * @param result result to process
439  * @param[in,out] rs result specification to extract for
440  * @param row row from the result to extract
441  * @return
442  *   #GNUNET_YES if all results could be extracted
443  *   #GNUNET_SYSERR if a result was invalid (non-existing field)
444  * @deprecated (should become an internal API)
445  */
446 int
447 GNUNET_PQ_extract_result(PGresult *result,
448                          struct GNUNET_PQ_ResultSpec *rs,
449                          int row);
450
451
452 /**
453  * Free all memory that was allocated in @a rs during
454  * #GNUNET_PQ_extract_result().
455  *
456  * @param rs reult specification to clean up
457  */
458 void
459 GNUNET_PQ_cleanup_result(struct GNUNET_PQ_ResultSpec *rs);
460
461
462 /* ******************** pq_eval.c functions ************** */
463
464
465 /**
466  * Check the @a result's error code to see what happened.
467  * Also logs errors.
468  *
469  * @param connection connection to execute the statement in
470  * @param statement_name name of the statement that created @a result
471  * @param result result to check
472  * @return status code from the result, mapping PQ status
473  *         codes to `enum GNUNET_DB_QueryStatus`.  Never
474  *         returns positive values as this function does
475  *         not look at the result set.
476  * @deprecated (low level, let's see if we can do with just the high-level functions)
477  */
478 enum GNUNET_DB_QueryStatus
479 GNUNET_PQ_eval_result(PGconn *connection,
480                       const char *statement_name,
481                       PGresult *result);
482
483
484 /**
485  * Execute a named prepared @a statement that is NOT a SELECT
486  * statement in @a connnection using the given @a params.  Returns the
487  * resulting session state.
488  *
489  * @param connection connection to execute the statement in
490  * @param statement_name name of the statement
491  * @param params parameters to give to the statement (#GNUNET_PQ_query_param_end-terminated)
492  * @return status code from the result, mapping PQ status
493  *         codes to `enum GNUNET_DB_QueryStatus`.   If the
494  *         statement was a DELETE or UPDATE statement, the
495  *         number of affected rows is returned; if the
496  *         statment was an INSERT statement, and no row
497  *         was added due to a UNIQUE violation, we return
498  *         zero; if INSERT was successful, we return one.
499  */
500 enum GNUNET_DB_QueryStatus
501 GNUNET_PQ_eval_prepared_non_select(PGconn *connection,
502                                    const char *statement_name,
503                                    const struct GNUNET_PQ_QueryParam *params);
504
505
506 /**
507  * Function to be called with the results of a SELECT statement
508  * that has returned @a num_results results.
509  *
510  * @param cls closure
511  * @param result the postgres result
512  * @param num_result the number of results in @a result
513  */
514 typedef void (*GNUNET_PQ_PostgresResultHandler) (void *cls,
515                                                  PGresult *result,
516                                                  unsigned int num_results);
517
518
519 /**
520  * Execute a named prepared @a statement that is a SELECT statement
521  * which may return multiple results in @a connection using the given
522  * @a params.  Call @a rh with the results.  Returns the query
523  * status including the number of results given to @a rh (possibly zero).
524  * @a rh will not have been called if the return value is negative.
525  *
526  * @param connection connection to execute the statement in
527  * @param statement_name name of the statement
528  * @param params parameters to give to the statement (#GNUNET_PQ_query_param_end-terminated)
529  * @param rh function to call with the result set, NULL to ignore
530  * @param rh_cls closure to pass to @a rh
531  * @return status code from the result, mapping PQ status
532  *         codes to `enum GNUNET_DB_QueryStatus`.
533  */
534 enum GNUNET_DB_QueryStatus
535 GNUNET_PQ_eval_prepared_multi_select(PGconn *connection,
536                                      const char *statement_name,
537                                      const struct GNUNET_PQ_QueryParam *params,
538                                      GNUNET_PQ_PostgresResultHandler rh,
539                                      void *rh_cls);
540
541
542 /**
543  * Execute a named prepared @a statement that is a SELECT statement
544  * which must return a single result in @a connection using the given
545  * @a params.  Stores the result (if any) in @a rs, which the caller
546  * must then clean up using #GNUNET_PQ_cleanup_result() if the return
547  * value was #GNUNET_DB_STATUS_SUCCESS_ONE_RESULT.  Returns the
548  * resulting session status.
549  *
550  * @param connection connection to execute the statement in
551  * @param statement_name name of the statement
552  * @param params parameters to give to the statement (#GNUNET_PQ_query_param_end-terminated)
553  * @param[in,out] rs result specification to use for storing the result of the query
554  * @return status code from the result, mapping PQ status
555  *         codes to `enum GNUNET_DB_QueryStatus`.
556  */
557 enum GNUNET_DB_QueryStatus
558 GNUNET_PQ_eval_prepared_singleton_select(
559   PGconn *connection,
560   const char *statement_name,
561   const struct GNUNET_PQ_QueryParam *params,
562   struct GNUNET_PQ_ResultSpec *rs);
563
564
565 /* ******************** pq_prepare.c functions ************** */
566
567
568 /**
569  * Information needed to prepare a list of SQL statements using
570  * #GNUNET_PQ_prepare_statements().
571  */
572 struct GNUNET_PQ_PreparedStatement {
573   /**
574    * Name of the statement.
575    */
576   const char *name;
577
578   /**
579    * Actual SQL statement.
580    */
581   const char *sql;
582
583   /**
584    * Number of arguments included in @e sql.
585    */
586   unsigned int num_arguments;
587 };
588
589
590 /**
591  * Terminator for prepared statement list.
592  */
593 #define GNUNET_PQ_PREPARED_STATEMENT_END \
594   {                                      \
595     NULL, NULL, 0                        \
596   }
597
598
599 /**
600  * Create a `struct GNUNET_PQ_PreparedStatement`.
601  *
602  * @param name name of the statement
603  * @param sql actual SQL statement
604  * @param num_args number of arguments in the statement
605  * @return initialized struct
606  */
607 struct GNUNET_PQ_PreparedStatement
608 GNUNET_PQ_make_prepare(const char *name,
609                        const char *sql,
610                        unsigned int num_args);
611
612
613 /**
614  * Request creation of prepared statements @a ps from Postgres.
615  *
616  * @param connection connection to prepare the statements for
617  * @param ps #GNUNET_PQ_PREPARED_STATEMENT_END-terminated array of prepared
618  *            statements.
619  * @return #GNUNET_OK on success,
620  *         #GNUNET_SYSERR on error
621  */
622 int
623 GNUNET_PQ_prepare_statements(PGconn *connection,
624                              const struct GNUNET_PQ_PreparedStatement *ps);
625
626
627 /* ******************** pq_exec.c functions ************** */
628
629
630 /**
631  * Information needed to run a list of SQL statements using
632  * #GNUNET_PQ_exec_statements().
633  */
634 struct GNUNET_PQ_ExecuteStatement {
635   /**
636    * Actual SQL statement.
637    */
638   const char *sql;
639
640   /**
641    * Should we ignore errors?
642    */
643   int ignore_errors;
644 };
645
646
647 /**
648  * Terminator for executable statement list.
649  */
650 #define GNUNET_PQ_EXECUTE_STATEMENT_END \
651   {                                     \
652     NULL, GNUNET_SYSERR                 \
653   }
654
655
656 /**
657  * Create a `struct GNUNET_PQ_ExecuteStatement` where errors are fatal.
658  *
659  * @param sql actual SQL statement
660  * @return initialized struct
661  */
662 struct GNUNET_PQ_ExecuteStatement
663 GNUNET_PQ_make_execute(const char *sql);
664
665
666 /**
667  * Create a `struct GNUNET_PQ_ExecuteStatement` where errors should
668  * be tolerated.
669  *
670  * @param sql actual SQL statement
671  * @return initialized struct
672  */
673 struct GNUNET_PQ_ExecuteStatement
674 GNUNET_PQ_make_try_execute(const char *sql);
675
676
677 /**
678  * Request execution of an array of statements @a es from Postgres.
679  *
680  * @param connection connection to execute the statements over
681  * @param es #GNUNET_PQ_PREPARED_STATEMENT_END-terminated array of prepared
682  *            statements.
683  * @return #GNUNET_OK on success (modulo statements where errors can be ignored)
684  *         #GNUNET_SYSERR on error
685  */
686 int
687 GNUNET_PQ_exec_statements(PGconn *connection,
688                           const struct GNUNET_PQ_ExecuteStatement *es);
689
690
691 /* ******************** pq_connect.c functions ************** */
692
693
694 /**
695  * Create a connection to the Postgres database using @a config_str
696  * for the configuration.  Initialize logging via GNUnet's log
697  * routines and disable Postgres's logger.
698  *
699  * @param config_str configuration to use
700  * @return NULL on error
701  */
702 PGconn *
703 GNUNET_PQ_connect(const char *config_str);
704
705
706 /**
707  * Connect to a postgres database using the configuration
708  * option "CONFIG" in @a section.
709  *
710  * @param cfg configuration
711  * @param section configuration section to use to get Postgres configuration options
712  * @return the postgres handle, NULL on error
713  */
714 PGconn *
715 GNUNET_PQ_connect_with_cfg(const struct GNUNET_CONFIGURATION_Handle *cfg,
716                            const char *section);
717
718
719 #endif /* GNUNET_PQ_LIB_H_ */
720
721 /* end of include/gnunet_pq_lib.h */