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