1 /**********************************************************************
2 * Copyright (c) 2002, Leo Seib, Hannover
4 * Project:Dataset C++ Dynamic Library
5 * Module: Dataset abstraction layer header file
6 * Author: Leo Seib E-Mail: leoseib@web.de
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:
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
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
27 **********************************************************************/
44 class Dataset; // forward declaration of class Dataset
47 #define S_NO_CONNECTION "No active connection";
49 #define DB_BUFF_MAX 8*1024 // Maximum buffer's capacity
51 #define DB_CONNECTION_NONE 0
52 #define DB_CONNECTION_OK 1
53 #define DB_CONNECTION_BAD 2
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
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
63 /******************* Class Database definition ********************
65 represents connection with database server;
67 ******************************************************************/
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
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(); }
88 void setPort(const char *newPort) { port = newPort; }
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; }
98 const char *getLogin(void) const { return login.c_str(); }
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) {
117 ciphers = newCiphers;
120 /* virtual methods that must be overloaded in derived classes */
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(); }
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;
138 /* \brief copy database */
139 virtual int copy(const char *new_name) { return -1; }
141 /* \brief drop all extra analytics from database */
142 virtual int drop_analytics(void) { return -1; }
144 virtual bool exists(void) { return false; }
146 /* virtual methods for transaction */
148 virtual void start_transaction() {};
149 virtual void commit_transaction() {};
150 virtual void rollback_transaction() {};
152 /* virtual methods for formatting */
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.
159 virtual std::string prepare(const char *format, ...);
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.
166 virtual std::string vprepare(const char *format, va_list args) = 0;
168 virtual bool in_transaction() {return false;};
175 /******************* Class Dataset definition *********************
177 global abstraction for using Databases
179 ******************************************************************/
181 // define Dataset States type
182 enum dsStates { dsSelect, dsInsert, dsEdit, dsUpdate, dsDelete, dsInactive };
183 enum sqlType {sqlSelect,sqlUpdate,sqlInsert,sqlDelete,sqlExec};
186 typedef std::list<std::string> StringList;
187 typedef std::map<std::string,field_value> ParamList;
192 /* char *Host = ""; //WORK_HOST;
193 char *Database = ""; //WORK_DATABASE;
194 char *User = ""; //WORK_USER;
195 char *Password = ""; //WORK_PASSWORD;
198 Database *db; // info about db connection
199 dsStates ds_state; // current state
200 Fields *fields_object, *edit_object;
208 bool active; // Is Query Opened?
210 int frecno; // number of current row bei bewegung
213 ParamList plist; // Paramlist for locate
215 bool autocommit; // for transactions
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
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
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) */
230 StringList insert_sql; // May be an array in complex queries
231 /* Field values for inserting must has prefix :NEW_ and field name
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) */
237 StringList delete_sql; // May be an array in complex queries
238 /* Field values for deleing must has prefix :OLD_ and field name
240 delete from wt_story where idobject=:OLD_idobject
241 Essentually field idobject must present in the
242 result set (select_sql statement) */
247 /* Arrays for searching */
248 // StringList names, values;
251 /* Makes direct inserts into database via mysql_query function */
252 virtual void make_insert() = 0;
254 virtual void make_edit() = 0;
256 virtual void make_deletion() = 0;
258 /* This function works only with MySQL database
259 Filling the fields information from select statement */
260 virtual void fill_fields(void)=0;
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);
265 /* Returns old field value (for :OLD) */
266 virtual const field_value f_old(const char *f);
270 virtual int str_compare(const char * s1, const char * s2);
273 Dataset(Database *newDb);
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; }
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(); }
288 /* status active is OK query */
289 virtual bool isActive(void) { return active; }
291 virtual void setSqlParams(const char *sqlFrmt, sqlType t, ...);
295 // virtual void halt(const char *msg);
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;
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;
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();
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.
327 virtual bool dropIndex(const char *table, const char *index) { return false; }
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 */
337 /* Go to porevious record */
339 /* Go to last record in dataset */
342 /* Check for Ending dataset */
343 virtual bool eof(void) { return feof; }
344 /* Check for Begining dataset */
345 virtual bool bof(void) { return fbof; }
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 */
354 /* Add changes, that were made during insert or edit states of dataset into the database */
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() {};
363 virtual void setParamList(const ParamList ¶ms);
364 virtual bool locate();
365 virtual bool locate(const ParamList ¶ms);
366 virtual bool findNext();
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);
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); }
387 /* Return field name by it index */
388 // virtual char *field_name(int f_index) { return field_by_index(f_index)->get_field_name(); };
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); }
397 /* ------------ for transaction ------------------- */
398 void set_autocommit(bool v) { autocommit = v; }
399 bool get_autocommit() { return autocommit; }
401 /* ----------------- for debug -------------------- */
402 Fields *get_fields_object() {return fields_object;};
403 Fields *get_edit_object() {return edit_object;};
405 /* --------------- for fast access ---------------- */
406 const result_set& get_result_set() { return result; }
407 const sql_record* const get_sql_record();
410 void set_ds_state(dsStates new_state) {ds_state = new_state;};
412 /* return ds_state value */
413 dsStates get_state() {return ds_state;};
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);
429 void clear_update_sql();
431 void clear_insert_sql();
433 void clear_delete_sql();
435 /*get value of select_sql*/
436 const char *get_select_sql();
442 /******************** Class DbErrors definition *********************
446 ******************************************************************/
453 DbErrors(const char *msg, ...);
455 const char * getMsg();