/[PAMELA software]/YodaProfiler/src/PamelaDBOperations.cpp
ViewVC logotype

Diff of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.5 by pam-fi, Fri Sep 8 14:42:48 2006 UTC revision 1.17 by mocchiut, Tue Nov 7 12:17:45 2006 UTC
# Line 15  Line 15 
15  #include <TTree.h>  #include <TTree.h>
16  #include <TGraph.h>  #include <TGraph.h>
17  #include <TDatime.h>  #include <TDatime.h>
18    #include <TTimeStamp.h>
19  #include <TF1.h>  #include <TF1.h>
20  //  //
21  #include <EventHeader.h>  #include <EventHeader.h>
# Line 31  Line 32 
32  #include <varDump/VarDumpRecord.h>  #include <varDump/VarDumpRecord.h>
33  #include <physics/S4/S4Event.h>  #include <physics/S4/S4Event.h>
34  //  //
35    #include <sgp4.h>
36    
37  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
38  //  //
39  using namespace std;  using namespace std;
40  using namespace pamela;  using namespace pamela;
41    
42    // Some function to work with cTle stuff.
43    bool compTLE(cTle* tle1, cTle *tle2);
44    float getTleJulian(cTle *);
45    string getTleDatetime(cTle*);
46    
47  /**  /**
48   * Constructor.   * Constructor.
49   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 47  using namespace pamela; Line 55  using namespace pamela;
55   * @param obt0         file obt0.   * @param obt0         file obt0.
56   * @param tsync        file timesync.   * @param tsync        file timesync.
57   * @param debug        debug flag.   * @param debug        debug flag.
58     * @param tlefilename  ascii file with TLE 3 line elements.
59   */   */
60  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename){
61    //    //
62    //    //
63    SetConnection(host,user,password);    SetConnection(host,user,password);
# Line 62  PamelaDBOperations::PamelaDBOperations(T Line 71  PamelaDBOperations::PamelaDBOperations(T
71    SetTsync(tsync);    SetTsync(tsync);
72    SetObt0(obt0);    SetObt0(obt0);
73    //    //
74      SetTLEPath(tlefilename);
75    //    //
   SetRootName(filerootname);  
   SetRawName(filerawname);  
76    //    //
77    this->OpenFile();    INSERT_RAW =!filerawname.IsNull();
78      if(INSERT_RAW)SetRawName(filerawname);
79      //
80      INSERT_ROOT = !filerootname.IsNull();
81      if( INSERT_ROOT ){
82        this->SetRootName(filerootname);
83        this->SetOrbitNo();
84        file = TFile::Open(this->GetRootName().Data());
85      } else {
86        this->SetRootName("");
87      };
88    //    //
89    this->SetID_RAW(0);    this->SetID_RAW(0);
90    this->SetID_ROOT(0);    this->SetID_ROOT(0);
91    
92      VALIDATE = false;
93      
94    //    //
95  };  };
96    
# Line 78  PamelaDBOperations::PamelaDBOperations(T Line 99  PamelaDBOperations::PamelaDBOperations(T
99   */   */
100  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
101    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
102      delete clean_time;
103    delete glrun;    delete glrun;
104    delete this;    delete this;
105  };  };
# Line 86  void PamelaDBOperations::Close(){ Line 108  void PamelaDBOperations::Close(){
108  // SETTERS  // SETTERS
109  //  //
110    
111    //
112    // must be out of the constructor in order to FORCE the validation of the latest runs in case you run the validation together with the latest file
113    //
114    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
115      clean_time = new TDatime();
116      //
117      if(olderthan >= 0){
118        VALIDATE = true;
119        UInt_t timelim = 0;
120        timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
121        clean_time->Set(timelim,false);
122      };
123    };
124    
125  /**  /**
126   * Open the DB connection   * Open the DB connection
127   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 93  void PamelaDBOperations::Close(){ Line 129  void PamelaDBOperations::Close(){
129   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
130   */   */
131  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
132      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
133    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
134  };  };
135    
# Line 121  void PamelaDBOperations::SetDebugFlag(Bo Line 158  void PamelaDBOperations::SetDebugFlag(Bo
158  };  };
159    
160  /**  /**
161     * Set the nofrag flag
162     *
163     */
164    void PamelaDBOperations::SetNoFrag(Bool_t nf){
165      NOFRAG = nf;
166    };
167    
168    /**
169   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
170   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
171   */   */
# Line 161  void PamelaDBOperations::SetRootName(TSt Line 206  void PamelaDBOperations::SetRootName(TSt
206  };  };
207    
208  /**  /**
209     * Store the downlink orbit number from filename.
210     */
211    void PamelaDBOperations::SetOrbitNo(){
212      dworbit = 0;
213      TString name = this->GetRootFile();
214      Int_t nlength = name.Length();
215      if ( nlength < 5 ) return;
216      TString dwo = 0;
217      for (Int_t i = 0; i<5; i++){
218        dwo.Append(name[i],1);
219      };
220      if ( dwo.IsDigit() ){
221        dworbit = (UInt_t)dwo.Atoi();
222      } else {
223        dwo="";
224        for (Int_t i = 8; i<13; i++){
225          dwo.Append(name[i],1);
226        };    
227        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
228      };
229      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
230      return;
231    };
232    
233    
234    
235    /**
236   * Store the NOBOOT flag.   * Store the NOBOOT flag.
237   * @param noboot    true/false.   * @param noboot    true/false.
238   */   */
# Line 169  void PamelaDBOperations::SetNOBOOT(Bool_ Line 241  void PamelaDBOperations::SetNOBOOT(Bool_
241  };  };
242    
243  /**  /**
244     * Store path to the TLE file.
245     */
246    void PamelaDBOperations::SetTLEPath(TString str){
247      tlefilename = str;
248    };
249    
250    /**
251   * Store the olderthan variable   * Store the olderthan variable
252   * @param olderthan   * @param olderthan
253   */   */
254  void PamelaDBOperations::SetOlderThan(Long64_t oldthan){  // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
255    olderthan = oldthan;  //   olderthan = oldthan;
256  };  // };
257    
258  /**  /**
259   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
# Line 225  Int_t PamelaDBOperations::SetUpperLimits Line 304  Int_t PamelaDBOperations::SetUpperLimits
304    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
305    EventCounter *code=0;    EventCounter *code=0;
306    //    //
307      UInt_t deltapkt = 5000;
308      ULong64_t deltaobt = 50000;
309      //
310    //   pcksList packetsNames;    //   pcksList packetsNames;
311    //   pcksList::iterator Iter;    //   pcksList::iterator Iter;
312    //   getPacketsNames(packetsNames);    //   getPacketsNames(packetsNames);
# Line 271  Int_t PamelaDBOperations::SetUpperLimits Line 353  Int_t PamelaDBOperations::SetUpperLimits
353    //    //
354    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
355    //    //
356    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) ){
357        //
358      // go back      // go back
359      zomp = nevent - 2;      zomp = nevent - 2;
360      //      //
# Line 320  Int_t PamelaDBOperations::SetUpperLimits Line 403  Int_t PamelaDBOperations::SetUpperLimits
403    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
404    //    //
405    PacketType *pctp=0;    PacketType *pctp=0;
   T->GetEntry(upperentry);  
   code = eh->GetCounter();  
   Int_t lasttrail = code->Get(pctp->RunTrailer);  
   Int_t lasthead = code->Get(pctp->RunHeader);  
406    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
407    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
408    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 346  Int_t PamelaDBOperations::SetUpperLimits Line 425  Int_t PamelaDBOperations::SetUpperLimits
425    UInt_t pkth = 0;    UInt_t pkth = 0;
426    ULong64_t obth = 0;    ULong64_t obth = 0;
427    //    //
428      T->GetEntry(upperentry);
429      code = eh->GetCounter();
430      Int_t lasttrail = code->Get(pctp->RunTrailer);
431      Int_t lasthead = code->Get(pctp->RunHeader);
432    if ( lasttrail < rtev ){    if ( lasttrail < rtev ){
433      rt->GetEntry(lasttrail);      rt->GetEntry(lasttrail);
434      pht = eht->GetPscuHeader();      pht = eht->GetPscuHeader();
# Line 356  Int_t PamelaDBOperations::SetUpperLimits Line 439  Int_t PamelaDBOperations::SetUpperLimits
439    if ( lasthead < rhev ){    if ( lasthead < rhev ){
440      rh->GetEntry(lasthead);      rh->GetEntry(lasthead);
441      phh = ehh->GetPscuHeader();      phh = ehh->GetPscuHeader();
442      pkth = PKT(pht->GetCounter());      pkth = PKT(phh->GetCounter());
443      obth = OBT(pht->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
444    };    };
445    //    //
446    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
# Line 401  Int_t PamelaDBOperations::SetUpperLimits Line 484  Int_t PamelaDBOperations::SetUpperLimits
484      pkth = PKT(phh->GetCounter());      pkth = PKT(phh->GetCounter());
485      obth = OBT(phh->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
486      //      //
487    //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
488        //
489      if ( pkth < spkth && obth < sobth ){      if ( pkth < spkth && obth < sobth ){
       if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);  
490        if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);        if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
491        //        //
492        rhev--;        rhev = k-1;
493        rh->GetEntry(rhev);        rh->GetEntry(rhev);
494        pkth = spkth;        pkth = spkth;
495        obth = sobth;        obth = sobth;
       if ( IsDebug() ) printf(" lasthead %i pt %i p1 %i ot %u o1 %u \n",rhev,pkth,spkth,obth,sobth);  
496        //        //
497        UInt_t evbefh = 0;        UInt_t evbefh = 0;
498        code = ehh->GetCounter();        code = ehh->GetCounter();
# Line 419  Int_t PamelaDBOperations::SetUpperLimits Line 502  Int_t PamelaDBOperations::SetUpperLimits
502          ph = eh->GetPscuHeader();          ph = eh->GetPscuHeader();
503          t_pktlast = PKT(ph->GetCounter());          t_pktlast = PKT(ph->GetCounter());
504          t_obtlast = OBT(ph->GetOrbitalTime());          t_obtlast = OBT(ph->GetOrbitalTime());
505          if ( t_pktlast < spkth && t_obtlast < sobth ){ // jump          if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
506            upperpkt = pkth;            upperpkt = pkth;
507            upperobt = obth;            upperobt = obth;
508            upperentry = evbefh-1;            upperentry = evbefh-1;
# Line 439  Int_t PamelaDBOperations::SetUpperLimits Line 522  Int_t PamelaDBOperations::SetUpperLimits
522          };              };    
523        };        };
524        if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);        if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
525          goto kikko0;
526      };      };
527    };    };
528     kikko0:
529    //    //
530    //    //
531    //    //
# Line 458  Int_t PamelaDBOperations::SetUpperLimits Line 543  Int_t PamelaDBOperations::SetUpperLimits
543      pktt = PKT(pht->GetCounter());      pktt = PKT(pht->GetCounter());
544      obtt = OBT(pht->GetOrbitalTime());      obtt = OBT(pht->GetOrbitalTime());
545      //      //
546    //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
547        //
548      if ( pktt < spktt && obtt < sobtt ){      if ( pktt < spktt && obtt < sobtt ){
       if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
549        if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);        if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
550        //        //
551        rtev--;        rtev = k-1;
552        rt->GetEntry(rtev);        rt->GetEntry(rtev);
553        pktt = spktt;        pktt = spktt;
554        obtt = sobtt;        obtt = sobtt;
# Line 476  Int_t PamelaDBOperations::SetUpperLimits Line 562  Int_t PamelaDBOperations::SetUpperLimits
562          ph = eh->GetPscuHeader();          ph = eh->GetPscuHeader();
563          t_pktlast = PKT(ph->GetCounter());          t_pktlast = PKT(ph->GetCounter());
564          t_obtlast = OBT(ph->GetOrbitalTime());          t_obtlast = OBT(ph->GetOrbitalTime());
565          if ( t_pktlast < spktt && t_obtlast < sobtt ){ // jump          if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
566            upperpkt = pktt;            upperpkt = pktt;
567            upperobt = obtt;            upperobt = obtt;
568            upperentry = evbeft-1;            upperentry = evbeft-1;
# Line 496  Int_t PamelaDBOperations::SetUpperLimits Line 582  Int_t PamelaDBOperations::SetUpperLimits
582          };          };
583        };        };
584        if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);        if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
585        break;        goto kikko;
586          //      break;
587        //        //
588      };      };
589      //        //  
590    };    };
591    //    //
592    // kikko:   kikko:
593      //
594      T->GetEntry(upperentry);
595      code = eh->GetCounter();
596      lasttrail = code->Get(pctp->RunTrailer);
597      lasthead = code->Get(pctp->RunHeader);
598      if ( lasttrail < rtev ){
599        rt->GetEntry(lasttrail);
600        pht = eht->GetPscuHeader();
601        pktt = PKT(pht->GetCounter());
602        obtt = OBT(pht->GetOrbitalTime());
603      };
604      //
605      if ( lasthead < rhev ){
606        rh->GetEntry(lasthead);
607        phh = ehh->GetPscuHeader();
608        pkth = PKT(phh->GetCounter());
609        obth = OBT(phh->GetOrbitalTime());
610      };
611      //
612      if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
613      if ( pkth > upperpkt && obth > upperobt ){
614        if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);
615        upperpkt = pkth;
616        upperobt = obth;
617        rhev = lasthead+1;
618      } else {
619        rhev = lasthead;
620      };
621      if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);
622      //
623      if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
624      if ( pktt > upperpkt && obtt > upperobt ){
625        if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);
626        upperpkt = pktt;
627        upperobt = obtt;
628        rtev = lasttrail+1;
629      } else {
630        rtev = lasttrail;
631      };
632      if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);
633    //    //
634    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);
635    //    //
636    return(0);    return(0);
637  }  }
638    
639    /**
640     *
641     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
642     * Entries in the _RUNID_GEN table are never deleted.
643     *
644     **/
645    UInt_t PamelaDBOperations::AssignRunID(){
646      //
647      TSQLResult *result = 0;
648      TSQLRow *row = 0;
649      UInt_t runid = 0;
650      //
651      stringstream   oss;
652      //  
653      oss.str("");
654      oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
655      result = conn->Query(oss.str().c_str());
656      if ( !result ) throw -10;
657      oss.str("");
658      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
659      result = conn->Query(oss.str().c_str());
660      if ( !result ) throw -10;
661      //
662      row = result->Next();
663      //
664      if ( !row ) throw -28;
665      //
666      runid = (UInt_t)atoll(row->GetField(0));
667      //
668      return(runid);
669    };
670    
671  //  //
672  // GETTERS  // GETTERS
673  //  //
# Line 584  const PacketType* PamelaDBOperations::Ge Line 743  const PacketType* PamelaDBOperations::Ge
743  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
744  //  //
745    
746  /**  // /**
747   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
748   */  // */
749  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
750    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
751    //   //
752    
753    void PamelaDBOperations::CheckFile(){  
754      if ( !file ) throw -12;
755  };  };
756    
757    
758  /**  /**
759   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
760   */   */
761  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
762    //    //
763    // check connection    // check connection
764    //    //
765    if( !conn ) throw -1;        if( !conn ) throw -1;
766    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
767    if( !connect ) throw -1;        if( !connect ) throw -1;
768      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
769      //
770      // set DB timezone to UTC
771      //
772      stringstream   oss;
773      //  
774      oss.str("");
775      oss << "SET time_zone='+0:00';";
776      conn->Query(oss.str().c_str());
777      //
778  };  };
779    
780  /**  /**
# Line 783  Int_t PamelaDBOperations::insertPamelaGL Line 954  Int_t PamelaDBOperations::insertPamelaGL
954    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
955    //    //
956    oss.str("");    oss.str("");
957    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ID_RAW<= "    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
958        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
959    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
960    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
961    if ( !result ) throw -10;    if ( !result ) throw -10;
962    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
963    //    //
964    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
965        oss.str("");
966        oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
967            << dworbit << " order by FROM_ORBIT desc limit 1;";
968        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
969        result = conn->Query(oss.str().c_str());
970        if ( !result ) throw -10;
971        row = result->Next();
972        if ( !row ) throw -10;
973      };
974      //
975      TDatime ti = TDatime(row->GetField(0));
976      TTimeStamp tu = TTimeStamp((UInt_t)ti.GetYear(),(UInt_t)ti.GetMonth(),(UInt_t)ti.GetDay(),(UInt_t)ti.GetHour(),(UInt_t)ti.GetMinute(),(UInt_t)ti.GetSecond(),0,true,0);
977      t0 = (UInt_t)tu.GetSec();
978      //
979      //  t0 = (UInt_t)TDatime(row->GetField(0)).Convert();
980    /*    /*
981     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
982     */     */
# Line 864  Int_t PamelaDBOperations::insertPamelaGL Line 1048  Int_t PamelaDBOperations::insertPamelaGL
1048          //          //
1049          TYPE = 55;//224;          TYPE = 55;//224;
1050          //          //
1051            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1052            //
1053          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1054            existsts = true;            existsts = true;
1055            goto eout;            goto eout;
# Line 886  Int_t PamelaDBOperations::insertPamelaGL Line 1072  Int_t PamelaDBOperations::insertPamelaGL
1072      //      //
1073      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1074      //      //
1075      if ( rhev > 0 ){      Int_t nrhev = rh->GetEntries();
1076        rh->GetEntry(0);      Int_t nrtev = rt->GetEntries();
1077        //      if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1078        TSYNC = runh->LAST_TIME_SYNC_INFO;      //
1079        OBT = runh->OBT_TIME_SYNC * 1000;      if ( nrhev > 0 ){
1080        //        for (Int_t i=0; i<nrhev; i++){
1081        TYPE = 20;          //
1082        //          rh->GetEntry(i);
1083        if ( TSYNC && OBT ){          //
1084          existsts = true;          TSYNC = runh->LAST_TIME_SYNC_INFO;
1085          goto eout;          OBT = runh->OBT_TIME_SYNC * 1000;
1086            //
1087            TYPE = 20;
1088            //
1089            if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1090            //
1091            if ( TSYNC && OBT ){
1092              existsts = true;
1093              goto eout;
1094            };
1095        };        };
1096        //        //
1097      };      };
1098      if ( rtev > 0 ){      if ( nrtev > 0 ){
1099        //        //
1100        if ( IsDebug() ) printf(" No runheader \n");        if ( IsDebug() ) printf(" No runheader \n");
1101        signal = 6;        signal = 6;
1102        //        //
1103        rt->GetEntry(0);        for (Int_t i=0; i<nrtev; i++){
1104        //          //
1105        TSYNC = runt->LAST_TYME_SYNC_INFO;          rt->GetEntry(i);
1106        OBT = runt->OBT_TYME_SYNC * 1000;          //
1107        //          TSYNC = runt->LAST_TYME_SYNC_INFO;
1108        TYPE = 21;          OBT = runt->OBT_TYME_SYNC * 1000;
1109        //          //
1110        if ( TSYNC && OBT ){          TYPE = 21;
1111          existsts = true;          //
1112          goto eout;          if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1113            //
1114            if ( TSYNC && OBT ){
1115              existsts = true;
1116              goto eout;
1117            };
1118        };        };
1119        //        //
1120      } else {      } else {
# Line 1381  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1581  Bool_t PamelaDBOperations::IsRunAlreadyI
1581      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1582        //        //
1583        if ( IsDebug() ) printf(" The new run has more events than the old one \n");        if ( IsDebug() ) printf(" The new run has more events than the old one \n");
1584        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1585        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1586        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1587        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1588    //       conn->Query(oss.str().c_str());
1589        if ( signal ) signal = false;        if ( signal ) signal = false;
1590        goto gonext;              goto gonext;      
1591        //        //
# Line 1398  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1599  Bool_t PamelaDBOperations::IsRunAlreadyI
1599        //        //
1600        if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");        if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
1601        //        //
1602        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1603        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1604        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1605        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1606    //       conn->Query(oss.str().c_str());
1607        //        //
1608        if ( signal ) signal = false;        if ( signal ) signal = false;
1609        goto gonext;        goto gonext;
# Line 1415  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1617  Bool_t PamelaDBOperations::IsRunAlreadyI
1617        //        //
1618        if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");        if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
1619        //        //
1620        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1621        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1622        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1623        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1624    //       conn->Query(oss.str().c_str());
1625        if ( signal ) signal = false;        if ( signal ) signal = false;
1626        //        //
1627      };      };
# Line 1454  void PamelaDBOperations::HandleRun(){   Line 1657  void PamelaDBOperations::HandleRun(){  
1657      //      //
1658      this->FillClass();      this->FillClass();
1659      //      //
1660      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1661          glrun->SetID(this->AssignRunID());
1662          glrun->SetID_RUN_FRAG(0);
1663          glrun->Fill_GL_RUN(conn);
1664        };
1665    } else {    } else {
1666      //      //
1667      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
# Line 1477  void PamelaDBOperations::HandleRunFragme Line 1684  void PamelaDBOperations::HandleRunFragme
1684    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1685    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1686    Bool_t found = false;    Bool_t found = false;
1687      Bool_t foundinrun = false;
1688    //    //
1689    TSQLResult *result = 0;    TSQLResult *result = 0;
1690    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1503  void PamelaDBOperations::HandleRunFragme Line 1711  void PamelaDBOperations::HandleRunFragme
1711    //    //
1712    if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");    if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
1713    //    //
1714      // First of all insert the run in the fragment table...
1715      //
1716      oss.str("");
1717      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1718          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1719          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1720          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1721          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1722          << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1723          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1724          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1725          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1726          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1727          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1728          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1729          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1730          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1731      //
1732      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1733      result = conn->Query(oss.str().c_str());
1734      //
1735      if ( !result ) throw -4;
1736      //
1737      row = result->Next();
1738      //
1739      if ( !row ){
1740        //
1741        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1742        //
1743        if ( IsDebug() ) printf(" The run is new \n");
1744        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1745        //
1746        glrun->SetID(this->AssignRunID());
1747        glrun->SetID_RUN_FRAG(0);
1748        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1749        //
1750      } else {
1751        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1752      };
1753      //
1754      //
1755    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1756    //        //    
1757    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
# Line 1511  void PamelaDBOperations::HandleRunFragme Line 1760  void PamelaDBOperations::HandleRunFragme
1760      oss.str("");      oss.str("");
1761      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1762          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1763          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1764            << " ID != " << glrun->ID
1765          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1766      //      //
1767      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1521  void PamelaDBOperations::HandleRunFragme Line 1771  void PamelaDBOperations::HandleRunFragme
1771      //      //
1772      row = result->Next();      row = result->Next();
1773      //      //
1774        if ( !row && NoFrag() ){
1775          //
1776          oss.str("");
1777          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1778              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1779              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1780              << " ID != " << glrun->ID
1781              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1782          //
1783          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1784          result = conn->Query(oss.str().c_str());
1785          //
1786          if ( !result ) throw -4;
1787          //
1788          foundinrun = true;
1789          //
1790          row = result->Next();
1791          //
1792        };
1793        //
1794      if ( !row ){      if ( !row ){
1795        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1796        found = false;        found = false;
# Line 1595  void PamelaDBOperations::HandleRunFragme Line 1865  void PamelaDBOperations::HandleRunFragme
1865        //        //
1866        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
1867        //        //
1868          if ( foundinrun ){
1869            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
1870            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1871          };
1872          //
1873        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
1874        //        //
1875        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
1876        //        //
1877        oss.str("");        oss.str("");
1878        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1626  void PamelaDBOperations::HandleRunFragme Line 1901  void PamelaDBOperations::HandleRunFragme
1901        };        };
1902        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
1903        //        //
       glrun1->SetID(0);  
1904        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
1905        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
1906        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1635  void PamelaDBOperations::HandleRunFragme Line 1909  void PamelaDBOperations::HandleRunFragme
1909        //        //
1910        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
1911        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
1912          //
1913        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
1914        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
1915        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1654  void PamelaDBOperations::HandleRunFragme Line 1929  void PamelaDBOperations::HandleRunFragme
1929        //        //
1930        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
1931          //          //
1932            //      glrun->SetID(this->AssignRunID());
1933            glrun->SetID_RUN_FRAG(glrun1->GetID());
1934          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
1935          //          //
1936          // get id number          // set id number
         //  
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  
             << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  
             << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  
         //  
         if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun0 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         glrun1->SetID_RUN_FRAG(idrun0);  
1937          //          //
1938            glrun1->SetID_RUN_FRAG(glrun->GetID());
1939          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
1940          //          //
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  
         //  
         if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun1 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun1 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         oss.str("");  
         oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         //  
1941        };        };
       //  
       delete glrun1;  
       //  
1942        // delete old entry in fragment table        // delete old entry in fragment table
1943        //        //
1944        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
1945          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
1946        //        //
1947        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
1948        //        //
       if ( IsDebug() ) printf(" Delete from frag table the old run :\n query is \n %s \n",oss.str().c_str());  
       result =  conn->Query(oss.str().c_str());  
       if ( !result ) throw -4;  
1949        //        //
1950        return;        return;
1951        //        //
# Line 1723  void PamelaDBOperations::HandleRunFragme Line 1954  void PamelaDBOperations::HandleRunFragme
1954    };    };
1955    //    //
1956    if ( mistrail && rtlastev == lastev ) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is    if ( mistrail && rtlastev == lastev ) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
1957                                             // missing it no way we can found a piece in the frag table      // missing it no way we can found a piece in the frag table
1958      //      //
1959      oss.str("");      oss.str("");
1960      oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1961          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1962          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
1963            << " ID != " << glrun->ID
1964          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
1965      //      //
1966      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1738  void PamelaDBOperations::HandleRunFragme Line 1970  void PamelaDBOperations::HandleRunFragme
1970      //      //
1971      row = result->Next();      row = result->Next();
1972      //      //
1973      if ( !row ){      if ( !row && NoFrag() ){
       if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");  
       found = false;  
     } else {  
1974        //        //
1975        found = false; // default value        oss.str("");
1976          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
1977              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1978              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
1979              << " ID != " << glrun->ID
1980              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
1981        //        //
1982        if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");        if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1983          result = conn->Query(oss.str().c_str());
1984        //        //
1985        // if we have both runheader and runtrailer we can check with pkt_counter:        if ( !result ) throw -4;
1986          //
1987          foundinrun = true;
1988          row = result->Next();
1989          //
1990        };
1991        //
1992        if ( !row ){
1993          if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1994          found = false;
1995        } else {
1996          //
1997          found = false; // default value
1998          //
1999          if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2000          //
2001          // if we have both runheader and runtrailer we can check with pkt_counter:
2002        //        //
2003        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2004          ULong64_t chkpkt = 0;            ULong64_t chkpkt = 0;  
# Line 1811  void PamelaDBOperations::HandleRunFragme Line 2062  void PamelaDBOperations::HandleRunFragme
2062        //        //
2063        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2064        //        //
2065          if ( foundinrun ){
2066            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2067            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2068          };
2069          //
2070        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2071        //        //
2072        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2073        //        //
2074        oss.str("");        oss.str("");
2075        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1850  void PamelaDBOperations::HandleRunFragme Line 2106  void PamelaDBOperations::HandleRunFragme
2106        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2107        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2108        //        //
       glrun1->SetID(0);  
2109        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2110        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2111        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1870  void PamelaDBOperations::HandleRunFragme Line 2125  void PamelaDBOperations::HandleRunFragme
2125        //        //
2126        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2127          //          //
2128          glrun->Fill_GL_RUN(conn);          //      glrun->SetID(this->AssignRunID());
         //  
         // get id number  
         //  
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  
             << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  
             << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  
         //  
         if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
2129          //          //
2130          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2131          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2132          //          //
2133          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2134          //          //
2135            glrun1->SetID_RUN_FRAG(glrun->GetID());
2136          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2137          //          //
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  
         //  
         if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun1 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun1 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         oss.str("");  
         oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         //  
2138        };        };
2139        //        //
2140        delete glrun1;        // delete old entries in fragment table
2141        //        //
2142        // delete old entry in fragment table        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2143        //        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       oss.str("");  
       //  
       oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";  
       //  
       if ( IsDebug() ) printf(" Delete from frag table the old run :\n query is \n %s \n",oss.str().c_str());  
       result =  conn->Query(oss.str().c_str());  
       if ( !result ) throw -4;  
2144        //        //
2145          delete glrun1;
2146        //        //
2147        return;        return;
2148        //        //
# Line 1968  void PamelaDBOperations::HandleRunFragme Line 2179  void PamelaDBOperations::HandleRunFragme
2179      //      //
2180      row = result->Next();      row = result->Next();
2181      //      //
2182      if ( !row ){      if ( row ){
       //  
       oss.str("");  
       oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "  
           << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("  
           << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "  
           << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("  
           << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "  
           << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
           << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "  
           << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "  
           << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
           << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("  
           << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "  
           << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
           << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "  
           << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";  
       //  
       if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());  
       result = conn->Query(oss.str().c_str());  
       //  
       if ( !result ) throw -4;  
       //  
       row = result->Next();  
       //  
       if ( !row ){  
         //  
         // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)  
         //  
         if ( IsDebug() ) printf(" The run is new \n");  
         if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");  
         //  
         glrun->Fill_GL_RUN_FRAGMENTS(conn);  
         //  
       } else {  
         if ( IsDebug() ) printf(" The run is already present in the fragment table \n");  
       };  
     } else {  
2183        if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
2184        } else {
2185          if ( NoFrag() ){
2186            glrun->SetID_RUN_FRAG(glrun->GetID());
2187            glrun->Fill_GL_RUN(conn);      
2188            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2189          };    
2190      };      };
2191    };    };
2192    //    //
# Line 2032  void PamelaDBOperations::HandleMissingHo Line 2212  void PamelaDBOperations::HandleMissingHo
2212      //      //
2213      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2214      //      //
2215      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2216          glrun->SetID(this->AssignRunID());
2217          glrun->SetID_RUN_FRAG(0);
2218          glrun->Fill_GL_RUN(conn);    
2219        };
2220      //      //
2221    };    };
2222    //    //
# Line 2199  Bool_t PamelaDBOperations::IsRunConsiste Line 2383  Bool_t PamelaDBOperations::IsRunConsiste
2383            //                  //      
2384            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2385            //            //
2386            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2387                glrun->SetID(this->AssignRunID());
2388                glrun->SetID_RUN_FRAG(0);
2389                glrun->Fill_GL_RUN(conn);      
2390              };
2391            //            //
2392            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2393            //            //
# Line 2275  void PamelaDBOperations::HandleSuspiciou Line 2463  void PamelaDBOperations::HandleSuspiciou
2463      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2464      //      //
2465      this->FillClass();      this->FillClass();
2466      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2467          glrun->SetID(this->AssignRunID());
2468          glrun->SetID_RUN_FRAG(0);
2469          glrun->Fill_GL_RUN(conn);    
2470        };
2471      //      //
2472    } else {    } else {
2473      //      //
# Line 2303  void PamelaDBOperations::HandleSuspiciou Line 2495  void PamelaDBOperations::HandleSuspiciou
2495        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
2496        //        //
2497        this->FillClass();        this->FillClass();
2498        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2499            glrun->SetID(this->AssignRunID());
2500            glrun->SetID_RUN_FRAG(0);
2501            glrun->Fill_GL_RUN(conn);        
2502          };
2503        //        //
2504      } else {      } else {
2505        //        //
# Line 2401  void PamelaDBOperations::HandleSuspiciou Line 2597  void PamelaDBOperations::HandleSuspiciou
2597            //                  //      
2598            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2599            //            //
2600            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2601                glrun->SetID(this->AssignRunID());
2602                glrun->SetID_RUN_FRAG(0);
2603                glrun->Fill_GL_RUN(conn);      
2604              };
2605            //            //
2606            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
2607              //              //
# Line 2436  void PamelaDBOperations::HandleSuspiciou Line 2636  void PamelaDBOperations::HandleSuspiciou
2636              //                  //    
2637              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2638              //              //
2639              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2640                  glrun->SetID(this->AssignRunID());
2641                  glrun->SetID_RUN_FRAG(0);
2642                  glrun->Fill_GL_RUN(conn);      
2643                };
2644            };            };
2645            //            //
2646            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3117  Int_t PamelaDBOperations::insertS4_CALIB Line 3321  Int_t PamelaDBOperations::insertS4_CALIB
3321   * Scan the fragment table and move old fragments to the GL_RUN table   * Scan the fragment table and move old fragments to the GL_RUN table
3322   */   */
3323  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3324      return(this->CleanGL_RUN_FRAGMENTS(""));
3325    };
3326    
3327    /**
3328     * Scan the fragment table and move old fragments to the GL_RUN table
3329     */
3330    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3331    //    //
3332    TSQLResult *result = 0;    TSQLResult *result = 0;
3333    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 3124  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3335  Int_t PamelaDBOperations::CleanGL_RUN_FR
3335    TSQLRow    *row2   = 0;    TSQLRow    *row2   = 0;
3336    //    //
3337    UInt_t moved = 0;    UInt_t moved = 0;
   UInt_t timelim = 0;  
   TDatime *time = new TDatime();  
3338    //    //
3339    stringstream oss;    stringstream oss;
3340    oss.str("");    oss.str("");
3341    //    //
3342    //    if ( !strcmp(fcleanfile.Data(),"") ){
3343    //      //
3344    if ( olderthan < 0 ){      // check if there are entries older than "olderthan" seconds from now
3345      if ( IsDebug() ) printf(" Do not clean GL_RUN_FRAGMENTS table \n");      //
3346      return(1);      oss.str("");
3347        oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3348            << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3349        //
3350        if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3351        result = conn->Query(oss.str().c_str());
3352        //
3353      } else {
3354        oss.str("");
3355        oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3356        if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3357        result = conn->Query(oss.str().c_str());
3358        //    
3359        if ( result ){
3360          //
3361          row = result->Next();
3362          //
3363          if ( row ){
3364            oss.str("");
3365            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3366                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3367            //
3368            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3369            result = conn->Query(oss.str().c_str());
3370            //    
3371          };
3372        } else {
3373          return(2);
3374        };
3375    };    };
3376    //    //
   // timelim = now - olderthan  
   //  
   time->Set();  
   timelim =  (UInt_t)time->Convert() - olderthan;  
   time->Set(timelim,false);  
   //  
   // check if there are entries older than "olderthan" seconds from now  
   //  
   oss.str("");  
   oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"  
       << " INSERT_TIME <= '" << time->AsSQLString() << "';";  
   //  
   if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",time->AsSQLString(),oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
   //  
3377    if ( result ){    if ( result ){
3378      //      //
3379      row = result->Next();      row = result->Next();
3380      //      //
3381      if ( row ){      while ( row ){
3382        //        //
3383        oss.str("");        oss.str("");
3384        oss << " ID= "<< row->GetField(0);        oss << " ID= "<< row->GetField(0);
# Line 3191  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3413  Int_t PamelaDBOperations::CleanGL_RUN_FR
3413          if ( IsDebug() ) printf(" The run is new \n");          if ( IsDebug() ) printf(" The run is new \n");
3414          if ( IsDebug() ) printf(" -> fill the DB \n");                if ( IsDebug() ) printf(" -> fill the DB \n");      
3415          //          //
3416          glrun->SetID(0);          //      glrun->SetID(this->AssignRunID()); we use the old run number!
3417            glrun->SetID_RUN_FRAG(glrun->GetID());
3418          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
3419          //          //
3420          oss.str("");  //      oss.str("");
3421          oss << " SELECT ID FROM GL_RUN WHERE "  //      oss << " SELECT ID FROM GL_RUN WHERE "
3422              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3423              << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3424              << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3425              << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3426              << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3427          //  //      //
3428          if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3429          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3430          //  //      //
3431          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3432          //  //      //
3433          row2 = result2->Next();  //      row2 = result2->Next();
3434          //  //      //
3435          if ( !row2 ) throw -25;  //      if ( !row2 ) throw -25;
3436          //  //      //
3437          oss.str("");  //      oss.str("");
3438          oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3439          if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3440          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3441          //  //      //
3442          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3443          //          //
3444          moved++;          moved++;
3445          //          //
# Line 3226  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3449  Int_t PamelaDBOperations::CleanGL_RUN_FR
3449        if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));              if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3450        //        //
3451        //        //
3452        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3453        oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);  //      oss.str("");
3454        if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3455        result2 = conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3456        //  //       result2 = conn->Query(oss.str().c_str());
3457        if ( !result2 ) throw -4;  //      //
3458        //  //      if ( !result2 ) throw -4;
3459    //      //
3460          row = result->Next();
3461      };      };
3462    };    };
3463    if ( IsDebug() ) printf(" Moved %u runs\n",moved);    if ( IsDebug() ) printf(" Moved %u runs\n",moved);
# Line 3243  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3468  Int_t PamelaDBOperations::CleanGL_RUN_FR
3468   * Check if runs are good, i.e. if the tracker calibration is correctly associated..   * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3469   */   */
3470  Int_t PamelaDBOperations::ValidateRuns(){  Int_t PamelaDBOperations::ValidateRuns(){
3471      return(this->ValidateRuns(""));
3472    };
3473    
3474    /**
3475     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3476     */
3477    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3478    //    //
3479    TSQLResult *result = 0;    TSQLResult *result = 0;
3480    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
3481    //    //
3482    UInt_t timelim = 0;    UInt_t calibtime = 50;
   TDatime *time = new TDatime();  
3483    //    //
3484    stringstream oss;    stringstream oss;
3485    oss.str("");    oss.str("");
3486    //    //
   //  
   //  
   if ( olderthan < 0 ){  
     if ( IsDebug() ) printf(" Do not validate runs \n");  
     return(1);  
   };  
   //  
   // timelim = now - olderthan  
   //  
   time->Set();  
   timelim =  (UInt_t)time->Convert() - olderthan;  
   time->Set(timelim,false);  
   
   printf("Validate runs older than %s \n",time->AsSQLString());  
   
3487    // =======================================================    // =======================================================
3488    // validate runs by checking missing calibrations    // validate runs by checking missing calibrations
3489    // =======================================================    // =======================================================
3490    UInt_t t_stop  = 0;    UInt_t t_stop  = 0;
3491    UInt_t t_start = 0;    UInt_t t_start = 0;
3492    // --------------------------------------------------------------    if ( !strcmp(valfile.Data(),"") ) {
3493    // 1) get the OBT of the last run inserted after clean-time limit      // --------------------------------------------------------------
3494    // --------------------------------------------------------------      // 1) get the OBT of the last run inserted after clean-time limit
3495    oss.str("");      // --------------------------------------------------------------
3496    oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << time->AsSQLString()      oss.str("");
3497        << "' ORDER BY INSERT_TIME DESC LIMIT 1;";      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3498    printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());          << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3499    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3500    if ( !result ) throw -4;      result = conn->Query(oss.str().c_str());
3501    if ( !result->GetRowCount() ) {      if ( !result ) throw -4;
3502            printf(" No runs to validate \n");      if ( !result->GetRowCount() ) {
3503            return(1);        printf(" No runs to validate \n");
3504    }else{        return(1);
3505          row = result->Next();      }else{
3506          t_start = (UInt_t)atoll(row->GetField(4));        row = result->Next();
3507          printf("t_start %i\n",t_start);        t_start = (UInt_t)atoll(row->GetField(4));
3508    };        };  
3509    // --------------------------------------------------------------      // --------------------------------------------------------------
3510    // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
3511    // --------------------------------------------------------------      // --------------------------------------------------------------
3512    oss.str("");      oss.str("");
3513    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3514        <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3515    printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3516    result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
3517    if ( !result ) throw -4;      if ( !result ) throw -4;
3518    if ( result->GetRowCount() ){      if ( result->GetRowCount() ){
3519            row = result->Next();        row = result->Next();
3520            t_stop = (UInt_t)atoll(row->GetField(4));        t_stop = (UInt_t)atoll(row->GetField(4));
3521        };
3522        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3523        // --------------------------------------------------------------
3524        // now retrieves runs to be validated
3525        // --------------------------------------------------------------
3526        oss.str("");
3527        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3528        oss << " AND RUNHEADER_TIME >="<< t_stop;
3529        oss << " ORDER BY RUNHEADER_TIME DESC;";
3530        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3531        result = conn->Query(oss.str().c_str());
3532      } else {
3533        //
3534        stringstream myquery;
3535        UInt_t myid = 0;
3536        myquery.str("");
3537        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3538        //
3539        result = conn->Query(myquery.str().c_str());
3540        //
3541        row = result->Next();      
3542        if( !row ){
3543          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3544            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3545            return(2);
3546          };
3547          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3548          return(0);
3549        };
3550        myid=(UInt_t)atoll(row->GetField(0));
3551        //
3552        myquery.str("");
3553        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3554        //
3555        result = conn->Query(myquery.str().c_str());
3556        //
3557        row = result->Next();      
3558        if( !row->GetField(0) || !row->GetField(1)){
3559          //
3560          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3561          //
3562          return(0);
3563          //
3564        } else {  
3565          //
3566          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3567          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3568          UInt_t caltime = 0;
3569          //
3570          myquery.str("");
3571          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3572          myquery << " order by FROM_TIME asc limit 1;";
3573          //
3574          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3575          //
3576          //
3577          result = conn->Query(myquery.str().c_str());
3578          //
3579          row = result->Next();      
3580          if( !row ){
3581            caltime = runhtime;
3582          } else {
3583            caltime = (UInt_t)atoll(row->GetField(0));
3584          };
3585          //
3586          myquery.str("");
3587          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3588          myquery << caltime << " order by RUNHEADER_TIME DESC";
3589          //
3590          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3591          //
3592          result = conn->Query(myquery.str().c_str());
3593          //
3594        };
3595    };    };
3596    printf("t_stop %i\n",t_stop);    //
   // --------------------------------------------------------------  
   // now retrieves runs to be validated  
   // --------------------------------------------------------------  
   oss.str("");  
   oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;  
   oss << " AND RUNHEADER_TIME >="<< t_stop;  
   oss << " ORDER BY RUNHEADER_TIME DESC;";  
 //  if ( IsDebug() )  
   printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
3597    if ( !result ) throw -4;    if ( !result ) throw -4;
3598    if ( !result->GetRowCount() ) printf(" No runs to validate \n");    if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3599    printf("------------------------------------------------------------------------------- \n");    //
     
3600    Int_t nrow = 0;    Int_t nrow = 0;
3601    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
3602    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
3603    Int_t   nseq_max = 100;    Int_t   nseq_max = 1000;
3604  //  UInt_t* sequence = new UInt_t[100];  //  UInt_t* sequence = new UInt_t[100];
3605    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
3606    Int_t   nseq = 0;    Int_t   nseq = 0;
# Line 3331  Int_t PamelaDBOperations::ValidateRuns() Line 3610  Int_t PamelaDBOperations::ValidateRuns()
3610    UInt_t t1=0,t2=0;    UInt_t t1=0,t2=0;
3611    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
3612    // - loop over runs, back in time,    // - loop over runs, back in time,
3613    // - select sequences of runs close in time (less than 60 s apart),    // - select sequences of runs close in time (less than calibtime s apart),
3614    //   which could be preceeded by a calibration    //   which could be preceeded by a calibration
3615    // - check if there might be a missing calibration    // - check if there might be a missing calibration
3616    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
# Line 3344  Int_t PamelaDBOperations::ValidateRuns() Line 3623  Int_t PamelaDBOperations::ValidateRuns()
3623            //get run info            //get run info
3624            //------------            //------------
3625            this_run->Set_GL_RUN(row);            this_run->Set_GL_RUN(row);
3626                                
           printf(" RUN ID %i --- TRK_CALIB_USED %i --- RM_ACQ_AFTER_CALIB %i --- TIME %i %i \n",this_run->ID,this_run->TRK_CALIB_USED,this_run->RM_ACQ_AFTER_CALIB,this_run->RUNHEADER_TIME, this_run->RUNTRAILER_TIME);  
             
3627            Bool_t this_BAD = false;            Bool_t this_BAD = false;
3628            if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;            if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3629            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3630            else{            else{
3631                    printf("Missing or corrupted header!! \n");  //                printf("Missing or corrupted header!! \n");
3632                    this_ONLINE = false;                    this_ONLINE = false;
3633                    this_BAD = true;                    this_BAD = true;
3634            };            };
# Line 3373  Int_t PamelaDBOperations::ValidateRuns() Line 3650  Int_t PamelaDBOperations::ValidateRuns()
3650                                                        
3651                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3652                                                        
3653                            if( interval >= 60 )CHECK = true;                     //more than 60 s => there might be a calibration                            if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
                             
 /*                        if( CHECK && !next_run->GetRM_ACQ_AFTER_CALIB() )  
                                   printf(" ValidateRuns ***WARNING*** : DT = %i but RM_ACQ_AFTER_CALIB = %i \n",(t2-t1),next_run->GetRM_ACQ_AFTER_CALIB());*/  
                                                     
3654                                                        
3655                            if( !CHECK && this_run->VALIDATION ){                            if( !CHECK && this_run->VALIDATION ){
3656                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
# Line 3387  Int_t PamelaDBOperations::ValidateRuns() Line 3660  Int_t PamelaDBOperations::ValidateRuns()
3660                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3661                                                        
3662                            CHECK = true;                            CHECK = true;
 //                        if( interval < 60 ) printf(" ValidateRuns ***WARNING*** : kkkkkk DT = %i \n",interval);  
3663    
3664                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3665                                                        
# Line 3401  Int_t PamelaDBOperations::ValidateRuns() Line 3673  Int_t PamelaDBOperations::ValidateRuns()
3673            //----------------------------            //----------------------------
3674            if( CHECK ){            if( CHECK ){
3675                    // check if calibration exists                    // check if calibration exists
3676                    printf("DT %i ===> CHECK Missing calibration\n",interval);                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3677                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3678                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3679                    nseq=0;                    nseq=0;
3680            } else printf("DT %i\n",interval);            };
3681            //--------------            //--------------
3682            //store run info            //store run info
3683            //--------------            //--------------
# Line 3418  Int_t PamelaDBOperations::ValidateRuns() Line 3690  Int_t PamelaDBOperations::ValidateRuns()
3690                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3691            };            };
3692                        
3693              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3694            nrow++;            nrow++;
3695                        
3696    };    };
# Line 3446  Bool_t PamelaDBOperations::MissingTRK_CA Line 3719  Bool_t PamelaDBOperations::MissingTRK_CA
3719          // which should be equal to the time between ascending-nodes.          // which should be equal to the time between ascending-nodes.
3720          //==============================================================          //==============================================================
3721          if ( t2 - trkcalib->FROM_TIME > 5700) {          if ( t2 - trkcalib->FROM_TIME > 5700) {
3722                  printf("Long time to previous calib %i :-( \n",t2 - trkcalib->FROM_TIME);                  if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3723          //==============================================================          //==============================================================
3724          // there might be a missing calibration, due to:          // there might be a missing calibration, due to:
3725          // - MM full          // - MM full
# Line 3467  Bool_t PamelaDBOperations::MissingTRK_CA Line 3740  Bool_t PamelaDBOperations::MissingTRK_CA
3740          // it is enough to say that there are no missing calibrations          // it is enough to say that there are no missing calibrations
3741          //==============================================================          //==============================================================
3742          // the long time interval bewteen runs might be due to download          // the long time interval bewteen runs might be due to download
3743          printf("Short time to previous calib %i :-) \n",t2 - trkcalib->FROM_TIME);          if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3744          return(false);          return(false);
3745                    
3746  };  };
# Line 3480  Int_t PamelaDBOperations::assignVALIDATI Line 3753  Int_t PamelaDBOperations::assignVALIDATI
3753          TSQLResult *result = 0;          TSQLResult *result = 0;
3754          stringstream oss;          stringstream oss;
3755          oss.str("");          oss.str("");
3756          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << "';";          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3757          //          //
3758  //      if ( IsDebug() )  //      if ( IsDebug() )
3759          printf(" Set VALIDATION = %i for run %i \n",validation,idrun);  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3760  //      printf(" Set VALIDATION = %i for run %i : query is \n %s \n",validation,idrun,oss.str().c_str());          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3761  //      result = conn->Query(oss.str().c_str());          result = conn->Query(oss.str().c_str());
3762  //      if ( !result ) throw -4;          if ( !result ) throw -4;
3763          return(0);          return(0);
3764  }  }
3765    
3766    
3767    
3768    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3769    // opened by conn, sorting them by date from older to newer, if each
3770    // TLE has not been alread inserted.
3771    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3772    {
3773      fstream tlefile(tlefilename, ios::in);
3774    
3775      if ( !tlefile ) throw -7;
3776    
3777      vector<cTle*> ctles;
3778      vector<cTle*>::iterator iter;
3779      int present = 0;
3780    
3781      // Get three lines from tlefile, create a cTle object and put it
3782      // into ctles
3783      while(1) {
3784        cTle *tlef;
3785        string str1, str2, str3;
3786    
3787        getline(tlefile, str1);
3788        if(tlefile.eof()) break;
3789    
3790        getline(tlefile, str2);
3791        if(tlefile.eof()) break;
3792    
3793        getline(tlefile, str3);
3794        if(tlefile.eof()) break;
3795    
3796        // We now have three good lines for a cTle.
3797        tlef = new cTle(str1, str2, str3);
3798        ctles.push_back(tlef);
3799      }
3800    
3801      tlefile.close();
3802    
3803      // Sort by date
3804      sort(ctles.begin(), ctles.end(), compTLE);
3805    
3806      // Now we insert each TLE into the db
3807      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3808        cTle *tle = *iter;
3809    
3810        // Do nothing if it's already present in the db.  Just increase
3811        // the counter present.
3812        if (! isTlePresent(tle))
3813          {
3814            int status = insertTle(tle);
3815    
3816            // Insert query failed.  Return 1.
3817            if(status == EXIT_FAILURE) {
3818              
3819              if( IsDebug() ) {
3820                cerr << "Error: inserting TLE:" << endl
3821                     << tle->getName() << endl
3822                     << tle->getLine1() << endl
3823                     << tle->getLine2() << endl;
3824              }
3825    
3826              throw -4;
3827              return 1;
3828            }
3829    
3830          }
3831        else
3832          present++;
3833    
3834      }
3835    
3836      int inserted = ctles.size() - present;  // Number of inserted TLE.
3837      if ( IsDebug() )
3838        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3839             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3840    
3841      ctles.clear();
3842    
3843    
3844      // Return 2 if no new TLE has been inserted.  0 otherwise.
3845      if(! inserted ) return 2;
3846      return 0;
3847    }
3848    
3849    
3850    // Insert tle in the table GL_TLE using the connection conn.
3851    Int_t PamelaDBOperations::insertTle(cTle *tle)
3852    {
3853      stringstream oss;
3854      TSQLResult *result = 0;
3855    
3856      oss.str("");
3857      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3858          << " VALUES ( '"
3859          << tle->getName() << "', '"
3860          << tle->getLine1() << "', '"
3861          << tle->getLine2() << "', '"
3862          << getTleDatetime(tle) << "')";
3863    
3864      //  cout << oss.str().c_str() << endl;
3865      result = conn->Query(oss.str().c_str());
3866      if (result == NULL)
3867        return EXIT_FAILURE;
3868    
3869      return EXIT_SUCCESS;
3870    }
3871    
3872    
3873    // Return whether tle is already in the db connected by conn.
3874    bool PamelaDBOperations::isTlePresent(cTle *tle)
3875    {
3876      stringstream oss;
3877      TSQLResult *result = 0;
3878    
3879      oss.str("");
3880      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3881          << getTleDatetime(tle) << "'";
3882    
3883      result = conn->Query(oss.str().c_str());
3884      if (result == NULL) throw -4;
3885    
3886      if (result->GetRowCount())
3887        return true;
3888      else
3889        return false;
3890    }
3891    
3892    
3893    // Return whether the first TLE is dated early than the second
3894    bool compTLE (cTle *tle1, cTle *tle2)
3895    {
3896      return getTleJulian(tle1) < getTleJulian(tle2);
3897    }
3898    
3899    
3900    // Return the date of the tle using the format (year-2000)*1e3 +
3901    // julian day.  e.g. 6365 is the 31th Dec 2006.
3902    // It does *not* return a cJulian date.
3903    float getTleJulian(cTle *tle) {
3904      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3905    }
3906    
3907    
3908    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3909    // format.
3910    string getTleDatetime(cTle *tle)
3911    {
3912      int year, mon, day, hh, mm, ss;
3913      double dom; // day of month (is double!)
3914      stringstream date; // date in datetime format
3915    
3916      // create a cJulian from the date in tle
3917      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
3918    
3919      // get year, month, day of month
3920      jdate.getComponent(&year, &mon, &dom);
3921    
3922      // build a datetime YYYY-MM-DD hh:mm:ss
3923      date.str("");
3924      day = (int) floor(dom);
3925      hh = (int) floor( (dom - day) * 24);
3926      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
3927      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
3928      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
3929    
3930      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
3931    
3932      return date.str();
3933    }
3934    
3935    /**
3936     * Remove a file from the DB, delete on cascade all entries related to that file
3937     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
3938     * calibration
3939     **/
3940    Int_t PamelaDBOperations::removeFile(TString remfile){
3941      //
3942      // Determine ID_ROOT_L0 and ID_RAW
3943      //
3944      TSQLResult *pResult;
3945      TSQLRow *Row;
3946      stringstream myquery;
3947      //  
3948      myquery.str("");
3949      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
3950      //
3951      pResult = conn->Query(myquery.str().c_str());
3952      //
3953      Row = pResult->Next();      
3954      if( !Row ){
3955        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
3956          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
3957          return(1);
3958        };
3959        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
3960        return(0);
3961      };
3962      //
3963      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
3964      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
3965      //
3966      this->ValidationOFF();
3967      //
3968      this->RemoveCALIBS();
3969      //
3970      this->RemoveRUNS();
3971      //
3972      this->RemoveFILES();
3973      //
3974      this->SetID_ROOT(0);
3975      this->SetID_RAW(0);
3976      //
3977      return(0);
3978    };
3979    
3980    /**
3981     *
3982     * Set validation bit to zero for runs following the removing file till
3983     * 1) a run with TRK_CALIB_USED=140
3984     * 2) a run with VALIDATION = 0
3985     * 3) the next calibration
3986     *
3987     **/
3988    void PamelaDBOperations::ValidationOFF(){
3989      TSQLResult *pResult;
3990      TSQLRow *Row;
3991      stringstream myquery;
3992      Int_t unv = 0;
3993      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
3994      myquery.str("");
3995      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
3996      //
3997      pResult = conn->Query(myquery.str().c_str());
3998      //
3999      Row = pResult->Next();      
4000      if( !Row->GetField(0) ){
4001        //
4002        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4003        //
4004      } else {  
4005        //
4006        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4007        UInt_t caltime = 0;
4008        //
4009        myquery.str("");
4010        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4011        myquery << " order by FROM_TIME asc limit 1;";
4012        //
4013        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4014        //
4015        //
4016        delete pResult;
4017        pResult = conn->Query(myquery.str().c_str());
4018        //
4019        Row = pResult->Next();      
4020        if( !Row ){
4021          caltime = runhtime;
4022        } else {
4023          caltime = (UInt_t)atoll(Row->GetField(0));
4024        };
4025        //
4026        myquery.str("");
4027        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4028        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4029        //
4030        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4031        //
4032        pResult = conn->Query(myquery.str().c_str());
4033        //
4034        Row = pResult->Next();      
4035        if( !Row ){
4036          //
4037          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4038          //
4039        } else {
4040          myquery.str("");
4041          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4042          myquery << " RUNHEADER_TIME>=" <<runhtime;
4043          myquery << " order by RUNHEADER_TIME asc;";
4044          //
4045          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4046          //
4047          pResult = conn->Query(myquery.str().c_str());
4048          //
4049          Row = pResult->Next();  
4050          while ( Row ){
4051            //      
4052            unv++;
4053            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4054            Row = pResult->Next();  
4055            //
4056          };
4057        };
4058      };
4059      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4060    };
4061    
4062    /**
4063     *
4064     * Rearrange GL_RUN table and remove runs
4065     *
4066     **/
4067    void PamelaDBOperations::RemoveRUNS(){
4068      TSQLResult *pResult;
4069      TSQLRow *Row;
4070      stringstream myquery;
4071      UInt_t drun = 0;
4072      GL_RUN *delrun = new GL_RUN();
4073      //
4074      myquery.str("");
4075      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4076      //
4077      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4078      //
4079      pResult = conn->Query(myquery.str().c_str());
4080      //
4081      Row = pResult->Next();    
4082      //
4083      //
4084      if ( !Row ){
4085        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4086      } else {
4087        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4088        while ( Row ){
4089          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4090          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4091          drun++;
4092          Row = pResult->Next();    
4093        };
4094      };
4095      //
4096      //
4097      myquery.str("");
4098      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4099      //
4100      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4101      //
4102      pResult = conn->Query(myquery.str().c_str());
4103      //
4104      Row = pResult->Next();    
4105      //
4106      if ( !Row ){
4107        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4108      } else {
4109        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4110        while ( Row ){
4111          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4112          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4113          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4114          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4115          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4116            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4117            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4118          };
4119          drun++;
4120          Row = pResult->Next();    
4121        };
4122      };
4123      //
4124      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4125      //
4126      //
4127      //
4128      drun = 0;
4129      //
4130      myquery.str("");
4131      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4132      //
4133      pResult = conn->Query(myquery.str().c_str());
4134      //
4135      Row = pResult->Next();    
4136      //
4137      if ( !Row ){
4138        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4139      } else {
4140        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4141        while ( Row ){
4142          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4143          myquery.str("");
4144          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4145          conn->Query(myquery.str().c_str());
4146          drun++;
4147          Row = pResult->Next();    
4148        };
4149      };
4150      //  
4151      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4152      //
4153      //
4154      //
4155      drun = 0;
4156      //
4157      myquery.str("");
4158      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4159      //
4160      pResult = conn->Query(myquery.str().c_str());
4161      //
4162      Row = pResult->Next();    
4163      //
4164      if ( !Row ){
4165        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4166      } else {
4167        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4168        while ( Row ){
4169          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4170          myquery.str("");
4171          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4172          conn->Query(myquery.str().c_str());
4173          drun++;
4174          Row = pResult->Next();    
4175        };
4176      };
4177      //  
4178      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4179      //
4180      //
4181      //
4182      delete delrun;
4183      //
4184    };
4185    
4186    
4187    /**
4188     *
4189     * Rearrange calibration tables
4190     *
4191     **/
4192    void PamelaDBOperations::RemoveFILES(){
4193      stringstream myquery;
4194      //
4195      myquery.str("");
4196      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4197      //
4198      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4199      //
4200      conn->Query(myquery.str().c_str());
4201      //
4202    };
4203    
4204    /**
4205     *
4206     * Rearrange calibration tables
4207     *
4208     **/
4209    void PamelaDBOperations::RemoveCALIBS(){
4210      TSQLResult *pResult;
4211      TSQLRow *Row;
4212      stringstream myquery;
4213      //  
4214      //
4215      // Calorimeter
4216      //
4217      for (Int_t section = 0; section < 4; section++){
4218        myquery.str("");
4219        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4220        myquery << " SECTION=" << section << ";";
4221        //
4222        pResult = conn->Query(myquery.str().c_str());
4223        //
4224        Row = pResult->Next();      
4225        if( !Row->GetField(0) || !Row->GetField(1) ){
4226          //
4227          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4228          //
4229        } else {
4230          //
4231          myquery.str("");
4232          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4233          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4234          myquery << " SECTION=" << section << ";";
4235          //
4236          pResult = conn->Query(myquery.str().c_str());
4237          //
4238          if( !pResult ){
4239            //
4240            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4241            //
4242            throw -4;
4243            //
4244          };
4245          //
4246        };
4247      };
4248      myquery.str("");
4249      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4250      //
4251      pResult = conn->Query(myquery.str().c_str());
4252      //
4253      if( !pResult ){
4254        //
4255        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4256        //
4257        throw -4;
4258        //
4259      };
4260      //
4261      // Tracker
4262      //
4263      myquery.str("");
4264      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4265      //
4266      pResult = conn->Query(myquery.str().c_str());
4267      //
4268      Row = pResult->Next();      
4269      if( !Row->GetField(0) || !Row->GetField(1) ){
4270        //
4271        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4272        //
4273      } else {
4274        //
4275        myquery.str("");
4276        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4277        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4278        //
4279        pResult = conn->Query(myquery.str().c_str());
4280        //
4281        if( !pResult ){
4282          //
4283          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4284          //
4285          throw -4;
4286          //
4287        };
4288        //
4289        myquery.str("");
4290        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4291        //
4292        pResult = conn->Query(myquery.str().c_str());
4293        //
4294        if( !pResult ){
4295          //
4296          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4297          //
4298          throw -4;
4299          //
4300        };
4301      };
4302      //
4303      //
4304      // S4
4305      //
4306      myquery.str("");
4307      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4308      //
4309      pResult = conn->Query(myquery.str().c_str());
4310      //
4311      Row = pResult->Next();      
4312      if( !Row->GetField(0) || !Row->GetField(1) ){
4313        //
4314        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4315        //
4316      } else {
4317        //
4318        myquery.str("");
4319        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4320        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4321        //
4322        pResult = conn->Query(myquery.str().c_str());
4323        //
4324        if( !pResult ){
4325          //
4326          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4327          //
4328          throw -4;
4329          //
4330        };
4331        //
4332        myquery.str("");
4333        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4334        //
4335        pResult = conn->Query(myquery.str().c_str());
4336        //
4337        if( !pResult ){
4338          //
4339          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4340          //
4341          throw -4;
4342          //
4343        };
4344        //
4345      };
4346    };

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.17

  ViewVC Help
Powered by ViewVC 1.1.23