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