]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/cats.h
Use the sqlite3_changes to implement sql_affected_rows()
[bacula/bacula] / bacula / src / cats / cats.h
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2008 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  * SQL header file
30  *
31  *   by Kern E. Sibbald
32  *
33  *   Anyone who accesses the database will need to include
34  *   this file.
35  *
36  * This file contains definitions common to sql.c and
37  * the external world, and definitions destined only
38  * for the external world. This is control with
39  * the define __SQL_C, which is defined only in sql.c
40  *
41  *    Version $Id$
42  */
43
44 /*
45    Here is how database versions work.
46
47    While I am working on a new release with database changes, the
48    update scripts are in the src/cats directory under the names
49    update_xxx_tables.in.  Most of the time, I make database updates
50    in one go and immediately update the version, but not always.  If
51    there are going to be several updates as is the case with version
52    1.37, then I will often forgo changing the version until the last
53    update otherwise I will end up with too many versions and a lot
54    of confusion.
55
56    When I am pretty sure there will be no more updates, I will
57    change the version from 8 to 9 (in the present case), and when I
58    am 100% sure there will be no more changes, the update script
59    will be copied to the updatedb directory with the correct name
60    (in the present case 8 to 9).
61
62    Now, in principle, each of the different DB implementations
63    can have a different version, but in practice they are all
64    the same (simplifies things). The exception is the internal
65    database, which is no longer used, and hence, no longer changes.
66  */
67
68
69 #ifndef __SQL_H_
70 #define __SQL_H_ 1
71
72 enum {
73    SQL_TYPE_MYSQL      = 0,
74    SQL_TYPE_POSTGRESQL = 1,
75    SQL_TYPE_SQLITE     = 2,
76    SQL_TYPE_SQLITE3
77 };
78
79
80 typedef void (DB_LIST_HANDLER)(void *, const char *);
81 typedef int (DB_RESULT_HANDLER)(void *, int, char **);
82
83 #define db_lock(mdb)   _db_lock(__FILE__, __LINE__, mdb)
84 #define db_unlock(mdb) _db_unlock(__FILE__, __LINE__, mdb)
85
86 #ifdef __SQL_C
87
88 #if defined(BUILDING_CATS)
89 #ifdef HAVE_SQLITE
90
91 #define BDB_VERSION 11
92
93 #include <sqlite.h>
94
95 /* Define opaque structure for sqlite */
96 struct sqlite {
97    char dummy;
98 };
99
100 #define IS_NUM(x)             ((x) == 1)
101 #define IS_NOT_NULL(x)        ((x) == 1)
102
103 typedef struct s_sql_field {
104    char *name;                        /* name of column */
105    int length;                        /* length */
106    int max_length;                    /* max length */
107    uint32_t type;                     /* type */
108    uint32_t flags;                    /* flags */
109 } SQL_FIELD;
110
111 /*
112  * This is the "real" definition that should only be
113  * used inside sql.c and associated database interface
114  * subroutines.
115  *                    S Q L I T E
116  */
117 struct B_DB {
118    BQUEUE bq;                         /* queue control */
119    brwlock_t lock;                    /* transaction lock */
120    struct sqlite *db;
121    char **result;
122    int status;
123    int nrow;                          /* nrow returned from sqlite */
124    int ncolumn;                       /* ncolum returned from sqlite */
125    int num_rows;                      /* used by code */
126    int row;                           /* seek row */
127    int field;                         /* seek field */
128    SQL_FIELD **fields;                /* defined fields */
129    int ref_count;
130    char *db_name;
131    char *db_user;
132    char *db_address;                  /* host name address */
133    char *db_socket;                   /* socket for local access */
134    char *db_password;
135    int  db_port;                      /* port for host name address */
136    bool connected;                    /* connection made to db */
137    bool have_insert_id;               /* do not have insert id */
138    bool fields_defined;               /* set when fields defined */
139    char *sqlite_errmsg;               /* error message returned by sqlite */
140    POOLMEM *errmsg;                   /* nicely edited error message */
141    POOLMEM *cmd;                      /* SQL command string */
142    POOLMEM *cached_path;              /* cached path name */
143    int cached_path_len;               /* length of cached path */
144    uint32_t cached_path_id;           /* cached path id */
145    bool allow_transactions;           /* transactions allowed */
146    bool transaction;                  /* transaction started */
147    int changes;                       /* changes during transaction */
148    POOLMEM *fname;                    /* Filename only */
149    POOLMEM *path;                     /* Path only */
150    POOLMEM *esc_name;                 /* Escaped file name */
151    POOLMEM *esc_path;                 /* Escaped path name */
152    int fnl;                           /* file name length */
153    int pnl;                           /* path name length */
154 };
155
156
157 /*
158  * "Generic" names for easier conversion
159  *
160  *                    S Q L I T E
161  */
162 #define sql_store_result(x)   (x)->result
163 #define sql_free_result(x)    my_sqlite_free_table(x)
164 #define sql_fetch_row(x)      my_sqlite_fetch_row(x)
165 #define sql_query(x, y)       my_sqlite_query((x), (y))
166 #ifdef HAVE_SQLITE3
167 #define sql_insert_id(x,y)    sqlite3_last_insert_rowid((x)->db)
168 #define sql_close(x)          sqlite3_close((x)->db)
169 #define sql_affected_rows(x)  sqlite3_changes((x)->db)
170 #else
171 #define sql_insert_id(x,y)    sqlite_last_insert_rowid((x)->db)
172 #define sql_close(x)          sqlite_close((x)->db)
173 #define sql_affected_rows(x)  1
174 #endif
175 #define sql_strerror(x)       (x)->sqlite_errmsg?(x)->sqlite_errmsg:"unknown"
176 #define sql_num_rows(x)       (x)->nrow
177 #define sql_data_seek(x, i)   (x)->row = (i)
178 #define sql_field_seek(x, y)  my_sqlite_field_seek((x), (y))
179 #define sql_fetch_field(x)    my_sqlite_fetch_field(x)
180 #define sql_num_fields(x)     ((x)->ncolumn)
181 #define SQL_ROW               char**
182
183 #define sql_batch_start(x,y)    my_batch_start(x,y)
184 #define sql_batch_end(x,y,z)    my_batch_end(x,y,z)
185 #define sql_batch_insert(x,y,z) my_batch_insert(x,y,z)
186 #define sql_batch_lock_path_query       my_sqlite_batch_lock_query
187 #define sql_batch_lock_filename_query   my_sqlite_batch_lock_query
188 #define sql_batch_unlock_tables_query   my_sqlite_batch_unlock_query
189 #define sql_batch_fill_filename_query   my_sqlite_batch_fill_filename_query
190 #define sql_batch_fill_path_query       my_sqlite_batch_fill_path_query
191
192 /* In cats/sqlite.c */
193 void       my_sqlite_free_table(B_DB *mdb);
194 SQL_ROW    my_sqlite_fetch_row(B_DB *mdb);
195 int        my_sqlite_query(B_DB *mdb, const char *cmd);
196 void       my_sqlite_field_seek(B_DB *mdb, int field);
197 SQL_FIELD *my_sqlite_fetch_field(B_DB *mdb);
198 extern const char* my_sqlite_batch_lock_query;
199 extern const char* my_sqlite_batch_unlock_query;
200 extern const char* my_sqlite_batch_fill_filename_query;
201 extern const char* my_sqlite_batch_fill_path_query;
202
203
204 #else
205
206 /*                    S Q L I T E 3            */
207
208
209 #ifdef HAVE_SQLITE3
210
211
212 #define BDB_VERSION 11
213
214 #include <sqlite3.h>
215
216 /* Define opaque structure for sqlite */
217 struct sqlite3 {
218    char dummy;
219 };
220
221 #define IS_NUM(x)             ((x) == 1)
222 #define IS_NOT_NULL(x)        ((x) == 1)
223
224 typedef struct s_sql_field {
225    char *name;                        /* name of column */
226    int length;                        /* length */
227    int max_length;                    /* max length */
228    uint32_t type;                     /* type */
229    uint32_t flags;                    /* flags */
230 } SQL_FIELD;
231
232 /*
233  * This is the "real" definition that should only be
234  * used inside sql.c and associated database interface
235  * subroutines.
236  *                    S Q L I T E
237  */
238 struct B_DB {
239    BQUEUE bq;                         /* queue control */
240    brwlock_t lock;                    /* transaction lock */
241    struct sqlite3 *db;
242    char **result;
243    int status;
244    int nrow;                          /* nrow returned from sqlite */
245    int ncolumn;                       /* ncolum returned from sqlite */
246    int num_rows;                      /* used by code */
247    int row;                           /* seek row */
248    int field;                         /* seek field */
249    SQL_FIELD **fields;                /* defined fields */
250    int ref_count;
251    char *db_name;
252    char *db_user;
253    char *db_address;                  /* host name address */
254    char *db_socket;                   /* socket for local access */
255    char *db_password;
256    int  db_port;                      /* port for host name address */
257    bool connected;                    /* connection made to db */
258    bool have_insert_id;               /* do not have insert id */
259    bool fields_defined;               /* set when fields defined */
260    char *sqlite_errmsg;               /* error message returned by sqlite */
261    POOLMEM *errmsg;                   /* nicely edited error message */
262    POOLMEM *cmd;                      /* SQL command string */
263    POOLMEM *cached_path;              /* cached path name */
264    int cached_path_len;               /* length of cached path */
265    uint32_t cached_path_id;           /* cached path id */
266    bool allow_transactions;           /* transactions allowed */
267    bool transaction;                  /* transaction started */
268    int changes;                       /* changes during transaction */
269    POOLMEM *fname;                    /* Filename only */
270    POOLMEM *path;                     /* Path only */
271    POOLMEM *esc_name;                 /* Escaped file name */
272    POOLMEM *esc_path;                 /* Escaped path name */
273    int fnl;                           /* file name length */
274    int pnl;                           /* path name length */
275 };
276
277 /*
278  * Conversion of sqlite 2 names to sqlite3
279  */
280 #define sqlite_last_insert_rowid sqlite3_last_insert_rowid
281 #define sqlite_open sqlite3_open
282 #define sqlite_close sqlite3_close
283 #define sqlite_result sqlite3_result
284 #define sqlite_exec sqlite3_exec
285 #define sqlite_get_table sqlite3_get_table
286 #define sqlite_free_table sqlite3_free_table
287
288
289 /*
290  * "Generic" names for easier conversion
291  *
292  *                    S Q L I T E 3
293  */
294 #define sql_store_result(x)   (x)->result
295 #define sql_free_result(x)    my_sqlite_free_table(x)
296 #define sql_fetch_row(x)      my_sqlite_fetch_row(x)
297 #define sql_query(x, y)       my_sqlite_query((x), (y))
298 #ifdef HAVE_SQLITE3
299 #define sql_insert_id(x,y)    sqlite3_last_insert_rowid((x)->db)
300 #define sql_close(x)          sqlite3_close((x)->db)
301 #else
302 #define sql_insert_id(x,y)    sqlite_last_insert_rowid((x)->db)
303 #define sql_close(x)          sqlite_close((x)->db)
304 #endif
305 #define sql_strerror(x)       (x)->sqlite_errmsg?(x)->sqlite_errmsg:"unknown"
306 #define sql_num_rows(x)       (x)->nrow
307 #define sql_data_seek(x, i)   (x)->row = (i)
308 #define sql_affected_rows(x)  sqlite3_changes((x)->db)
309 #define sql_field_seek(x, y)  my_sqlite_field_seek((x), (y))
310 #define sql_fetch_field(x)    my_sqlite_fetch_field(x)
311 #define sql_num_fields(x)     ((x)->ncolumn)
312 #define sql_batch_start(x,y)    my_batch_start(x,y)
313 #define sql_batch_end(x,y,z)    my_batch_end(x,y,z)
314 #define sql_batch_insert(x,y,z) my_batch_insert(x,y,z)
315 #define SQL_ROW               char**
316 #define sql_batch_lock_path_query       my_sqlite_batch_lock_query
317 #define sql_batch_lock_filename_query   my_sqlite_batch_lock_query
318 #define sql_batch_unlock_tables_query   my_sqlite_batch_unlock_query
319 #define sql_batch_fill_filename_query   my_sqlite_batch_fill_filename_query
320 #define sql_batch_fill_path_query       my_sqlite_batch_fill_path_query
321
322 /* In cats/sqlite.c */
323 void       my_sqlite_free_table(B_DB *mdb);
324 SQL_ROW    my_sqlite_fetch_row(B_DB *mdb);
325 int        my_sqlite_query(B_DB *mdb, const char *cmd);
326 void       my_sqlite_field_seek(B_DB *mdb, int field);
327 SQL_FIELD *my_sqlite_fetch_field(B_DB *mdb);
328 extern const char* my_sqlite_batch_lock_query;
329 extern const char* my_sqlite_batch_unlock_query;
330 extern const char* my_sqlite_batch_fill_filename_query;
331 extern const char* my_sqlite_batch_fill_path_query;
332
333
334 #else
335
336 #ifdef HAVE_MYSQL
337
338 #define BDB_VERSION 11
339
340 #include <mysql.h>
341
342 /*
343  * This is the "real" definition that should only be
344  * used inside sql.c and associated database interface
345  * subroutines.
346  *
347  *                     M Y S Q L
348  */
349 struct B_DB {
350    BQUEUE bq;                         /* queue control */
351    brwlock_t lock;                    /* transaction lock */
352    MYSQL mysql;
353    MYSQL *db;
354    MYSQL_RES *result;
355    int status;
356    my_ulonglong num_rows;
357    int ref_count;
358    char *db_name;
359    char *db_user;
360    char *db_password;
361    char *db_address;                  /* host address */
362    char *db_socket;                   /* socket for local access */
363    int db_port;                       /* port of host address */
364    int have_insert_id;                /* do have insert_id() */
365    bool connected;
366    POOLMEM *errmsg;                   /* nicely edited error message */
367    POOLMEM *cmd;                      /* SQL command string */
368    POOLMEM *cached_path;
369    int cached_path_len;               /* length of cached path */
370    uint32_t cached_path_id;
371    bool allow_transactions;           /* transactions allowed */ 
372    int changes;                       /* changes made to db */
373    POOLMEM *fname;                    /* Filename only */
374    POOLMEM *path;                     /* Path only */
375    POOLMEM *esc_name;                 /* Escaped file name */
376    POOLMEM *esc_path;                 /* Escaped path name */
377    int fnl;                           /* file name length */
378    int pnl;                           /* path name length */
379 };
380
381 #define DB_STATUS int
382
383 /* "Generic" names for easier conversion */
384 #define sql_store_result(x)   mysql_store_result((x)->db)
385 #define sql_use_result(x)     mysql_use_result((x)->db)
386 #define sql_free_result(x)    my_mysql_free_result(x)
387 #define sql_fetch_row(x)      mysql_fetch_row((x)->result)
388 #define sql_query(x, y)       mysql_query((x)->db, (y))
389 #define sql_strerror(x)       mysql_error((x)->db)
390 #define sql_num_rows(x)       mysql_num_rows((x)->result)
391 #define sql_data_seek(x, i)   mysql_data_seek((x)->result, (i))
392 #define sql_affected_rows(x)  mysql_affected_rows((x)->db)
393 #define sql_insert_id(x,y)    mysql_insert_id((x)->db)
394 #define sql_field_seek(x, y)  mysql_field_seek((x)->result, (y))
395 #define sql_fetch_field(x)    mysql_fetch_field((x)->result)
396 #define sql_num_fields(x)     (int)mysql_num_fields((x)->result)
397 #define SQL_ROW               MYSQL_ROW
398 #define SQL_FIELD             MYSQL_FIELD
399
400 #define sql_batch_start(x,y)    my_batch_start(x,y)
401 #define sql_batch_end(x,y,z)    my_batch_end(x,y,z)
402 #define sql_batch_insert(x,y,z) my_batch_insert(x,y,z)
403 #define sql_batch_lock_path_query       my_mysql_batch_lock_path_query
404 #define sql_batch_lock_filename_query   my_mysql_batch_lock_filename_query
405 #define sql_batch_unlock_tables_query   my_mysql_batch_unlock_tables_query
406 #define sql_batch_fill_filename_query   my_mysql_batch_fill_filename_query
407 #define sql_batch_fill_path_query       my_mysql_batch_fill_path_query
408
409
410 extern const char* my_mysql_batch_lock_path_query;
411 extern const char* my_mysql_batch_lock_filename_query;
412 extern const char* my_mysql_batch_unlock_tables_query;
413 extern const char* my_mysql_batch_fill_filename_query;
414 extern const char* my_mysql_batch_fill_path_query;
415 extern void  my_mysql_free_result(B_DB *mdb);
416
417 #else
418
419 #ifdef HAVE_POSTGRESQL
420
421 #define BDB_VERSION 11
422
423 #include <libpq-fe.h>
424
425 /* TEMP: the following is taken from select OID, typname from pg_type; */
426 #define IS_NUM(x)        ((x) == 20 || (x) == 21 || (x) == 23 || (x) == 700 || (x) == 701)
427 #define IS_NOT_NULL(x)   ((x) == 1)
428
429 typedef char **POSTGRESQL_ROW;
430 typedef struct pg_field {
431    char         *name;
432    int           max_length;
433    unsigned int  type;
434    unsigned int  flags;       // 1 == not null
435 } POSTGRESQL_FIELD;
436
437
438 /*
439  * This is the "real" definition that should only be
440  * used inside sql.c and associated database interface
441  * subroutines.
442  *
443  *                     P O S T G R E S Q L
444  */
445 struct B_DB {
446    BQUEUE bq;                         /* queue control */
447    brwlock_t lock;                    /* transaction lock */
448    PGconn *db;
449    PGresult *result;
450    int status;
451    POSTGRESQL_ROW row;
452    POSTGRESQL_FIELD *fields;
453    int num_rows;
454    int row_size;                  /* size of malloced rows */
455    int num_fields;
456    int fields_size;               /* size of malloced fields */
457    int row_number;                /* row number from my_postgresql_data_seek */
458    int field_number;              /* field number from my_postgresql_field_seek */
459    int ref_count;
460    char *db_name;
461    char *db_user;
462    char *db_password;
463    char *db_address;              /* host address */
464    char *db_socket;               /* socket for local access */
465    int db_port;                   /* port of host address */
466    int have_insert_id;            /* do have insert_id() */
467    bool connected;
468    POOLMEM *errmsg;               /* nicely edited error message */
469    POOLMEM *cmd;                  /* SQL command string */
470    POOLMEM *cached_path;
471    int cached_path_len;           /* length of cached path */
472    uint32_t cached_path_id;
473    bool allow_transactions;       /* transactions allowed */
474    bool transaction;              /* transaction started */
475    int changes;                   /* changes made to db */
476    POOLMEM *fname;                /* Filename only */
477    POOLMEM *path;                 /* Path only */
478    POOLMEM *esc_name;             /* Escaped file name */
479    POOLMEM *esc_path;             /* Escaped path name */
480    int fnl;                       /* file name length */
481    int pnl;                       /* path name length */
482 };
483
484 void               my_postgresql_free_result(B_DB *mdb);
485 POSTGRESQL_ROW     my_postgresql_fetch_row  (B_DB *mdb);
486 int                my_postgresql_query      (B_DB *mdb, const char *query);
487 void               my_postgresql_data_seek  (B_DB *mdb, int row);
488 int                my_postgresql_currval    (B_DB *mdb, const char *table_name);
489 void               my_postgresql_field_seek (B_DB *mdb, int row);
490 POSTGRESQL_FIELD * my_postgresql_fetch_field(B_DB *mdb);
491
492 int my_postgresql_batch_start(JCR *jcr, B_DB *mdb);
493 int my_postgresql_batch_end(JCR *jcr, B_DB *mdb, const char *error);
494 typedef struct ATTR_DBR ATTR_DBR;
495 int my_postgresql_batch_insert(JCR *jcr, B_DB *mdb, ATTR_DBR *ar);
496 char *my_postgresql_copy_escape(char *dest, char *src, size_t len);
497
498 extern const char* my_pg_batch_lock_path_query;
499 extern const char* my_pg_batch_lock_filename_query;
500 extern const char* my_pg_batch_unlock_tables_query;
501 extern const char* my_pg_batch_fill_filename_query;
502 extern const char* my_pg_batch_fill_path_query;
503
504 /* "Generic" names for easier conversion */
505 #define sql_store_result(x)   ((x)->result)
506 #define sql_free_result(x)    my_postgresql_free_result(x)
507 #define sql_fetch_row(x)      my_postgresql_fetch_row(x)
508 #define sql_query(x, y)       my_postgresql_query((x), (y))
509 #define sql_close(x)          PQfinish((x)->db)
510 #define sql_strerror(x)       PQerrorMessage((x)->db)
511 #define sql_num_rows(x)       ((unsigned) PQntuples((x)->result))
512 #define sql_data_seek(x, i)   my_postgresql_data_seek((x), (i))
513 #define sql_affected_rows(x)  ((unsigned) atoi(PQcmdTuples((x)->result)))
514 #define sql_insert_id(x,y)    my_postgresql_currval((x), (y))
515 #define sql_field_seek(x, y)  my_postgresql_field_seek((x), (y))
516 #define sql_fetch_field(x)    my_postgresql_fetch_field(x)
517 #define sql_num_fields(x)     ((x)->num_fields)
518
519 #define sql_batch_start(x,y)    my_postgresql_batch_start(x,y)
520 #define sql_batch_end(x,y,z)    my_postgresql_batch_end(x,y,z)
521 #define sql_batch_insert(x,y,z) my_postgresql_batch_insert(x,y,z)
522 #define sql_batch_lock_path_query       my_pg_batch_lock_path_query
523 #define sql_batch_lock_filename_query   my_pg_batch_lock_filename_query
524 #define sql_batch_unlock_tables_query   my_pg_batch_unlock_tables_query
525 #define sql_batch_fill_filename_query   my_pg_batch_fill_filename_query
526 #define sql_batch_fill_path_query       my_pg_batch_fill_path_query
527
528 #define SQL_ROW               POSTGRESQL_ROW
529 #define SQL_FIELD             POSTGRESQL_FIELD
530
531 #else
532
533 #ifdef HAVE_DBI
534
535 #define BDB_VERSION 11
536
537 #include <dbi/dbi.h>
538
539 #ifdef HAVE_BATCH_FILE_INSERT
540 #include <dbi/dbi-dev.h>
541 #endif //HAVE_BATCH_FILE_INSERT
542
543 #define IS_NUM(x)        ((x) == 1 || (x) == 2 )
544 #define IS_NOT_NULL(x)   ((x) == (1 << 0))
545
546 typedef char **DBI_ROW;
547 typedef struct dbi_field {
548    char         *name;
549    int           max_length;
550    unsigned int  type;
551    unsigned int  flags;       // 1 == not null
552 } DBI_FIELD;
553
554 typedef struct dbi_field_get {
555    BQUEUE bq;
556    char *value;
557 } DBI_FIELD_GET;
558
559 /*
560  * This is the "real" definition that should only be
561  * used inside sql.c and associated database interface
562  * subroutines.
563  *
564  *                     D B I
565  */
566 struct B_DB {
567    BQUEUE bq;                         /* queue control */
568    brwlock_t lock;                    /* transaction lock */
569    dbi_conn *db;
570    dbi_result *result;
571    dbi_inst instance;
572    dbi_error_flag status;
573    DBI_ROW row;
574    DBI_FIELD *fields;
575    DBI_FIELD_GET *field_get;
576    int num_rows;
577    int row_size;                  /* size of malloced rows */
578    int num_fields;
579    int fields_size;               /* size of malloced fields */
580    int row_number;                /* row number from my_postgresql_data_seek */
581    int field_number;              /* field number from my_postgresql_field_seek */
582    int ref_count;
583    int db_type;                   /* DBI driver defined */
584    char *db_driverdir ;           /* DBI driver dir */
585    char *db_driver;               /* DBI type database */
586    char *db_name;
587    char *db_user;
588    char *db_password;
589    char *db_address;              /* host address */
590    char *db_socket;               /* socket for local access */
591    int db_port;                   /* port of host address */
592    int have_insert_id;            /* do have insert_id() */
593    bool connected;
594    POOLMEM *errmsg;               /* nicely edited error message */
595    POOLMEM *cmd;                  /* SQL command string */
596    POOLMEM *cached_path;
597    int cached_path_len;           /* length of cached path */
598    uint32_t cached_path_id;
599    bool allow_transactions;       /* transactions allowed */
600    bool transaction;              /* transaction started */
601    int changes;                   /* changes made to db */
602    POOLMEM *fname;                /* Filename only */
603    POOLMEM *path;                 /* Path only */
604    POOLMEM *esc_name;             /* Escaped file name */
605    POOLMEM *esc_path;             /* Escaped path name */
606    int fnl;                       /* file name length */
607    int pnl;                       /* path name length */
608 };
609
610 void               my_dbi_free_result(B_DB *mdb);
611 DBI_ROW            my_dbi_fetch_row  (B_DB *mdb);
612 int                my_dbi_query      (B_DB *mdb, const char *query);
613 void               my_dbi_data_seek  (B_DB *mdb, int row);
614 void               my_dbi_field_seek (B_DB *mdb, int row);
615 DBI_FIELD *        my_dbi_fetch_field(B_DB *mdb);
616 const char *       my_dbi_strerror   (B_DB *mdb);
617 int                my_dbi_getisnull  (dbi_result *result, int row_number, int column_number);
618 char *             my_dbi_getvalue   (dbi_result *result, int row_number, unsigned int column_number);
619 //int                my_dbi_getvalue   (dbi_result *result, int row_number, unsigned int column_number, char *value);
620 int                my_dbi_sql_insert_id(B_DB *mdb, char *table_name);
621
622 int my_dbi_batch_start(JCR *jcr, B_DB *mdb);
623 int my_dbi_batch_end(JCR *jcr, B_DB *mdb, const char *error);
624 typedef struct ATTR_DBR ATTR_DBR;
625 int my_dbi_batch_insert(JCR *jcr, B_DB *mdb, ATTR_DBR *ar);
626 char *my_postgresql_copy_escape(char *dest, char *src, size_t len);
627 // typedefs for libdbi work with postgresql copy insert
628 typedef int (*custom_function_insert_t)(void*, const char*, int);
629 typedef char* (*custom_function_error_t)(void*);
630 typedef int (*custom_function_end_t)(void*, const char*);
631
632 extern const char* my_dbi_batch_lock_path_query[4];
633 extern const char* my_dbi_batch_lock_filename_query[4];
634 extern const char* my_dbi_batch_unlock_tables_query[4];
635 extern const char* my_dbi_batch_fill_filename_query[4];
636 extern const char* my_dbi_batch_fill_path_query[4];
637
638 /* "Generic" names for easier conversion */
639 #define sql_store_result(x)   (x)->result
640 #define sql_free_result(x)    my_dbi_free_result(x)
641 #define sql_fetch_row(x)      my_dbi_fetch_row(x)
642 #define sql_query(x, y)       my_dbi_query((x), (y))
643 #define sql_close(x)          dbi_conn_close((x)->db)
644 #define sql_strerror(x)       my_dbi_strerror(x)
645 #define sql_num_rows(x)       dbi_result_get_numrows((x)->result)
646 #define sql_data_seek(x, i)   my_dbi_data_seek((x), (i))
647 /* #define sql_affected_rows(x)  dbi_result_get_numrows_affected((x)->result) */
648 #define sql_affected_rows(x)  1
649 #define sql_insert_id(x,y)    my_dbi_sql_insert_id((x), (y))
650 #define sql_field_seek(x, y)  my_dbi_field_seek((x), (y))
651 #define sql_fetch_field(x)    my_dbi_fetch_field(x)
652 #define sql_num_fields(x)     ((x)->num_fields)
653 #define sql_batch_start(x,y)    my_dbi_batch_start(x,y)
654 #define sql_batch_end(x,y,z)    my_dbi_batch_end(x,y,z)
655 #define sql_batch_insert(x,y,z) my_dbi_batch_insert(x,y,z)
656 #define sql_batch_lock_path_query       my_dbi_batch_lock_path_query[db_type]
657 #define sql_batch_lock_filename_query   my_dbi_batch_lock_filename_query[db_type]
658 #define sql_batch_unlock_tables_query   my_dbi_batch_unlock_tables_query[db_type]
659 #define sql_batch_fill_filename_query   my_dbi_batch_fill_filename_query[db_type]
660 #define sql_batch_fill_path_query       my_dbi_batch_fill_path_query[db_type]
661
662 #define SQL_ROW               DBI_ROW
663 #define SQL_FIELD             DBI_FIELD
664
665
666 #else  /* USE BACULA DB routines */
667
668 #define HAVE_BACULA_DB 1
669
670 /* Change this each time there is some incompatible
671  * file format change!!!!
672  */
673 #define BDB_VERSION 13                /* file version number */
674
675 struct s_control {
676    int bdb_version;                   /* Version number */
677    uint32_t JobId;                    /* next Job Id */
678    uint32_t PoolId;                   /* next Pool Id */
679    uint32_t MediaId;                  /* next Media Id */
680    uint32_t JobMediaId;               /* next JobMedia Id */
681    uint32_t ClientId;                 /* next Client Id */
682    uint32_t FileSetId;                /* nest FileSet Id */
683    time_t time;                       /* time file written */
684 };
685
686
687 /* This is the REAL definition for using the
688  *  Bacula internal DB
689  */
690 struct B_DB {
691    BQUEUE bq;                         /* queue control */
692 /* pthread_mutex_t mutex;  */         /* single thread lock */
693    brwlock_t lock;                    /* transaction lock */
694    int ref_count;                     /* number of times opened */
695    struct s_control control;          /* control file structure */
696    int cfd;                           /* control file device */
697    FILE *jobfd;                       /* Jobs records file descriptor */
698    FILE *poolfd;                      /* Pool records fd */
699    FILE *mediafd;                     /* Media records fd */
700    FILE *jobmediafd;                  /* JobMedia records fd */
701    FILE *clientfd;                    /* Client records fd */
702    FILE *filesetfd;                   /* FileSet records fd */
703    char *db_name;                     /* name of database */
704    POOLMEM *errmsg;                   /* nicely edited error message */
705    POOLMEM *cmd;                      /* Command string */
706    POOLMEM *cached_path;
707    int cached_path_len;               /* length of cached path */
708    uint32_t cached_path_id;
709 };
710
711 #endif /* HAVE_SQLITE3 */
712 #endif /* HAVE_MYSQL */
713 #endif /* HAVE_SQLITE */
714 #endif /* HAVE_POSTGRESQL */
715 #endif /* HAVE_DBI */
716 #endif
717
718 /* Use for better error location printing */
719 #define UPDATE_DB(jcr, db, cmd) UpdateDB(__FILE__, __LINE__, jcr, db, cmd)
720 #define INSERT_DB(jcr, db, cmd) InsertDB(__FILE__, __LINE__, jcr, db, cmd)
721 #define QUERY_DB(jcr, db, cmd) QueryDB(__FILE__, __LINE__, jcr, db, cmd)
722 #define DELETE_DB(jcr, db, cmd) DeleteDB(__FILE__, __LINE__, jcr, db, cmd)
723
724
725 #else    /* not __SQL_C */
726
727 /* This is a "dummy" definition for use outside of sql.c
728  */
729 struct B_DB {
730    int dummy;                         /* for SunOS compiler */
731 };
732
733 #endif /*  __SQL_C */
734
735 /* ==============================================================
736  *
737  *  What follows are definitions that are used "globally" for all
738  *   the different SQL engines and both inside and external to the
739  *   cats directory.
740  */
741
742 extern uint32_t bacula_db_version;
743
744 #define faddr_t long
745
746 /*
747  * Structure used when calling db_get_query_ids()
748  *  allows the subroutine to return a list of ids.
749  */
750 class dbid_list : public SMARTALLOC {
751 public:
752    DBId_t *DBId;                      /* array of DBIds */
753    char *PurgedFiles;                 /* Array of PurgedFile flags */
754    int num_ids;                       /* num of ids actually stored */
755    int max_ids;                       /* size of id array */
756    int num_seen;                      /* number of ids processed */
757    int tot_ids;                       /* total to process */
758
759    dbid_list();                       /* in sql.c */
760    ~dbid_list();                      /* in sql.c */
761 };
762
763
764
765
766 /* Job information passed to create job record and update
767  * job record at end of job. Note, although this record
768  * contains all the fields found in the Job database record,
769  * it also contains fields found in the JobMedia record.
770  */
771 /* Job record */
772 struct JOB_DBR {
773    JobId_t JobId;
774    char Job[MAX_NAME_LENGTH];         /* Job unique name */
775    char Name[MAX_NAME_LENGTH];        /* Job base name */
776    int JobType;                       /* actually char(1) */
777    int JobLevel;                      /* actually char(1) */
778    int JobStatus;                     /* actually char(1) */
779    DBId_t ClientId;                   /* Id of client */
780    DBId_t PoolId;                     /* Id of pool */
781    DBId_t FileSetId;                  /* Id of FileSet */
782    DBId_t PriorJobId;                 /* Id of migrated (prior) job */
783    time_t SchedTime;                  /* Time job scheduled */
784    time_t StartTime;                  /* Job start time */
785    time_t EndTime;                    /* Job termination time of orig job */
786    time_t RealEndTime;                /* Job termination time of this job */
787    utime_t JobTDate;                  /* Backup time/date in seconds */
788    uint32_t VolSessionId;
789    uint32_t VolSessionTime;
790    uint32_t JobFiles;
791    uint32_t JobErrors;
792    uint32_t JobMissingFiles;
793    uint64_t JobBytes;
794    uint64_t ReadBytes;
795    int PurgedFiles;
796    int HasBase;
797
798    /* Note, FirstIndex, LastIndex, Start/End File and Block
799     * are only used in the JobMedia record.
800     */
801    uint32_t FirstIndex;               /* First index this Volume */
802    uint32_t LastIndex;                /* Last index this Volume */
803    uint32_t StartFile;
804    uint32_t EndFile;
805    uint32_t StartBlock;
806    uint32_t EndBlock;
807
808    char cSchedTime[MAX_TIME_LENGTH];
809    char cStartTime[MAX_TIME_LENGTH];
810    char cEndTime[MAX_TIME_LENGTH];
811    char cRealEndTime[MAX_TIME_LENGTH];
812    /* Extra stuff not in DB */
813    int limit;                         /* limit records to display */
814    faddr_t rec_addr;
815    uint32_t FileIndex;                /* added during Verify */
816 };
817
818 /* Job Media information used to create the media records
819  * for each Volume used for the job.
820  */
821 /* JobMedia record */
822 struct JOBMEDIA_DBR {
823    DBId_t JobMediaId;                 /* record id */
824    JobId_t  JobId;                    /* JobId */
825    DBId_t MediaId;                    /* MediaId */
826    uint32_t FirstIndex;               /* First index this Volume */
827    uint32_t LastIndex;                /* Last index this Volume */
828    uint32_t StartFile;                /* File for start of data */
829    uint32_t EndFile;                  /* End file on Volume */
830    uint32_t StartBlock;               /* start block on tape */
831    uint32_t EndBlock;                 /* last block */
832    uint32_t Copy;                     /* identical copy */
833 };
834
835
836 /* Volume Parameter structure */
837 struct VOL_PARAMS {
838    char VolumeName[MAX_NAME_LENGTH];  /* Volume name */
839    char MediaType[MAX_NAME_LENGTH];   /* Media Type */
840    char Storage[MAX_NAME_LENGTH];     /* Storage name */
841    uint32_t VolIndex;                 /* Volume seqence no. */
842    uint32_t FirstIndex;               /* First index this Volume */
843    uint32_t LastIndex;                /* Last index this Volume */
844    int32_t Slot;                      /* Slot */
845    uint64_t StartAddr;                /* Start address */
846    uint64_t EndAddr;                  /* End address */
847    int32_t InChanger;                 /* InChanger flag */
848 // uint32_t Copy;                     /* identical copy */
849 // uint32_t Stripe;                   /* RAIT strip number */
850 };
851
852
853 /* Attributes record -- NOT same as in database because
854  *  in general, this "record" creates multiple database
855  *  records (e.g. pathname, filename, fileattributes).
856  */
857 struct ATTR_DBR {
858    char *fname;                       /* full path & filename */
859    char *link;                        /* link if any */
860    char *attr;                        /* attributes statp */
861    uint32_t FileIndex;
862    uint32_t Stream;
863    JobId_t  JobId;
864    DBId_t ClientId;
865    DBId_t PathId;
866    DBId_t FilenameId;
867    FileId_t FileId;
868    char *Digest;
869    int DigestType;
870 };
871
872
873 /* File record -- same format as database */
874 struct FILE_DBR {
875    FileId_t FileId;
876    uint32_t FileIndex;
877    JobId_t  JobId;
878    DBId_t FilenameId;
879    DBId_t PathId;
880    JobId_t  MarkId;
881    char LStat[256];
882    char Digest[BASE64_SIZE(CRYPTO_DIGEST_MAX_SIZE)];
883    int DigestType;                    /* NO_SIG/MD5_SIG/SHA1_SIG */
884 };
885
886 /* Pool record -- same format as database */
887 struct POOL_DBR {
888    DBId_t PoolId;
889    char Name[MAX_NAME_LENGTH];        /* Pool name */
890    uint32_t NumVols;                  /* total number of volumes */
891    uint32_t MaxVols;                  /* max allowed volumes */
892    int32_t LabelType;                 /* Bacula/ANSI/IBM */
893    int32_t UseOnce;                   /* set to use once only */
894    int32_t UseCatalog;                /* set to use catalog */
895    int32_t AcceptAnyVolume;           /* set to accept any volume sequence */
896    int32_t AutoPrune;                 /* set to prune automatically */
897    int32_t Recycle;                   /* default Vol recycle flag */
898    utime_t  VolRetention;             /* retention period in seconds */
899    utime_t  VolUseDuration;           /* time in secs volume can be used */
900    uint32_t MaxVolJobs;               /* Max Jobs on Volume */
901    uint32_t MaxVolFiles;              /* Max files on Volume */
902    uint64_t MaxVolBytes;              /* Max bytes on Volume */
903    DBId_t RecyclePoolId;              /* RecyclePool destination when media is purged */
904    DBId_t ScratchPoolId;              /* ScratchPool source when media is needed */
905    char PoolType[MAX_NAME_LENGTH];
906    char LabelFormat[MAX_NAME_LENGTH];
907    /* Extra stuff not in DB */
908    faddr_t rec_addr;
909 };
910
911 class DEVICE_DBR {
912 public:
913    DBId_t DeviceId;
914    char Name[MAX_NAME_LENGTH];        /* Device name */
915    DBId_t MediaTypeId;                /* MediaType */
916    DBId_t StorageId;                  /* Storage id if autochanger */
917    uint32_t DevMounts;                /* Number of times mounted */
918    uint32_t DevErrors;                /* Number of read/write errors */
919    uint64_t DevReadBytes;             /* Number of bytes read */
920    uint64_t DevWriteBytes;            /* Number of bytew written */
921    uint64_t DevReadTime;              /* time spent reading volume */
922    uint64_t DevWriteTime;             /* time spent writing volume */
923    uint64_t DevReadTimeSincCleaning;  /* read time since cleaning */
924    uint64_t DevWriteTimeSincCleaning; /* write time since cleaning */
925    time_t   CleaningDate;             /* time last cleaned */
926    utime_t  CleaningPeriod;           /* time between cleanings */
927 };
928
929 class STORAGE_DBR {
930 public:
931    DBId_t StorageId;
932    char Name[MAX_NAME_LENGTH];        /* Device name */
933    int AutoChanger;                   /* Set if autochanger */
934
935    /* Not in database */
936    bool created;                      /* set if created by db_create ... */
937 };
938
939 class MEDIATYPE_DBR {
940 public:
941    DBId_t MediaTypeId;
942    char MediaType[MAX_NAME_LENGTH];   /* MediaType string */
943    int ReadOnly;                      /* Set if read-only */
944 };
945
946
947 /* Media record -- same as the database */
948 struct MEDIA_DBR {
949    DBId_t MediaId;                    /* Unique volume id */
950    char VolumeName[MAX_NAME_LENGTH];  /* Volume name */
951    char MediaType[MAX_NAME_LENGTH];   /* Media type */
952    DBId_t PoolId;                     /* Pool id */
953    time_t   FirstWritten;             /* Time Volume first written this usage */
954    time_t   LastWritten;              /* Time Volume last written */
955    time_t   LabelDate;                /* Date/Time Volume labeled */
956    time_t   InitialWrite;             /* Date/Time Volume first written */
957    int32_t  LabelType;                /* Label (Bacula/ANSI/IBM) */
958    uint32_t VolJobs;                  /* number of jobs on this medium */
959    uint32_t VolFiles;                 /* Number of files */
960    uint32_t VolBlocks;                /* Number of blocks */
961    uint32_t VolMounts;                /* Number of times mounted */
962    uint32_t VolErrors;                /* Number of read/write errors */
963    uint32_t VolWrites;                /* Number of writes */
964    uint32_t VolReads;                 /* Number of reads */
965    uint64_t VolBytes;                 /* Number of bytes written */
966    uint32_t VolParts;                 /* Number of parts written */
967    uint64_t MaxVolBytes;              /* Max bytes to write to Volume */
968    uint64_t VolCapacityBytes;         /* capacity estimate */
969    uint64_t VolReadTime;              /* time spent reading volume */
970    uint64_t VolWriteTime;             /* time spent writing volume */
971    utime_t  VolRetention;             /* Volume retention in seconds */
972    utime_t  VolUseDuration;           /* time in secs volume can be used */
973    uint32_t MaxVolJobs;               /* Max Jobs on Volume */
974    uint32_t MaxVolFiles;              /* Max files on Volume */
975    int32_t  Recycle;                  /* recycle yes/no */
976    int32_t  Slot;                     /* slot in changer */
977    int32_t  Enabled;                  /* 0=disabled, 1=enabled, 2=archived */
978    int32_t  InChanger;                /* Volume currently in changer */
979    DBId_t   StorageId;                /* Storage record Id */
980    uint32_t EndFile;                  /* Last file on volume */
981    uint32_t EndBlock;                 /* Last block on volume */
982    uint32_t RecycleCount;             /* Number of times recycled */
983    char     VolStatus[20];            /* Volume status */
984    DBId_t   DeviceId;                 /* Device where Vol last written */
985    DBId_t   LocationId;               /* Where Volume is -- user defined */
986    DBId_t   ScratchPoolId;            /* Where to move if scratch */
987    DBId_t   RecyclePoolId;            /* Where to move when recycled */
988    /* Extra stuff not in DB */
989    faddr_t rec_addr;                  /* found record address */
990    /* Since the database returns times as strings, this is how we pass
991     *   them back.
992     */
993    char    cFirstWritten[MAX_TIME_LENGTH]; /* FirstWritten returned from DB */
994    char    cLastWritten[MAX_TIME_LENGTH];  /* LastWritten returned from DB */
995    char    cLabelDate[MAX_TIME_LENGTH];    /* LabelData returned from DB */
996    char    cInitialWrite[MAX_TIME_LENGTH]; /* InitialWrite returned from DB */
997    bool    set_first_written;
998    bool    set_label_date;
999 };
1000
1001 /* Client record -- same as the database */
1002 struct CLIENT_DBR {
1003    DBId_t ClientId;                   /* Unique Client id */
1004    int AutoPrune;
1005    utime_t FileRetention;
1006    utime_t JobRetention;
1007    char Name[MAX_NAME_LENGTH];        /* Client name */
1008    char Uname[256];                   /* Uname for client */
1009 };
1010
1011 /* Counter record as in database */
1012 struct COUNTER_DBR {
1013    char Counter[MAX_NAME_LENGTH];
1014    int32_t MinValue;
1015    int32_t MaxValue;
1016    int32_t CurrentValue;
1017    char WrapCounter[MAX_NAME_LENGTH];
1018 };
1019
1020
1021 /* FileSet record -- same as the database */
1022 struct FILESET_DBR {
1023    DBId_t FileSetId;                  /* Unique FileSet id */
1024    char FileSet[MAX_NAME_LENGTH];     /* FileSet name */
1025    char MD5[50];                      /* MD5 signature of include/exclude */
1026    time_t CreateTime;                 /* date created */
1027    /*
1028     * This is where we return CreateTime
1029     */
1030    char cCreateTime[MAX_TIME_LENGTH]; /* CreateTime as returned from DB */
1031    /* Not in DB but returned by db_create_fileset() */
1032    bool created;                      /* set when record newly created */
1033 };
1034
1035 /* Call back context for getting a 32/64 bit value from the database */
1036 struct db_int64_ctx {
1037    int64_t value;                     /* value returned */
1038    int count;                         /* number of values seen */
1039 };
1040
1041
1042 #include "protos.h"
1043 #include "jcr.h"
1044 #include "sql_cmds.h"
1045
1046 /*
1047  * Exported globals from sql.c
1048  */
1049 extern int DLL_IMP_EXP db_type;        /* SQL engine type index */
1050
1051 /*
1052  * Some functions exported by sql.c for use within the
1053  *   cats directory.
1054  */
1055 void list_result(JCR *jcr, B_DB *mdb, DB_LIST_HANDLER *send, void *ctx, e_list_type type);
1056 void list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx);
1057 int get_sql_record_max(JCR *jcr, B_DB *mdb);
1058 bool check_tables_version(JCR *jcr, B_DB *mdb);
1059 void _db_unlock(const char *file, int line, B_DB *mdb);
1060 void _db_lock(const char *file, int line, B_DB *mdb);
1061 const char *db_get_type(void);
1062
1063 void print_dashes(B_DB *mdb);
1064 void print_result(B_DB *mdb);
1065 int QueryDB(const char *file, int line, JCR *jcr, B_DB *db, char *select_cmd);
1066 int InsertDB(const char *file, int line, JCR *jcr, B_DB *db, char *select_cmd);
1067 int DeleteDB(const char *file, int line, JCR *jcr, B_DB *db, char *delete_cmd);
1068 int UpdateDB(const char *file, int line, JCR *jcr, B_DB *db, char *update_cmd);
1069 void split_path_and_file(JCR *jcr, B_DB *mdb, const char *fname);
1070 #endif /* __SQL_H_ */