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