StRoot  1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
MysqlDb.h
1 /***************************************************************************
2  *
3  * $Id: MysqlDb.h,v 1.30 2016/05/25 20:17:51 dmitry Exp $
4  *
5  * Author: Laurent Conin
6  ***************************************************************************
7  *
8  * Description: Mysql - SQL Query handler
9  *
10  ***************************************************************************
11  *
12  * $Log: MysqlDb.h,v $
13  * Revision 1.30 2016/05/25 20:17:51 dmitry
14  * coverity - uninit ctor
15  *
16  * Revision 1.29 2012/05/04 17:19:14 dmitry
17  * Part One integration for Hyper Cache. HyperCache added to workflow, but config is set to DISABLE
18  *
19  * Revision 1.28 2011/01/07 18:19:02 dmitry
20  * user name lookup is done once now (for speedup, based on profiler report)
21  *
22  * Revision 1.27 2007/10/29 22:50:56 deph
23  * Abstracted load balancer call from connect to own function called from reconnect
24  * removed extraneuos methods from header
25  *
26  * Revision 1.26 2007/01/09 16:27:39 deph
27  * Updates for load balancing "added 1)write privilege 2)xml comments 3)camelCase notation
28  *
29  * Revision 1.25 2006/08/17 02:58:56 deph
30  * updated load balancer - removing hard-coded nodes from API to xml
31  *
32  * Revision 1.24 2006/06/02 18:23:23 deph
33  * Added an extra machine (db01) for analysis between 11pm and 7am
34  *
35  * Revision 1.22 2005/12/15 03:14:27 jeromel
36  * Mem Leak fixes / Missing delete in new and stream context.
37  *
38  * Revision 1.21 2004/01/15 00:02:24 fisyak
39  * Replace ostringstream => StString, add option for alpha
40  *
41  * Revision 1.20 2003/09/16 22:44:17 porter
42  * got rid of all ostrstream objects; replaced with StString+string.
43  * modified rules.make and added file stdb_streams.h for standalone compilation
44  *
45  * Revision 1.19 2003/09/02 17:57:49 perev
46  * gcc 3.2 updates + WarnOff
47  *
48  * Revision 1.18 2003/07/02 18:39:24 porter
49  * added server version to connection notification and host:port to connection failure notification
50  *
51  * Revision 1.17 2003/04/11 22:47:35 porter
52  * Added a fast multi-row write model specifically needed by the daqEventTag
53  * writer. Speed increased from about 100Hz to ~3000Hz. It is only invoked if
54  * the table is marked as Non-Indexed (daqTags & scalers). For non-indexed tables
55  * which include binary stored data (we don't have any yet), the fast writer has
56  * to invoke a slower buffer so that the rates are a bit slower (~500Hz at 50 rows/insert).
57  *
58  * Revision 1.16 2002/03/22 19:05:38 porter
59  * #-of-retries on server connect increased to 7 with timeout period doubled per
60  * retry starting at 1 sec. DOES NOT work (is ignored) on STAR's Redhat 6.2
61  * version of mysqlclient but does on Redhat 7.2. Needed for maintainable
62  * multiple mirror servers using dns for round-robin load balancing.
63  *
64  * Revision 1.15 2002/01/30 15:40:47 porter
65  * changed limits on flavor tag & made defaults retrieving more readable
66  *
67  * Revision 1.14 2001/10/24 04:05:08 porter
68  * added long long type to I/O and got rid of obsolete dataIndex table
69  *
70  * Revision 1.13 2001/04/25 17:17:33 perev
71  * HPcorrs
72  *
73  * Revision 1.12 2001/03/30 18:48:26 porter
74  * modified code to keep Insure from wigging-out on ostrstream functions.
75  * moved some messaging into a StDbSql method.
76  *
77  * Revision 1.11 2001/02/09 23:06:24 porter
78  * replaced ostrstream into a buffer with ostrstream creating the
79  * buffer. The former somehow clashed on Solaris with CC5 iostream (current .dev)
80  *
81  * Revision 1.10 2001/01/22 18:37:50 porter
82  * Update of code needed in next year running. This update has little
83  * effect on the interface (only 1 method has been changed in the interface).
84  * Code also preserves backwards compatibility so that old versions of
85  * StDbLib can read new table structures.
86  * -Important features:
87  * a. more efficient low-level table structure (see StDbSql.cc)
88  * b. more flexible indexing for new systems (see StDbElememtIndex.cc)
89  * c. environment variable override KEYS for each database
90  * d. StMessage support & clock-time logging diagnostics
91  * -Cosmetic features
92  * e. hid stl behind interfaces (see new *Impl.* files) to again allow rootcint access
93  * f. removed codes that have been obsolete for awhile (e.g. db factories)
94  * & renamed some classes for clarity (e.g. tableQuery became StDataBaseI
95  * and mysqlAccessor became StDbSql)
96  *
97  * Revision 1.9 2000/03/01 20:56:15 porter
98  * 3 items:
99  * 1. activated reConnect for server timeouts
100  * 2. activated connection sharing; better resource utilization but poorer
101  * logging
102  * 3. made rollback method in mysqlAccessor more robust (affects writes only)
103  *
104  * Revision 1.8 2000/02/18 16:58:09 porter
105  * optimization of table-query, + whereClause gets timeStamp if indexed
106  * + fix to write multiple rows algorithm
107  *
108  * Revision 1.7 2000/02/15 20:27:43 porter
109  * Some updates to writing to the database(s) via an ensemble (should
110  * not affect read methods & haven't in my tests.
111  * - closeAllConnections(node) & closeConnection(table) method to mgr.
112  * - 'NullEntry' version to write, with setStoreMode in table;
113  * - updated both StDbTable's & StDbTableDescriptor's copy-constructor
114  *
115  * Revision 1.6 2000/01/27 05:54:32 porter
116  * Updated for compiling on CC5 + HPUX-aCC + KCC (when flags are reset)
117  * Fixed reConnect()+transaction model mismatch
118  * added some in-code comments
119  *
120  * Revision 1.5 2000/01/10 20:37:53 porter
121  * expanded functionality based on planned additions or feedback from Online work.
122  * update includes:
123  * 1. basis for real transaction model with roll-back
124  * 2. limited SQL access via the manager for run-log & tagDb
125  * 3. balance obtained between enumerated & string access to databases
126  * 4. 3-levels of diagnostic output: Quiet, Normal, Verbose
127  * 5. restructured Node model for better XML support
128  *
129  * Revision 1.4 1999/10/19 14:30:37 porter
130  * modifications relevant to use with StDbBroker and future merging with
131  * "params" database structure + some docs + suppressing diagnostics messages
132  *
133  * Revision 1.3 1999/09/30 02:06:00 porter
134  * add StDbTime to better handle timestamps, modify SQL content (mysqlAccessor)
135  * allow multiple rows (StDbTable), & Added the comment sections at top of
136  * each header and src file
137  *
138  **************************************************************************/
139 #ifndef MYSQDB_HH
140 #define MYSQDB_HH
141 #ifndef __CINT__
142 #include "mysql.h"
143 #else
144 typedef char MYSQL_RES;
145 typedef char MYSQL_ROW;
146 typedef char MYSQL;
147 typedef int MYSQL_FIELD;
148 #endif
149 
150 #include "stdb_streams.h"
151 #include "StDbBuffer.h"
152 #include "StDbLogger.hh"
153 #include "parseXmlString.hh"
154 #include "StDbManagerImpl.hh"
155 #include "StHyperCacheManager.h"
156 
157 #include <string>
158 
159 #ifdef HPUX
160 #define freeze(i) str()
161 #endif
162 
163 #define endsql ";"
164 
165 
166 class StDbBuffer;
167 
168 class MysqlResult {
169 
170 private:
171  MYSQL_RES * mRes;
172  MYSQL_ROW mRow;
173  char mSep = '\0';
174 
175 public:
176  MysqlResult() {mRes=0;};
177  // virtual char float* NextRowBin();
178  //virtual void Set(const MYSQL_RES *aPnt) {mRes=aPnt;};
179  virtual unsigned NbRows () {return mysql_num_rows(mRes);};
180  virtual unsigned NbFields () {return mysql_num_fields(mRes);};
181  virtual void Release () {if(mRes)mysql_free_result(mRes);mRes=0;};
182  MysqlResult &operator++() {mRow=mysql_fetch_row(mRes);return *this;};
183  // MysqlResult &operator >>(char *aString);
184 
185  protected:
186 
187  friend class MysqlDb;
188 };
189 
190 class MysqlBin{
191 
192 private:
193  char *mBinData;
194  unsigned long int mLen;
195 
196 public:
197  MysqlBin() {mBinData=0;mLen=0;};
198  virtual void Input(const unsigned long int aLen,char *aBin)
199  {mBinData=aBin;mLen=aLen;};
200 
201  friend class MysqlDb;
202 };
203 
204 
205 class MysqlDb{
206 
207 private:
208 
209  MYSQL mData;
210  char* mQuery;
211  unsigned long int mQueryLen;
212  char* mQueryLast; // for printing query after execution
213  MysqlResult* mRes;
214  bool mqueryState;
215  bool mhasConnected;
216  bool mhasBinaryQuery;
217 
218  char* mdbhost;
219  char* mdbName;
220  char* mdbuser;
221  char* mdbpw;
222  int mdbPort;
223  char* mdbServerVersion;
224 
225  std::string mSysusername;
226 
227  unsigned int mtimeout; // wait time between connection tries
228 
229 
230  // these are specific for fast multi-row writes of non-indexed tables
231  int jfields;
232  char* cnames[200];
233  bool isBlob[200];
234  bool isBinary[200];
235  bool isSpecialType[200];
236  bool loadBalance();
237 
238 public:
239 
240  // for logging times
241  bool mlogTime;
242  StDbLogger mqueryLog;
243  StDbLogger msocketLog;
244  StDbLogger mconnectLog;
245 
246  MysqlDb();
247  virtual ~MysqlDb();
248  virtual bool Connect(const char *aHost, const char *aUser,
249  const char *aPasswd, const char *aDb, const int aPort=0);
250  virtual bool reConnect();
251 
252  virtual unsigned NbRows() {
253  if (mqueryState) {
254  if (m_Mgr.isActive() && m_Mgr.isValueFound()) { return m_Mgr.getNumRows(); }
255  return mRes->NbRows();
256  };
257  return 0;
258  };
259 
260  virtual unsigned NbFields() {
261  if (mqueryState) {
262  if (m_Mgr.isActive() && m_Mgr.isValueFound()) { return m_Mgr.getNumFields(); }
263  return mRes->NbFields();
264  };
265  return 0;
266  };
267 
268  virtual void Release() {mRes->Release();};
269 
270  virtual char* printQuery();
271  // virtual char* LastQuery();
272 
273  // these 3 meths are specific for fast multi-row writes of non-index tables
274  virtual bool InputStart(const char *aName,StDbBuffer *aBuff, const char* colList, int nRows, bool& hasBinary);
275  virtual bool InputRow(StDbBuffer* aBuff, int row);
276  virtual bool InputEnd();
277 
278 
279  virtual bool Input(const char *aName,StDbBuffer *aBuff);
280  //virtual bool InitBuff(StDbBuffer *aBuff);
281  virtual bool Output(StDbBuffer *aBuff);
282  MysqlDb &operator<<(const char *c);
283  MysqlDb &operator<<(const string s);
284  MysqlDb &operator<<(const MysqlBin *aBin);
285 
286  MysqlDb &operator<<(const short aq);
287  MysqlDb &operator<<(const unsigned short aq);
288  MysqlDb &operator<<(const int aq);
289  MysqlDb &operator<<(const unsigned int aq);
290  MysqlDb &operator<<(const long long aq);
291  MysqlDb &operator<<(const float aq);
292  MysqlDb &operator<<(const double aq);
293 
294  char **DecodeStrArray(char* strinput , int &aLen) ;
295  char* CodeStrArray(char** strarr , int aLen);
296  virtual int GetLastInsertID(){ return (int)mysql_insert_id(&mData);}
297  virtual bool QueryStatus() { return mqueryState; }
298  virtual bool checkForTable(const char* tableName);
299  virtual void Close();
300  virtual bool IsConnected() { return mhasConnected; }
301  virtual bool setDefaultDb(const char* dbName);
302 
303  StDbManagerImpl* my_manager; // need access to the list of servers and their properties for load balancing
304 
305 protected:
306  virtual void RazQuery() ;
307  virtual bool ExecQuery();
308 
309  StHyperCacheManager m_Mgr;
310 
311  //virtual column* NextRow();
312  //virtual column* PrepareWrite();
313  //virtual void Print() {cout << mQueryMess << "|" <<mQueryLast <<endl;}; // debug
314  //virtual void Out(); //debug
315  //virtual MysqlResult* Result() { return mRes;}; //debug
316 
317  //ClassDef(MysqlDb,0)
318 
319 };
320 
321 inline void MysqlDb::Close(){
322  if(mhasConnected)mysql_close(&mData);
323  mhasConnected=false;
324 }
325 
326 inline MysqlDb &MysqlDb::operator<<( const string s){
327  return *this<<s.c_str();
328 }
329 
330 inline MysqlDb &MysqlDb::operator<<( const short aq){
331  StString ts; ts<<aq;
332  return *this<<ts.str();
333 }
334 
335 inline MysqlDb &MysqlDb::operator<<( const unsigned short aq){
336  StString ts; ts<<aq;
337  return *this<<ts.str();
338 }
339 
340 inline MysqlDb &MysqlDb::operator<<( const int aq){
341  StString ts; ts<<aq;
342  return *this<<ts.str();
343 }
344 
345 inline MysqlDb &MysqlDb::operator<<( const unsigned int aq){
346  StString ts; ts<<aq;
347  return *this<<ts.str();
348 }
349 
350 inline MysqlDb &MysqlDb::operator<<( const long long aq){
351  StString ts; ts<<aq;
352  return *this<<ts.str();
353 }
354 
355 inline MysqlDb &MysqlDb::operator<<( const float aq){
356  StString ts; ts<<aq;
357  return *this<<ts.str();
358 }
359 
360 inline MysqlDb &MysqlDb::operator<<( const double aq){
361  StString ts; ts<<aq;
362  return *this<<ts.str();
363 }
364 
365 
366 extern const MysqlBin *Binary(const unsigned long int aLen,const float *aBin);
367 //extern MysqlBin *Binary(const unsigned long int aLen,const char *aBin);
368 #endif
369 
370 
371 
372 
373 
374 
375