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