Merge pull request #4676 from jmarshallnz/dont_set_scraper_on_tvshow_on_nfo
[vuplus_xbmc] / xbmc / dbwrappers / dataset.h
1 /**********************************************************************
2  * Copyright (c) 2002, Leo Seib, Hannover
3  *
4  * Project:Dataset C++ Dynamic Library
5  * Module: Dataset abstraction layer header file
6  * Author: Leo Seib      E-Mail: leoseib@web.de
7  * Begin: 5/04/2002
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  *
27  **********************************************************************/
28
29
30 #ifndef _DATASET_H
31 #define _DATASET_H
32
33 #include <cstdio>
34 #include <string>
35 #include <map>
36 #include <list>
37 #include "qry_dat.h"
38 #include <stdarg.h>
39
40
41
42
43 namespace dbiplus {
44 class Dataset;          // forward declaration of class Dataset
45
46
47 #define S_NO_CONNECTION "No active connection";
48
49 #define DB_BUFF_MAX           8*1024    // Maximum buffer's capacity
50
51 #define DB_CONNECTION_NONE      0
52 #define DB_CONNECTION_OK        1
53 #define DB_CONNECTION_BAD       2
54
55 #define DB_COMMAND_OK           0       // OK - command executed
56 #define DB_EMPTY_QUERY          1       // Query didn't return tuples
57 #define DB_TUPLES_OK            2       // Query returned tuples
58 #define DB_ERROR                5
59 #define DB_BAD_RESPONSE         6
60 #define DB_UNEXPECTED           7       // This shouldn't ever happen
61 #define DB_UNEXPECTED_RESULT   -1       //For integer functions
62
63 /******************* Class Database definition ********************
64
65    represents  connection with database server;
66
67 ******************************************************************/
68 class Database  {
69 protected:
70   bool active;
71   std::string error, // Error description
72     host, port, db, login, passwd, //Login info
73     sequence_table, //Sequence table for nextid
74     default_charset, //Default character set
75     key, cert, ca, capath, ciphers; //SSL - Encryption info
76
77 public:
78 /* constructor */
79   Database();
80 /* destructor */
81   virtual ~Database();
82   virtual Dataset *CreateDataset() const = 0;
83 /* sets a new host name */
84   virtual void setHostName(const char *newHost) { host = newHost; }
85 /* gets a host name */
86   const char *getHostName(void) const { return host.c_str(); }
87 /* sets a new port */
88   void setPort(const char *newPort) { port = newPort; }
89 /* gets a port */
90   const char *getPort(void) const { return port.c_str(); }
91 /* sets a new database name */
92   virtual void setDatabase(const char *newDb) { db = newDb; }
93 /* gets a database name */
94   const char *getDatabase(void) const { return db.c_str(); }
95 /* sets a new login to database */
96   void setLogin(const char *newLogin) { login = newLogin; }
97 /* gets a login */
98   const char *getLogin(void) const { return login.c_str(); }
99 /* sets a password */
100   void setPasswd(const char *newPasswd) { passwd = newPasswd; }
101 /* gets a password */
102   const char *getPasswd(void) const { return passwd.c_str(); }
103 /* active status is OK state */
104   virtual bool isActive(void) const { return active; }
105 /* Set new name of sequence table */
106   void setSequenceTable(const char *new_seq_table) { sequence_table = new_seq_table; };
107 /* Get name of sequence table */
108   const char *getSequenceTable(void) { return sequence_table.c_str(); }
109 /* Get the default character set */
110   const char *getDefaultCharset(void) { return default_charset.c_str(); }
111 /* Sets SSL configuration */
112   virtual void setSSLConfig(const char *newKey, const char *newCert, const char *newCA, const char *newCApath, const char *newCiphers) {
113     key = newKey;
114     cert = newCert;
115     ca = newCA;
116     capath = newCApath;
117     ciphers = newCiphers;
118   }
119
120 /* virtual methods that must be overloaded in derived classes */
121
122   virtual int init(void) { return DB_COMMAND_OK; }
123   virtual int status(void) { return DB_CONNECTION_NONE; }
124   virtual int setErr(int err_code, const char *qry)=0;
125   virtual const char *getErrorMsg(void) { return error.c_str(); }
126         
127   virtual int connect(bool create) { return DB_COMMAND_OK; }
128   virtual int connectFull( const char *newDb, const char *newHost=NULL,
129                       const char *newLogin=NULL, const char *newPasswd=NULL,const char *newPort=NULL,
130                       const char *newKey=NULL, const char *newCert=NULL, const char *newCA=NULL, 
131                       const char *newCApath=NULL, const char *newCiphers=NULL);
132   virtual void disconnect(void) { active = false; }
133   virtual int reset(void) { return DB_COMMAND_OK; }
134   virtual int create(void) { return DB_COMMAND_OK; }
135   virtual int drop(void) { return DB_COMMAND_OK; }
136   virtual long nextid(const char* seq_name)=0;
137
138 /* \brief copy database */
139   virtual int copy(const char *new_name) { return -1; }
140
141 /* \brief drop all extra analytics from database */
142   virtual int drop_analytics(void) { return -1; }
143
144   virtual bool exists(void) { return false; }
145
146 /* virtual methods for transaction */
147
148   virtual void start_transaction() {};
149   virtual void commit_transaction() {};
150   virtual void rollback_transaction() {};
151
152 /* virtual methods for formatting */
153
154   /*! \brief Prepare a SQL statement for execution or querying using C printf nomenclature.
155    \param format - C printf compliant format string
156    \param ... - optional comma seperated list of variables for substitution in format string placeholders.
157    \return escaped and formatted string.
158    */
159   virtual std::string prepare(const char *format, ...);
160
161   /*! \brief Prepare a SQL statement for execution or querying using C printf nomenclature
162    \param format - C printf compliant format string
163    \param args - va_list of variables for substitution in format string placeholders.
164    \return escaped and formatted string.
165    */
166   virtual std::string vprepare(const char *format, va_list args) = 0;
167
168   virtual bool in_transaction() {return false;};
169
170 };
171
172
173
174
175 /******************* Class Dataset definition *********************
176
177   global abstraction for using Databases
178
179 ******************************************************************/
180
181 // define Dataset States type
182 enum dsStates { dsSelect, dsInsert, dsEdit, dsUpdate, dsDelete, dsInactive };
183 enum sqlType {sqlSelect,sqlUpdate,sqlInsert,sqlDelete,sqlExec};
184
185
186 typedef std::list<std::string> StringList;
187 typedef std::map<std::string,field_value> ParamList;
188
189
190 class Dataset  {
191 protected:
192 /*  char *Host     = ""; //WORK_HOST;
193   char *Database = ""; //WORK_DATABASE;
194   char *User     = ""; //WORK_USER;
195   char *Password = ""; //WORK_PASSWORD;
196 */
197
198   Database *db;         // info about db connection
199   dsStates ds_state;            // current state
200   Fields *fields_object, *edit_object;
201       
202   /* query results*/
203   result_set result;
204   result_set exec_res;
205   bool autorefresh;
206   char* errmsg;
207
208   bool active;                  // Is Query Opened?
209   bool haveError;
210   int frecno;                   // number of current row bei bewegung
211   std::string sql;
212
213   ParamList plist;              // Paramlist for locate
214   bool fbof, feof;
215   bool autocommit;              // for transactions
216
217
218 /* Variables to store SQL statements */
219   std::string empty_sql;                // Executed when result set is empty
220   std::string select_sql;               // May be only single string variable
221
222   StringList update_sql;                // May be an array in complex queries
223 /* Field values for updating must has prefix :NEW_ and :OLD_ and field name
224    Example:
225    update  wt_story set idobject set idobject=:NEW_idobject,body=:NEW_body
226    where idobject=:OLD_idobject
227    Essentually fields idobject and body must present in the
228    result set (select_sql statement) */
229
230   StringList insert_sql;                // May be an array in complex queries
231 /* Field values for inserting must has prefix :NEW_ and field name
232    Example:
233    insert into wt_story (idobject, body) values (:NEW_idobject, :NEW_body)
234    Essentually fields idobject and body must present in the
235    result set (select_sql statement) */
236
237   StringList delete_sql;                // May be an array in complex queries
238 /* Field values for deleing must has prefix :OLD_ and field name
239    Example:
240    delete from wt_story where idobject=:OLD_idobject
241    Essentually field idobject must present in the
242    result set (select_sql statement) */
243
244
245
246
247 /* Arrays for searching */
248 //  StringList names, values;
249
250
251 /* Makes direct inserts into database via mysql_query function */
252   virtual void make_insert() = 0;
253 /* Edit SQL */
254   virtual void make_edit() = 0;
255 /* Delete SQL */
256   virtual void make_deletion() = 0;
257
258 /* This function works only with MySQL database
259    Filling the fields information from select statement */
260   virtual void fill_fields(void)=0;
261
262 /* Parse Sql - replacing fields with prefixes :OLD_ and :NEW_ with current values of OLD or NEW field. */
263   void parse_sql(std::string &sql);
264
265 /* Returns old field value (for :OLD) */
266   virtual const field_value f_old(const char *f);
267
268 public:
269
270  virtual int str_compare(const char * s1, const char * s2);
271 /* constructor */
272   Dataset();
273   Dataset(Database *newDb);
274
275 /* destructor */
276   virtual ~Dataset();
277
278 /* sets a new value of connection to database */
279   void setDatabase(Database *newDb) { db = newDb; }
280 /* retrieves  a database which connected */
281   Database *getDatabase(void) { return db; }
282
283 /* sets a new query string to database server */
284   void setExecSql(const char *newSql) { sql = newSql; }
285 /* retrieves a query string */
286   const char *getExecSql(void) { return sql.c_str(); }
287
288 /* status active is OK query */
289   virtual bool isActive(void) { return active; }
290
291   virtual void setSqlParams(const char *sqlFrmt, sqlType t, ...); 
292
293
294 /* error handling */
295 //  virtual void halt(const char *msg);
296
297 /* last inserted id */
298   virtual int64_t lastinsertid() = 0;
299 /* sequence numbers */
300   virtual long nextid(const char *seq_name)=0;
301 /* sequence numbers */
302   virtual int num_rows()= 0;
303
304 /* Open SQL query */
305   virtual void open(const std::string &sql) = 0;
306   virtual void open() = 0;
307 /* func. executes a query without results to return */
308   virtual int  exec (const std::string &sql) = 0;
309   virtual int  exec() = 0;
310   virtual const void* getExecRes()=0;
311 /* as open, but with our query exept Sql */
312   virtual bool query(const char *sql) = 0;
313 /* Close SQL Query*/
314   virtual void close();
315 /* This function looks for field Field_name with value equal Field_value
316    Returns true if found (position of dataset is set to founded position)
317    and false another way (position is not changed). */
318 //  virtual bool lookup(char *field_name, char*field_value);
319 /* Refresh dataset (reopen it and set the same cursor position) */
320   virtual void refresh();
321
322   /*! \brief Drop an index from the database table, provided it exists.
323    \param table - name of the table the index to be dropped is associated with
324    \param index - name of the index to be dropped
325    \return true when the index is guaranteed to no longer exist in the database.
326    */
327   virtual bool dropIndex(const char *table, const char *index) { return false; }
328
329 /* Go to record No (starting with 0) */
330   virtual bool seek(int pos=0);
331 /* Go to record No (starting with 1) */
332   virtual bool goto_rec(int pos=1);
333 /* Go to the first record in dataset */
334   virtual void first();
335 /* Go to next record in dataset */
336   virtual void next();
337 /* Go to porevious record */
338   virtual void prev();
339 /* Go to last record in dataset */
340   virtual void last();
341
342 /* Check for Ending dataset */
343   virtual bool eof(void) { return feof; }
344 /* Check for Begining dataset */
345   virtual bool bof(void) { return fbof; }
346
347 /* Start the insert mode */
348   virtual void insert();
349 /* Start the insert mode (alias for insert() function) */
350   virtual void append() { insert(); }
351 /* Start the edit mode */
352   virtual void edit();
353
354 /* Add changes, that were made during insert or edit states of dataset into the database */
355   virtual void post();
356 /* Delete statements from database */
357   virtual void deletion();
358 /* Cancel changes, made in insert or edit states of dataset */
359   virtual void cancel() {};
360 /* interupt any pending database operation  */
361         virtual void interrupt() {};
362
363   virtual void setParamList(const ParamList &params);
364   virtual bool locate();
365   virtual bool locate(const ParamList &params);
366   virtual bool findNext();
367
368 /* func. retrieves a number of fields */
369 /* Number of fields in a record */
370   virtual int field_count();                                            
371   virtual int fieldCount();
372 /* func. retrieves a field name with 'n' index */
373   virtual const char *fieldName(int n);
374 /* func. retrieves a field index with 'fn' field name,return -1 when field name not found */
375   virtual int  fieldIndex(const char *fn);
376 /* func. retrieves a field size */
377   virtual int  fieldSize(int n);
378
379
380 /* Set field value */
381   virtual bool set_field_value(const char *f_name, const field_value &value);
382 /* alias for set_field_value */
383   virtual bool sf(const char *f, const field_value &v) { return set_field_value(f,v); }
384
385
386
387 /* Return field name by it index */
388 //  virtual char *field_name(int f_index) { return field_by_index(f_index)->get_field_name(); };
389
390 /* Getting value of field for current record */
391   virtual const field_value get_field_value(const char *f_name);
392   virtual const field_value get_field_value(int index);
393 /* Alias to get_field_value */
394   const field_value fv(const char *f) { return get_field_value(f); }
395   const field_value fv(int index) { return get_field_value(index); }
396
397 /* ------------ for transaction ------------------- */
398   void set_autocommit(bool v) { autocommit = v; }
399   bool get_autocommit() { return autocommit; }
400
401 /* ----------------- for debug -------------------- */
402   Fields *get_fields_object() {return fields_object;};
403   Fields *get_edit_object() {return edit_object;};
404
405 /* --------------- for fast access ---------------- */
406   const result_set& get_result_set() { return result; }
407   const sql_record* const get_sql_record();
408
409  private:
410   void set_ds_state(dsStates new_state) {ds_state = new_state;};        
411  public:
412 /* return ds_state value */
413   dsStates get_state() {return ds_state;};
414
415 /*add a new value to select_sql*/
416   void set_select_sql(const char *sel_sql);
417   void set_select_sql(const std::string &select_sql);
418 /*add a new value to update_sql*/
419   void add_update_sql(const char *upd_sql);
420   void add_update_sql(const std::string &upd_sql);
421 /*add a new value to insert_sql*/
422   void add_insert_sql(const char *ins_sql);
423   void add_insert_sql(const std::string &ins_sql);
424   /*add a new value to delete_sql*/
425   void add_delete_sql(const char *del_sql);
426   void add_delete_sql(const std::string &del_sql);
427
428 /*clear update_sql*/
429   void clear_update_sql();
430 /*clear insert_sql*/
431   void clear_insert_sql();
432 /*clear delete_sql*/
433   void clear_delete_sql();
434
435 /*get value of select_sql*/
436  const char *get_select_sql();
437
438 };
439
440
441
442 /******************** Class DbErrors definition *********************
443
444                            error handling
445
446 ******************************************************************/
447 class DbErrors  {
448
449 public:
450
451 /* constructor */
452   DbErrors();
453   DbErrors(const char *msg, ...);
454
455   const char  * getMsg();
456  private:
457  std::string  msg_;
458 };
459
460 }
461 #endif