예제 #1
0
ResultSet  DBService::query(const QString& sqlQuery)
{
//    qDebug()<<"query sql : "<<sqlQuery;
    ResultSet results;
    isValid = true;
    if(!open())
    {
        isValid = false;
        return results;
    }
    QSqlQuery sql_query(database);
    sql_query.prepare(sqlQuery);
    if(!sql_query.exec())
    {
        isValid = false;
        qDebug()<<sql_query.lastError();
        return results;
    }
    else
    {
        QSqlRecord record = sql_query.record();
        while(sql_query.next())
        {
            ResultRow resMap;
            for(int i = 0;i < record.count();i++)
            {
                resMap.insert(record.fieldName(i),sql_query.value(i).toString());
            }
            results.resultList.append(resMap);
        }

    }
    close();
    return results;
}
예제 #2
0
Vector *HomologyAdaptor_listStableIdsFromSpecies(HomologyAdaptor *ha, char *sp)  {
  StatementHandle *sth;
  ResultRow *row;
  Vector *genes;
  char qStr[1024];
  char *species;

  species = StrUtil_copyString(&species,sp,0);
  species = StrUtil_strReplChr(species,'_',' ');

  sprintf(qStr,
          "select  distinct grm.member_stable_id "
          " from    gene_relationship_member grm,"
          "         genome_db gd "
          " where   gd.genome_db_id = grm.genome_db_id "
          " and     gd.name = '%s'", species);


  sth = ha->prepare((BaseAdaptor *)ha, qStr, strlen(qStr));
  sth->execute(sth);

  genes = Vector_new();

  while ((row = sth->fetchRow(sth))) {
    char *tmpStr;
    Vector_addElement(genes,StrUtil_copyString(&tmpStr, row->getStringAt(row,0),0));
  }
  sth->finish(sth);

  free(species);

  return genes;
}                               
Vector *IntronSupportingEvidenceAdaptor_listLinkedTranscriptIds(IntronSupportingEvidenceAdaptor *isea, IntronSupportingEvidence *ise) {
  char qStr[1024];

  sprintf(qStr,"SELECT transcript_id from transcript_intron_supporting_evidence "
               "WHERE intron_supporting_evidence_id = "IDFMTSTR, IntronSupportingEvidence_getDbID(ise));

  StatementHandle *sth = isea->prepare((BaseAdaptor *)isea,qStr,strlen(qStr));
  sth->execute(sth);

  Vector *idVec = Vector_new();
  ResultRow *row;
  while ((row = sth->fetchRow(sth))) {
    IDType id = row->getLongLongAt(row, 0);
    IDType *idP;

    if ((idP = calloc(1,sizeof(IDType))) == NULL) {
      fprintf(stderr, "Failed allocating space for a id\n");
      exit(1);
    }

    *idP = id;
    Vector_addElement(idVec, idP);
  }
  sth->finish(sth);

  Vector_setFreeFunc(idVec, free);
  return idVec;
}
예제 #4
0
IDType GenomicAlignAdaptor_methodLinkIdByAlignmentType(GenomicAlignAdaptor *gaa, char *alignmentType) {
  StatementHandle *sth;
  ResultRow *row;
  IDType methodLinkId = 0;
  char qStr[512];
  int ok = 1;

  if (!alignmentType) {
    fprintf(stderr, "Error: alignment_type has to be defined\n");
    ok = 0;
  }
  
  if (ok) {
    sprintf(qStr, "SELECT method_link_id FROM method_link WHERE type = '%s'", alignmentType);
    sth = gaa->prepare((BaseAdaptor *)gaa, qStr, strlen(qStr));
    sth->execute(sth);

    if ((row = sth->fetchRow(sth))) {
      methodLinkId = row->getLongLongAt(row,0); 
    } else {
      fprintf(stderr,"Error: No methodLinkId for %s\n",alignmentType);
      ok = 0;
    }
  }

  if (ok) {
    sth->finish(sth);
  }

  return methodLinkId;
}
예제 #5
0
char *GenomicAlignAdaptor_alignmentTypeByMethodLinkId(GenomicAlignAdaptor *gaa, IDType methodLinkId) {
  StatementHandle *sth;
  ResultRow *row;
  char qStr[512];
  char *alignmentType = NULL;
  int ok = 1;

  if (!methodLinkId) {
    fprintf(stderr, "Error: methodLinkId has to be defined");
    ok = 0;
  } 

  if (ok) {
    sprintf(qStr,"SELECT type FROM method_link WHERE method_link_id = " IDFMTSTR, methodLinkId);
    sth = gaa->prepare((BaseAdaptor *)gaa, qStr, strlen(qStr));
    sth->execute(sth);

    if ((row = sth->fetchRow(sth))) {
      alignmentType = StrUtil_copyString(&alignmentType, row->getStringAt(row,0), 0); 
    } else {
      fprintf(stderr,"Error: No alignmentType for " IDFMTSTR "\n",methodLinkId);
      ok = 0;
    }
  }

  if (ok) {
    sth->finish(sth);
  }

// NIY switch to using passed in string
  return alignmentType;
}
예제 #6
0
int BaseAdaptor_genericCount(BaseAdaptor *ba, char *constraint) {
  char *qStr = NULL;

  if ((qStr = (char *)calloc(655500,sizeof(char))) == NULL) {
    fprintf(stderr,"Failed allocating qStr\n");
    return 0;
  }

  qStr[0] = '\0';

  BaseAdaptor_generateSql(ba, constraint, countCols, qStr);

  StatementHandle *sth = ba->prepare(ba,qStr,strlen(qStr));
  sth->execute(sth);

  if (sth->numRows(sth) != 1) {
    fprintf(stderr, "genericCount didn't return a row - bye!\n");
    return 0;
  }
  ResultRow *row = sth->fetchRow(sth);
  int count = row->getLongAt(row, 0);

  free(qStr);
  return count;
}
예제 #7
0
int DBEntryAdaptor_fetchAllByGene(DBEntryAdaptor *dbea, Gene *gene) {
  char qStr[512];
  StatementHandle *sth;
  ResultRow *row;
 
  sprintf(qStr,
      "SELECT t.transcript_id, t.canonical_translation_id"
      " FROM   transcript t"
      " WHERE  t.gene_id = " IDFMTSTR,
       Gene_getDbID(gene));

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));
  
  sth->execute(sth);
  
  while ((row = sth->fetchRow(sth))) {
    IDType transcriptId = row->getLongLongAt(row,0);
    int i;
    Vector *transLinks;

    if (row->col(row,1)) {
      IDType translationId = row->getLongLongAt(row,1);
      Vector *translatLinks = DBEntryAdaptor_fetchByObjectType(dbea, translationId,"Translation");

      for (i=0;i<Vector_getNumElement(translatLinks); i++) {
        Gene_addDBLink(gene,Vector_getElementAt(translatLinks,i));
      }
      Vector_free(translatLinks);
    }

    
    transLinks = DBEntryAdaptor_fetchByObjectType(dbea, transcriptId,"Transcript");
    for (i=0;i<Vector_getNumElement(transLinks); i++) {
      Gene_addDBLink(gene, Vector_getElementAt(transLinks,i));
    }
    Vector_free(transLinks);
  }

/* NIY This is wrong so I'm not going to implement it!
  if($gene->stable_id){
    my $genelinks = $self->_fetch_by_object_type( $gene->stable_id, 'Gene' );
    foreach my $genelink ( @$genelinks ) {
      $gene->add_DBLink( $genelink );
    }
  }
*/
  return 1;
}
예제 #8
0
DBEntry *DBEntryAdaptor_fetchByDbID(DBEntryAdaptor *dbea, IDType dbID) {
  char qStr[512];
  StatementHandle *sth;
  ResultRow *row;
  DBEntry *dbe = NULL;

  sprintf(qStr,
   "SELECT xref.xref_id, xref.dbprimary_acc, xref.display_label,"
   "       xref.version, xref.description,"
   "       exDB.db_name, exDB.db_release, es.synonym"
   " FROM  (xref, external_db exDB)"
   " LEFT JOIN external_synonym es on es.xref_id = xref.xref_id"
   " WHERE  xref.xref_id = " IDFMTSTR
   " AND    xref.external_db_id = exDB.external_db_id",
   dbID);
   

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

  sth->execute(sth);
  

  // Why???? my %duplicate;

  while ((row = sth->fetchRow(sth))){
    if (!row->col(row,0)) {
      fprintf(stderr,"WARNING: Got xref with no refID\n");
      return NULL;
    }
    
    if (!dbe) {
      dbe = DBEntry_new();

      DBEntry_setAdaptor(dbe,(BaseAdaptor *)dbea);
      DBEntry_setDbID(dbe, dbID);
      DBEntry_setPrimaryId(dbe, row->getStringAt(row,1));
      DBEntry_setDisplayId(dbe, row->getStringAt(row,2));
      DBEntry_setVersion(dbe, row->getStringAt(row,3));
      DBEntry_setRelease(dbe, row->getStringAt(row,6));
      DBEntry_setDbName(dbe, row->getStringAt(row,5));
      
      if (row->col(row,4)) DBEntry_setDescription(dbe, row->getStringAt(row,4));
    }
 
    if (row->col(row,7)) DBEntry_addSynonym(dbe, row->getStringAt(row,7));
  }

  sth->finish(sth);

  return dbe;
}
예제 #9
0
int DBEntryAdaptor_fetchAllByTranscript(DBEntryAdaptor *dbea, Transcript *trans) {
  char qStr[512];
  StatementHandle *sth;
  ResultRow *row;
  Vector *transLinks;
  int i;

  sprintf(qStr, 
    "SELECT t.canonical_translation_id" 
    " FROM transcript t"
    " WHERE t.transcript_id = " IDFMTSTR,
    Transcript_getDbID(trans));
  
  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

  sth->execute(sth);

  // 
  // Did this to be consistent with fetch_by_Gene, but don't like
  // it (filling in the object). I think returning the array would
  // be better. Oh well. EB
  //
  
  while ((row = sth->fetchRow(sth))) {
    IDType translationId = row->getLongLongAt(row,0);
    Vector *translatLinks = DBEntryAdaptor_fetchByObjectType(dbea, translationId,"Translation");
    for (i=0;i<Vector_getNumElement(translatLinks); i++) {
      Transcript_addDBLink(trans,Vector_getElementAt(translatLinks,i));
    }
    Vector_free(translatLinks);
  }

  sth->finish(sth);

  transLinks = DBEntryAdaptor_fetchByObjectType(dbea, Transcript_getDbID(trans),"Transcript");
      fprintf(stderr,"transLinks\n");
  for (i=0;i<Vector_getNumElement(transLinks); i++) {
    Transcript_addDBLink(trans,Vector_getElementAt(transLinks,i));
  }
  Vector_free(transLinks);

  return 1;
}
예제 #10
0
SyntenyRegion *SyntenyRegionAdaptor_fetchByDbID(SyntenyRegionAdaptor *sra, IDType dbID) {
  StatementHandle *sth;
  ResultRow *row;
  char qStr[1024];
  SyntenyRegion *sr = NULL;
  int ok = 1;
  
  if (!dbID) {
    fprintf(stderr,"Error: SyntenyRegionAdaptor_fetchByDbID with no dbID!\n");
    ok = 0;
  }

  if (ok) {
    sprintf(qStr,
            "select synteny_cluster_id,"
            "       dnafrag_id,"
            "       seq_start,"
            "       seq_end"
            " from synteny_region "
            " where synteny_region_id = " IDFMTSTR,
            dbID);
           
    sth = sra->prepare((BaseAdaptor *)sra, qStr, strlen(qStr));
    sth->execute(sth);

    if (!(row = sth->fetchRow(sth))) {
      fprintf(stderr,"Error: No such dbID " IDFMTSTR "\n",dbID);
      ok = 0;
    }
  }

  if (ok) {
    sr =  SyntenyRegionAdaptor_newRegionFromArray(sra, 
                                                  dbID,
                                                  row->getLongLongAt(row,0),
                                                  row->getLongLongAt(row,1), 
                                                  row->getIntAt(row,2),
                                                  row->getIntAt(row,3));
    sth->finish(sth);
  }

  return sr;
}
예제 #11
0
/*
# _store_type
*/
IDType AttributeAdaptor_storeType(AttributeAdaptor *ata, Attribute *attrib) {
  char qStr[1024];
  sprintf(qStr,"INSERT IGNORE INTO attrib_type set code = '%s', name = '%s', description = '%s'", 
          Attribute_getCode(attrib), 
          Attribute_getName(attrib), 
          Attribute_getDescription(attrib));

  StatementHandle *sth1 = ata->prepare((BaseAdaptor *)ata,qStr,strlen(qStr));

// Not sure if this returns the num rows!
  int rowsInserted = sth1->execute(sth1);

  IDType atId = sth1->getInsertId(sth1);

  if (rowsInserted == 0) {
    // the insert failed because the code is already stored
    sprintf(qStr,"SELECT attrib_type_id FROM attrib_type WHERE code = '%s'", Attribute_getCode(attrib));

    StatementHandle *sth2 = ata->prepare((BaseAdaptor *)ata,qStr,strlen(qStr));
    
    sth2->execute(sth2);
 
    if (sth2->numRows(sth2) == 0) {
      atId = 0;
    } else {
      ResultRow *row = sth2->fetchRow(sth2);
      atId = row->getLongLongAt(row, 0);
    }

    if (!atId) {
      fprintf(stderr, "Could not store or fetch attrib_type code [%s]\n"
	              "Wrong database user/permissions?\n", Attribute_getCode(attrib));
      return 0;
    }
    sth2->finish(sth2);
  }

  sth1->finish(sth1);

  // fprintf(stderr, "atId in end is "IDFMTSTR"\n", atId);
  return atId;
}
예제 #12
0
IDType HomologyAdaptor_getRelationship(HomologyAdaptor *ha, char *qStr) {
  StatementHandle *sth;
  ResultRow *row;
  IDType relId;
  

  sth = ha->prepare((BaseAdaptor *)ha, qStr, strlen(qStr));
  sth->execute(sth);

  if ((row = sth->fetchRow(sth))) {
    relId = row->getLongLongAt(row,0);
  } else {
    fprintf(stderr, "Error: No relationship found by %s\n",qStr);
    relId = 0;
  }

  sth->finish(sth);

  return relId;
}
예제 #13
0
/* 
  In perl note this is misspelled compared to normal _objs_from_sth
  Not sure if that's deliberate to avoid clash or just an error
  Obviously this isn't called through the normal path at all
  (just directly from within the fetch method).
*/
Vector *AttributeAdaptor_objectsFromStatementHandle(AttributeAdaptor *ata, StatementHandle *sth) {
  Vector *results = Vector_new();

  ResultRow *row;
// Note extra parentheses are to keep mac compiler happy
  while ((row = sth->fetchRow(sth))) {
    char *code  = row->getStringAt(row, 0);
    char *name  = row->getStringAt(row, 1);
    char *desc  = row->getStringAt(row, 2);
    char *value = row->getStringAt(row, 3);

    Attribute *attr = Attribute_new();
    Attribute_setCode(attr, code);
    Attribute_setName(attr, name);
    Attribute_setDescription(attr, desc);
    Attribute_setValue(attr, value);
    
    Vector_addElement(results, attr);
  }

  return results;
}
예제 #14
0
IDType DBEntryAdaptor_exists(DBEntryAdaptor *dbea, DBEntry *dbe) {
  char qStr[512];
  StatementHandle *sth;
  ResultRow *row;
  IDType dbID;

  if (!dbe || !Class_isDescendent(CLASS_DBENTRY, dbe->objectType)) {
    fprintf(stderr,"Error: arg must be a DBEntry\n");
    exit(1);
  }

// NIY Was dbe->external_db instead of dbe->dbname - are they different?
// NIY mysql_quote strings
  sprintf(qStr,
              "SELECT x.xref_id "
              " FROM   xref x, external_db xdb"
              " WHERE  x.external_db_id = xdb.external_db_id"
              " AND    x.display_label = '%s' "
              " AND    xdb.db_name = '%s'",
          DBEntry_getDisplayId(dbe),
          DBEntry_getDbName(dbe));
  

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

  sth->execute(sth);

  row = sth->fetchRow(sth);
  if( row == NULL ) {
    sth->finish(sth);
    return 0;
  }

  dbID = row->getLongLongAt(row,0);

  sth->finish(sth);

  return dbID;
}
/*
=head2 fetch_all_by_Transcript

  Arg[1]      : Bio::EnsEMBL::Transcript Transcript to search with
  Example     : my $ises = $isea->fetch_all_by_Transcript($transcript);
  Description : Uses the given Transcript to search for all instances of
                IntronSupportingEvidence linked to the transcript in the 
                database 
  Returntype  : ArrayRef of IntronSupportingEvidence objects
  Exceptions  : Thrown if arguments are not as stated and for DB errors 

=cut
*/
Vector *IntronSupportingEvidenceAdaptor_fetchAllByTranscript(IntronSupportingEvidenceAdaptor *isea, Transcript *transcript) {
  char qStr[1024];

  sprintf(qStr,"SELECT intron_supporting_evidence_id "
                 "FROM transcript_intron_supporting_evidence "
                "WHERE transcript_id = "IDFMTSTR, Transcript_getDbID(transcript));

  StatementHandle *sth = isea->prepare((BaseAdaptor *)isea,qStr,strlen(qStr));
  sth->execute(sth);

  Vector *idVec = Vector_new();
  ResultRow *row;
  while ((row = sth->fetchRow(sth))) {
    IDType id = row->getLongLongAt(row, 0);
    IDType *idP;

    if ((idP = calloc(1,sizeof(IDType))) == NULL) {
      fprintf(stderr, "Failed allocating space for a id\n");
      exit(1);
    }

    *idP = id;
    Vector_addElement(idVec, idP);
  }
  sth->finish(sth);

  Vector *out;
  if (Vector_getNumElement(idVec) > 0) {
    out = IntronSupportingEvidenceAdaptor_fetchAllByDbIDList(isea, idVec, NULL); 
  } else {
    out = Vector_new();
  }
 
  // Free ids vector
  Vector_setFreeFunc(idVec, free);
  Vector_free(idVec);

  return out;
}
예제 #16
0
Vector *SyntenyRegionAdaptor_fetchByClusterId(SyntenyRegionAdaptor *sra, IDType clusterId) {
  char qStr[256];
  StatementHandle *sth;
  ResultRow *row;
  Vector *out = NULL;

  if (!clusterId) {
    fprintf(stderr, "Error: fetch_by_cluster_id with no cluster_id!\n");
  } else {
    sprintf(qStr,
            "select synteny_region_id,"
            "       dnafrag_id,"
            "       seq_start,"
            "       seq_end "
            " from synteny_region "
            " where synteny_cluster_id = " IDFMTSTR, clusterId);

    sth = sra->prepare((BaseAdaptor *)sra, qStr, strlen(qStr));
    sth->execute(sth);

    out = Vector_new();
    while ((row = sth->fetchRow(sth))) {
      SyntenyRegion *sr = SyntenyRegionAdaptor_newRegionFromArray(sra, 
                                                                  row->getLongLongAt(row,0),
                                                                  clusterId,
                                                                  row->getLongLongAt(row,1), 
                                                                  row->getIntAt(row,2),
                                                                  row->getIntAt(row,3));
    
      Vector_addElement(out,sr);
    }
    sth->finish(sth);
  }

  return out;
}
// Switch to passing two element array to fill in as an argument, so don't have to allocate it
IDType *IntronSupportingEvidenceAdaptor_fetchFlankingExonIds(IntronSupportingEvidenceAdaptor *isea, IntronSupportingEvidence *ise, Transcript *transcript, IDType *flanks) {
  char qStr[1024];

  sprintf(qStr,"SELECT previous_exon_id, next_exon_id "
                 "FROM transcript_intron_supporting_evidence "
                "WHERE transcript_id ="IDFMTSTR" and intron_supporting_evidence_id ="IDFMTSTR, 
          Transcript_getDbID(transcript), IntronSupportingEvidence_getDbID(ise));

  StatementHandle *sth = isea->prepare((BaseAdaptor *)isea,qStr,strlen(qStr));
  sth->execute(sth);

  if (sth->numRows(sth) == 0) {
    return NULL;
  }
  
  ResultRow *row = sth->fetchRow(sth);

  flanks[0] = row->getLongLongAt(row, 0);
  flanks[1] = row->getLongLongAt(row, 1);

  sth->finish(sth);

  return flanks;
}
예제 #18
0
int HomologyAdaptor_getRelationships(HomologyAdaptor *ha, char *qStr, IDType **idsP) {
  StatementHandle *sth;
  ResultRow *row;
  int nAlloced = 2;
  int nId = 0;
  int ok = 1;

  sth = ha->prepare((BaseAdaptor *)ha, qStr, strlen(qStr));
  sth->execute(sth);

  if ((*idsP = (IDType *)calloc(nAlloced,sizeof(IDType))) == NULL) {
    fprintf(stderr,"Error: Failed allocating idsP\n");
    ok = 0;
  }

  if (ok) {
    while ((row = sth->fetchRow(sth))) {
      if (nId == nAlloced) {
        nAlloced = (nAlloced *2);
        if ((*idsP = (IDType *)realloc(*idsP,nAlloced*sizeof(IDType))) == NULL) {
          fprintf(stderr,"Error: Failed reallocating idsP\n");
          ok = 0;
          break;
        }
      }

      (*idsP)[nId++] = row->getLongLongAt(row,0); 
    }
  }

  if (ok) {
    sth->finish(sth);
  }

  return nId;
}
예제 #19
0
Vector *HomologyAdaptor_getHomologues(HomologyAdaptor *ha, char *qStr) {
  StatementHandle *sth;
  ResultRow *row;
  Vector *genes;

  sth = ha->prepare((BaseAdaptor *)ha, qStr, strlen(qStr));
  sth->execute(sth);

  genes = Vector_new();
  while ((row = sth->fetchRow(sth))) {
    Homology *homol = Homology_new();
    Homology_setSpecies(homol, row->getStringAt(row,1));
    Homology_setStableId(homol, row->getStringAt(row,0));
    Homology_setChromosome(homol, row->getStringAt(row,2));
    Homology_setChrStart(homol, row->getIntAt(row,3));
    Homology_setChrEnd(homol, row->getIntAt(row,4));
        
    Vector_addElement(genes,homol);
  }

  sth->finish(sth);

  return genes;
}
예제 #20
0
Vector *DBEntryAdaptor_fetchByObjectType(DBEntryAdaptor *dbea, IDType ensObj, char *ensType) {
  Vector *out;
  char qStr[1024];
  StatementHandle *sth;
  ResultRow *row;
  IDHash *seen;
  
  if (!ensObj) {
    fprintf(stderr,"Error: Can't fetchByObjectType without an object\n");
    exit(1);
  }

  if (!ensType) {
    fprintf(stderr,"Error: Can't fetchByObjectType without a type\n");
    exit(1);
  }

// Not sure if idt identities are right way round
  sprintf(qStr,
    "SELECT xref.xref_id, xref.dbprimary_acc, xref.display_label, xref.version,"
    "       xref.description,"
    "       exDB.db_name, exDB.db_release, exDB.status," 
    "       oxr.object_xref_id,"
    "       es.synonym," 
    "       idt.xref_identity, idt.ensembl_identity"
    " FROM  (external_db exDB, object_xref oxr, xref xref)" 
    " LEFT JOIN external_synonym es on es.xref_id = xref.xref_id"
    " LEFT JOIN identity_xref idt on idt.object_xref_id = oxr.object_xref_id"
    " WHERE  xref.xref_id = oxr.xref_id"
    "  AND  xref.external_db_id = exDB.external_db_id"
    "  AND  oxr.ensembl_id = " IDFMTSTR
    "  AND  oxr.ensembl_object_type = '%s'",
    ensObj,
    ensType);
  
  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

  sth->execute(sth);

  seen = IDHash_new(IDHASH_SMALL);
  out = Vector_new();

  while ((row = sth->fetchRow(sth))) {
    DBEntry *exDB;
    IDType refID = row->getLongLongAt(row,0);
			    
    // using an outer join on the synonyms as well as on identity_xref, we
    // now have to filter out the duplicates (see v.1.18 for
    // original). Since there is at most one identity_xref row per xref,
    // this is easy enough; all the 'extra' bits are synonyms

    if (!IDHash_contains(seen,refID))  {
      exDB = DBEntry_new();
      DBEntry_setAdaptor(exDB,(BaseAdaptor *)dbea);
      DBEntry_setDbID(exDB, refID);
      DBEntry_setPrimaryId(exDB, row->getStringAt(row,1));
      DBEntry_setDisplayId(exDB, row->getStringAt(row,2));
      DBEntry_setVersion(exDB, row->getStringAt(row,3));
      DBEntry_setDbName(exDB, row->getStringAt(row,5));
      DBEntry_setRelease(exDB, row->getStringAt(row,6));

      if (row->col(row,10)) {
        IdentityXref *idx = IdentityXref_new();
        DBEntry_setIdentityXref(exDB,idx);
	IdentityXref_setQueryIdentity(idx, row->getDoubleAt(row,10));
	IdentityXref_setTargetIdentity(idx, row->getDoubleAt(row,11));
      }
      
      if (row->col(row,4)) DBEntry_setDescription(exDB, row->getStringAt(row,4));
      if (row->col(row,7)) DBEntry_setStatus(exDB, row->getStringAt(row,7));
      
      Vector_addElement(out, exDB);
      IDHash_add(seen, refID, exDB);
    } 

    exDB = IDHash_getValue(seen, refID);

    if (row->col(row,9)) {
      DBEntry_addSynonym(exDB,row->getStringAt(row,9));
    }
  }

  IDHash_free(seen, NULL);

  sth->finish(sth);
  
  return out;
}
예제 #21
0
Vector *GenomicAlignAdaptor_objectsFromStatementHandle(GenomicAlignAdaptor *gaa, StatementHandle *sth,
                                                       int reverse) {
  Vector *results = Vector_new();
  ResultRow *row;
  DNAFragAdaptor *dfa;

  IDType consensusDNAFragId;
  IDType queryDNAFragId;
  int consensusStart;
  int consensusEnd;
  int queryStart;
  int queryEnd;
  int queryStrand;
  IDType methodLinkId;
  double score;
  double percId;
  char *cigarString;

  dfa = ComparaDBAdaptor_getDNAFragAdaptor(gaa->dba);

  while ((row = sth->fetchRow(sth))) {
    GenomicAlign *genomicAlign;
    char *alignmentType;
    
    if (reverse) {
      queryDNAFragId     = row->getLongLongAt(row,0);
      queryStart         = row->getIntAt(row,1);
      queryEnd           = row->getIntAt(row,2);
      consensusDNAFragId = row->getLongLongAt(row,3);
      consensusStart     = row->getIntAt(row,4);
      consensusEnd       = row->getIntAt(row,5);
    } else {
      consensusDNAFragId = row->getLongLongAt(row,0);
      consensusStart     = row->getIntAt(row,1);
      consensusEnd       = row->getIntAt(row,2);
      queryDNAFragId     = row->getLongLongAt(row,3);
      queryStart         = row->getIntAt(row,4);
      queryEnd           = row->getIntAt(row,5);
    }
    queryStrand  = row->getIntAt(row,6);
    methodLinkId = row->getLongLongAt(row,7);
    score        = row->getDoubleAt(row,8);
    percId       = row->getDoubleAt(row,9);
    cigarString  = row->getStringAt(row,10);

    alignmentType = GenomicAlignAdaptor_alignmentTypeByMethodLinkId(gaa, methodLinkId);

    if (reverse) {
      StrUtil_strReplChrs(cigarString,"DI","ID");

      // alignment of the opposite strand
      if (queryStrand == -1) {
        cigarString = CigarStrUtil_reverse(cigarString, strlen(cigarString));
      }
    }
    
    
    genomicAlign = GenomicAlign_new();
    GenomicAlign_setAdaptor(genomicAlign, (BaseAdaptor *)gaa);
    GenomicAlign_setConsensusDNAFrag(genomicAlign, DNAFragAdaptor_fetchByDbID(dfa,consensusDNAFragId));
    GenomicAlign_setConsensusStart(genomicAlign, consensusStart);
    GenomicAlign_setConsensusEnd(genomicAlign, consensusEnd);
    GenomicAlign_setQueryDNAFrag(genomicAlign, DNAFragAdaptor_fetchByDbID(dfa,queryDNAFragId));
    GenomicAlign_setQueryStart(genomicAlign, queryStart);
    GenomicAlign_setQueryEnd(genomicAlign, queryEnd);
    GenomicAlign_setQueryStrand(genomicAlign, queryStrand);
    GenomicAlign_setAlignmentType(genomicAlign, alignmentType);
    GenomicAlign_setScore(genomicAlign, score);
    GenomicAlign_setPercentId(genomicAlign, percId);
    GenomicAlign_setCigarString(genomicAlign, cigarString);

    Vector_addElement(results, genomicAlign);
  }

  return results;
}
Vector *IntronSupportingEvidenceAdaptor_objectsFromStatementHandle(IntronSupportingEvidenceAdaptor *isea, 
                                                                   StatementHandle *sth,
                                                                   AssemblyMapper *assMapper,
                                                                   Slice *destSlice) {
  SliceAdaptor *sa     = DBAdaptor_getSliceAdaptor(isea->dba);
  AnalysisAdaptor *aa  = DBAdaptor_getAnalysisAdaptor(isea->dba);

  Vector *features = Vector_new();
  IDHash *sliceHash = IDHash_new(IDHASH_SMALL);
  
/* Unneccesary
  my %analysis_hash;
  my %sr_name_hash;
  my %sr_cs_hash;
*/
  

  
/* Unused
  my $asm_cs;
  my $cmp_cs;
  my $asm_cs_vers;
  my $asm_cs_name;
  my $cmp_cs_vers;
  my $cmp_cs_name;
  if($mapper) {
    $asm_cs = $mapper->assembled_CoordSystem();
    $cmp_cs = $mapper->component_CoordSystem();
    $asm_cs_name = $asm_cs->name();
    $asm_cs_vers = $asm_cs->version();
    $cmp_cs_name = $cmp_cs->name();
    $cmp_cs_vers = $cmp_cs->version();
  }
*/

  long         destSliceStart;
  long         destSliceEnd;
  int          destSliceStrand;
  long         destSliceLength;
  //CoordSystem *destSliceCs;
  char *       destSliceSrName;
  IDType       destSliceSrId = 0;
  //AssemblyMapperAdaptor *asma;

  if (destSlice) {
    destSliceStart  = Slice_getStart(destSlice);
    destSliceEnd    = Slice_getEnd(destSlice);
    destSliceStrand = Slice_getStrand(destSlice);
    destSliceLength = Slice_getLength(destSlice);
    //??destSliceCs     = Slice_getCoordSystem(destSlice);
    destSliceSrName = Slice_getSeqRegionName(destSlice);
    destSliceSrId   = Slice_getSeqRegionId(destSlice);
    //??asma            = DBAdaptor_getAssemblyMapperAdaptor(ea->dba);
  }

  ResultRow *row;
  while ((row = sth->fetchRow(sth))) {
    IDType id =           row->getLongLongAt(row,0);
    IDType analysisId =   row->getLongLongAt(row,1);
    IDType seqRegionId =  row->getLongLongAt(row,2);
    long seqRegionStart = row->getLongAt(row,3);
    long seqRegionEnd =   row->getLongAt(row,4);
    int seqRegionStrand = row->getIntAt(row,5);
    char *hitName =       row->getStringAt(row,6);
    double score =        row->getDoubleAt(row,7);
    char *scoreType =     row->getStringAt(row,8);
    int spliceCanonical = row->getIntAt(row,9); 

    // get the analysis object
    Analysis *analysis = AnalysisAdaptor_fetchByDbID(aa, analysisId);

/*
    // need to get the internal_seq_region, if present
    $seq_region_id = $self->get_seq_region_id_internal($seq_region_id);
    #get the slice object
    my $slice = $slice_hash{"ID:".$seq_region_id};
    if(!$slice) {
      $slice = $sa->fetch_by_seq_region_id($seq_region_id);
      $slice_hash{"ID:".$seq_region_id} = $slice;
      $sr_name_hash{$seq_region_id} = $slice->seq_region_name();
      $sr_cs_hash{$seq_region_id} = $slice->coord_system();
    }

    my $sr_name = $sr_name_hash{$seq_region_id};
    my $sr_cs   = $sr_cs_hash{$seq_region_id};
*/
    if (! IDHash_contains(sliceHash, seqRegionId)) {
      IDHash_add(sliceHash, seqRegionId, SliceAdaptor_fetchBySeqRegionId(sa, seqRegionId, POS_UNDEF, POS_UNDEF, STRAND_UNDEF));
    }
    Slice *slice = IDHash_getValue(sliceHash, seqRegionId);

    Slice *iseSlice = slice;
    
    char *srName      = Slice_getSeqRegionName(slice);
    CoordSystem *srCs = Slice_getCoordSystem(slice);

    // 
    // remap the feature coordinates to another coord system
    // if a mapper was provided
    //
    if (assMapper != NULL) {
      MapperRangeSet *mrs;

      // Slightly suspicious about need for this if statement so left in perl statements for now
      if (destSlice != NULL &&
          assMapper->objectType == CLASS_CHAINEDASSEMBLYMAPPER) {
        mrs = ChainedAssemblyMapper_map(assMapper, srName, seqRegionStart, seqRegionEnd, seqRegionStrand, srCs, 1, destSlice);
      } else {
        mrs = AssemblyMapper_fastMap(assMapper, srName, seqRegionStart, seqRegionEnd, seqRegionStrand, srCs, NULL);
      }

      // skip features that map to gaps or coord system boundaries
      //next FEATURE if (!defined($seq_region_id));
      if (MapperRangeSet_getNumRange(mrs) == 0) {
        continue;
      }
      MapperRange *range = MapperRangeSet_getRangeAt(mrs, 0);
      if (range->rangeType == MAPPERRANGE_GAP) {
        fprintf(stderr,"Got a mapper gap in gene obj_from_sth - not sure if this is allowed\n");
        exit(1);
      } else {
        MapperCoordinate *mc = (MapperCoordinate *)range;

        seqRegionId     = mc->id;
        seqRegionStart  = mc->start;
        seqRegionEnd    = mc->end;
        seqRegionStrand = mc->strand;
      }

      MapperRangeSet_free(mrs);

      
/* Was - but identical if and else so why test???
      #get a slice in the coord system we just mapped to
      if($asm_cs == $sr_cs || ($cmp_cs != $sr_cs && $asm_cs->equals($sr_cs))) {
        $slice = $slice_hash{"ID:".$seq_region_id} ||=
          $sa->fetch_by_seq_region_id($seq_region_id);
      } else {
        $slice = $slice_hash{"ID:".$seq_region_id} ||=
          $sa->fetch_by_seq_region_id($seq_region_id);
      }
*/
// Instead...
      if (! IDHash_contains(sliceHash, seqRegionId)) {
        IDHash_add(sliceHash, seqRegionId, SliceAdaptor_fetchBySeqRegionId(sa, seqRegionId, POS_UNDEF, POS_UNDEF, STRAND_UNDEF));
      }
      iseSlice = IDHash_getValue(sliceHash, seqRegionId);
    }


    //
    // If a destination slice was provided convert the coords
    // If the dest_slice starts at 1 and is foward strand, nothing needs doing
    // 
    if (destSlice != NULL) {
      if (destSliceStart != 1 || destSliceStrand != 1) {
        if (destSliceStrand == 1) {
          seqRegionStart = seqRegionStart - destSliceStart + 1;
          seqRegionEnd   = seqRegionEnd - destSliceStart + 1;
        } else {
          long tmpSeqRegionStart = seqRegionStart;
          seqRegionStart = destSliceEnd - seqRegionEnd + 1;
          seqRegionEnd   = destSliceEnd - tmpSeqRegionStart + 1;

          seqRegionStrand = -seqRegionStrand;
        }
      }
       
      // throw away features off the end of the requested slice
      if (seqRegionEnd < 1 || seqRegionStart > destSliceLength || (destSliceSrId != seqRegionId)) {
        continue;
      }
      iseSlice = destSlice;
    }
    
    IntronSupportingEvidence *ise = IntronSupportingEvidence_new();

    IntronSupportingEvidence_setStart             (ise, seqRegionStart);
    IntronSupportingEvidence_setEnd               (ise, seqRegionEnd);
    IntronSupportingEvidence_setStrand            (ise, seqRegionStrand);
    IntronSupportingEvidence_setSlice             (ise, iseSlice);
    IntronSupportingEvidence_setAnalysis          (ise, analysis);
    IntronSupportingEvidence_setAdaptor           (ise, (BaseAdaptor *)isea);
    IntronSupportingEvidence_setDbID              (ise, id);
    IntronSupportingEvidence_setHitName           (ise, hitName);
    IntronSupportingEvidence_setScore             (ise, score);
    IntronSupportingEvidence_setScoreType         (ise, scoreType);
    IntronSupportingEvidence_setIsSpliceCanonical(ise, spliceCanonical);

    Vector_addElement(features, ise);
  }
  
  return features;
}
예제 #23
0
// For ordered, the default should be 0 (if you just need to fill out the args)
// Note ONLY stable_id can be char, all other pk's must be IDType (see code)
Vector *BaseAdaptor_listDbIDs(BaseAdaptor *ba, char *table, char *pk, int ordered) {
  int ok = 1;
  char colName[1024];

  if (pk == NULL) {
    sprintf(colName, "%s_id", table);
  } else {
    strcpy(colName, pk);
  }

  char qStr[1024];
  sprintf(qStr,"SELECT `%s` FROM `%s`", colName, table );

  if ( BaseAdaptor_isMultiSpecies(BaseAdaptor *ba)
      // For now just the multi species because I don't have adaptors in the Class hierarchy
      // && $self->isa('Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor')
      // && !$self->isa('Bio::EnsEMBL::DBSQL::UnmappedObjectAdaptor') 
     ) {
    char tmpStr[1024];
    
    sprintf(tmpStr, "JOIN seq_region USING (seq_region_id) "
                    "JOIN coord_system cs USING (coord_system_id) "
                    "WHERE cs.species_id = "IDFMTSTR, BaseAdaptor_getSpeciesId(ba));

    sprintf(qStr, "%s %s", qStr, tmpStr);
  }

  if (ordered) {
    sprintf(qStr, "%s ORDER BY seq_region_id, seq_region_start", qStr);
  }

  StatementHandle *sth = ba->prepare(ba,qStr,strlen(qStr));

  sth->execute(sth);

  Vector *out = Vector_new();

  if (strcmp(pk, "stable_id")) {
    ResultRow *row;
    while ((row = sth->fetchRow(sth))) {
      char *stableId = row->getStringCopyAt(row, 0);
  
      Vector_addElement(out, stableId);
    }
  } else  {
    IDType *idP;
    ResultRow *row;
    while ((row = sth->fetchRow(sth))) {
      IDType id = row->getLongLongAt(row, 0);
  
      if ((idP = calloc(1,sizeof(IDType))) == NULL) {
        fprintf(stderr, "Failed allocating space for a id\n");      
        ok = 0;
      } else {
        *idP = id;
        Vector_addElement(out, idP);
      }
    }
  }

  if (!ok) {
    Vector_free(out);
    out = NULL;
  }

  return out;
}
예제 #24
0
Vector *PredictionTranscriptAdaptor_fetchAllBySlice(PredictionTranscriptAdaptor *pta, Slice *slice, char *logicName, int loadExons) {

  //my $transcripts = $self->SUPER::fetch_all_by_Slice($slice,$logic_name);
  Vector *transcripts = BaseFeatureAdaptor_fetchAllBySlice((BaseFeatureAdaptor *)pta, slice, logicName);

  // if there are 0 or 1 transcripts still do lazy-loading
  if ( ! loadExons || Vector_getNumElement(transcripts) < 2 ) {
    return transcripts;
  }

  // preload all of the exons now, instead of lazy loading later
  // faster than 1 query per transcript

  // get extent of region spanned by transcripts
  long minStart =  2000000000;
  long maxEnd   = -2000000000;

  int i;
  for (i=0; i<Vector_getNumElement(transcripts); i++) {
    PredictionTranscript *t  = Vector_getElementAt(transcripts, i);
    if (PredictionTranscript_getSeqRegionStart((SeqFeature*)t) < minStart) {
      minStart = PredictionTranscript_getSeqRegionStart((SeqFeature*)t);
    }
    if (PredictionTranscript_getSeqRegionEnd((SeqFeature*)t) > maxEnd) {
      maxEnd = PredictionTranscript_getSeqRegionEnd((SeqFeature*)t);
    }
  }

  Slice *extSlice;

  if (minStart >= Slice_getStart(slice) && maxEnd <= Slice_getEnd(slice)) {
    extSlice = slice;
  } else {
    SliceAdaptor *sa = DBAdaptor_getSliceAdaptor(pta->dba);
    extSlice = SliceAdaptor_fetchByRegion(sa, Slice_getCoordSystemName(slice), Slice_getSeqRegionName(slice),
                                          minStart, maxEnd, Slice_getStrand(slice), CoordSystem_getVersion(Slice_getCoordSystem(slice)), 0);
  }

  // associate exon identifiers with transcripts
  IDHash *trHash = IDHash_new(IDHASH_MEDIUM);
  for (i=0; i<Vector_getNumElement(transcripts); i++) {
    PredictionTranscript *t  = Vector_getElementAt(transcripts, i);
    if ( ! IDHash_contains(trHash, PredictionTranscript_getDbID(t))) {
      IDHash_add(trHash, PredictionTranscript_getDbID(t), t);
    }
  }

  IDType *uniqueIds = IDHash_getKeys(trHash);

  char tmpStr[1024];
  char *qStr = NULL;
  if ((qStr = (char *)calloc(655500,sizeof(char))) == NULL) {
    fprintf(stderr,"Failed allocating qStr\n");
    return transcripts;
  }

  int lenNum;
  int endPoint = sprintf(qStr, "SELECT prediction_transcript_id, prediction_exon_id, exon_rank FROM prediction_exon WHERE  prediction_transcript_id IN (");
  for (i=0; i<IDHash_getNumValues(trHash); i++) {
    if (i!=0) {
      qStr[endPoint++] = ',';
      qStr[endPoint++] = ' ';
    }
    lenNum = sprintf(tmpStr,IDFMTSTR,uniqueIds[i]);
    memcpy(&(qStr[endPoint]), tmpStr, lenNum);
    endPoint+=lenNum;
  }
  qStr[endPoint++] = ')';
  qStr[endPoint] = '\0';

  free(uniqueIds);

  StatementHandle *sth = pta->prepare((BaseAdaptor *)pta,qStr,strlen(qStr));
  sth->execute(sth);

  IDHash *exTrHash = IDHash_new(IDHASH_MEDIUM);
  ResultRow *row;
  while ((row = sth->fetchRow(sth))) {
    IDType trId = row->getLongLongAt(row,0);
    IDType exId = row->getLongLongAt(row,1);
    int    rank = row->getIntAt(row,2);

    if (! IDHash_contains(exTrHash, exId)) {
      Vector *vec = Vector_new();
      Vector_setFreeFunc(vec, PredictionTranscriptRankPair_free);
      IDHash_add(exTrHash, exId, vec);
    }
    Vector *exVec = IDHash_getValue(exTrHash, exId);
    PredictionTranscriptRankPair *trp = PredictionTranscriptRankPair_new(IDHash_getValue(trHash, trId), rank);
    Vector_addElement(exVec, trp);
  }

  IDHash_free(trHash, NULL);

  sth->finish(sth);

  PredictionExonAdaptor *pea = DBAdaptor_getPredictionExonAdaptor(pta->dba);
  Vector *exons = PredictionExonAdaptor_fetchAllBySlice(pea, extSlice);

  // move exons onto transcript slice, and add them to transcripts
  for (i=0; i<Vector_getNumElement(exons); i++) {
    PredictionExon *ex = Vector_getElementAt(exons, i);

  // Perl didn't have this line - it was in GeneAdaptor version so I think I'm going to keep it
    if (!IDHash_contains(exTrHash, PredictionExon_getDbID(ex))) continue;

    PredictionExon *newEx;
    if (slice != extSlice) {
      newEx = (PredictionExon*)PredictionExon_transfer((SeqFeature*)ex, slice);
      if (newEx == NULL) {
        fprintf(stderr, "Unexpected. Exon could not be transferred onto PredictionTranscript slice.\n");
        exit(1);
      }
    } else {
      newEx = ex;
    }

    Vector *exVec = IDHash_getValue(exTrHash, PredictionExon_getDbID(newEx));
    int j;
    for (j=0; j<Vector_getNumElement(exVec); j++) {
      PredictionTranscriptRankPair *trp = Vector_getElementAt(exVec, j);
      PredictionTranscript_addExon(trp->transcript, newEx, &trp->rank);
    }
  }

  IDHash_free(exTrHash, Vector_free);
  free(qStr);

  return transcripts;
}
예제 #25
0
/*
=head2 _objs_from_sth

  Arg [1]    : DBI:st $sth 
               An executed DBI statement handle
  Arg [2]    : (optional) Bio::EnsEMBL::Mapper $mapper 
               An mapper to be used to convert contig coordinates
               to assembly coordinates.
  Arg [3]    : (optional) Bio::EnsEMBL::Slice $slice
               A slice to map the prediction transcript to.   
  Example    : $p_transcripts = $self->_objs_from_sth($sth);
  Description: Creates a list of Prediction transcripts from an executed DBI
               statement handle.  The columns retrieved via the statement 
               handle must be in the same order as the columns defined by the
               _columns method.  If the slice argument is provided then the
               the prediction transcripts will be in returned in the coordinate
               system of the $slice argument.  Otherwise the prediction 
               transcripts will be returned in the RawContig coordinate system.
  Returntype : reference to a list of Bio::EnsEMBL::PredictionTranscripts
  Exceptions : none
  Caller     : superclass generic_fetch
  Status     : Stable

=cut
*/
Vector *PredictionTranscriptAdaptor_objectsFromStatementHandle(PredictionTranscriptAdaptor *pta, 
                                                               StatementHandle *sth, 
                                                               AssemblyMapper *assMapper, 
                                                               Slice *destSlice) {
  SliceAdaptor *sa     = DBAdaptor_getSliceAdaptor(pta->dba);
  AnalysisAdaptor *aa  = DBAdaptor_getAnalysisAdaptor(pta->dba);

  Vector *pTranscripts = Vector_new();
  IDHash *sliceHash = IDHash_new(IDHASH_SMALL);

  long         destSliceStart;
  long         destSliceEnd;
  int          destSliceStrand;
  long         destSliceLength;
  char *       destSliceSrName;
  IDType       destSliceSrId = 0;

  if (destSlice) {
    destSliceStart  = Slice_getStart(destSlice);
    destSliceEnd    = Slice_getEnd(destSlice);
    destSliceStrand = Slice_getStrand(destSlice);
    destSliceLength = Slice_getLength(destSlice);
    destSliceSrName = Slice_getSeqRegionName(destSlice);
    destSliceSrId   = Slice_getSeqRegionId(destSlice);
  }

  ResultRow *row;
  while ((row = sth->fetchRow(sth))) {
    IDType predictionTranscriptId = row->getLongLongAt(row,0);
    IDType seqRegionId            = row->getLongLongAt(row,1);
    long seqRegionStart           = row->getLongAt(row,2);
    long seqRegionEnd             = row->getLongAt(row,3);
    int seqRegionStrand           = row->getIntAt(row,4);
    IDType analysisId             = row->getLongLongAt(row,5);
    char *displayLabel            = row->getStringAt(row,6);

    // get the analysis object
    Analysis *analysis = AnalysisAdaptor_fetchByDbID(aa, analysisId);

    if (! IDHash_contains(sliceHash, seqRegionId)) {
      IDHash_add(sliceHash, seqRegionId, SliceAdaptor_fetchBySeqRegionId(sa, seqRegionId, POS_UNDEF, POS_UNDEF, STRAND_UNDEF));
    }
    Slice *slice = IDHash_getValue(sliceHash, seqRegionId);

    Slice *ptSlice = slice;

    char *srName      = Slice_getSeqRegionName(slice);
    CoordSystem *srCs = Slice_getCoordSystem(slice);

    //
    // remap the feature coordinates to another coord system
    // if a mapper was provided
    //
    if (assMapper != NULL) {
      MapperRangeSet *mrs;

      // Slightly suspicious about need for this if statement so left in perl statements for now
      if (destSlice != NULL &&
          assMapper->objectType == CLASS_CHAINEDASSEMBLYMAPPER) {
        mrs = ChainedAssemblyMapper_map(assMapper, srName, seqRegionStart, seqRegionEnd, seqRegionStrand, srCs, 1, destSlice);
      } else {
        mrs = AssemblyMapper_fastMap(assMapper, srName, seqRegionStart, seqRegionEnd, seqRegionStrand, srCs, NULL);
      }

      // skip features that map to gaps or coord system boundaries
      if (MapperRangeSet_getNumRange(mrs) == 0) {
        continue;
      }
      MapperRange *range = MapperRangeSet_getRangeAt(mrs, 0);
      if (range->rangeType == MAPPERRANGE_GAP) {
        fprintf(stderr,"Got a mapper gap in gene obj_from_sth - not sure if this is allowed\n");
        exit(1);
      } else {
        MapperCoordinate *mc = (MapperCoordinate *)range;

        seqRegionId     = mc->id;
        seqRegionStart  = mc->start;
        seqRegionEnd    = mc->end;
        seqRegionStrand = mc->strand;
      }

      MapperRangeSet_free(mrs);

      if (! IDHash_contains(sliceHash, seqRegionId)) {
        IDHash_add(sliceHash, seqRegionId, SliceAdaptor_fetchBySeqRegionId(sa, seqRegionId, POS_UNDEF, POS_UNDEF, STRAND_UNDEF));
      }
      ptSlice = IDHash_getValue(sliceHash, seqRegionId);
    }

    //
    // If a destination slice was provided convert the coords
    // If the dest_slice starts at 1 and is foward strand, nothing needs doing
    //
    if (destSlice != NULL) {
      if (destSliceStart != 1 || destSliceStrand != 1) {
        if (destSliceStrand == 1) {
          seqRegionStart = seqRegionStart - destSliceStart + 1;
          seqRegionEnd   = seqRegionEnd - destSliceStart + 1;
        } else {
          long tmpSeqRegionStart = seqRegionStart;
          seqRegionStart = destSliceEnd - seqRegionEnd + 1;
          seqRegionEnd   = destSliceEnd - tmpSeqRegionStart + 1;

          seqRegionStrand = -seqRegionStrand;
        }
      }
      // throw away features off the end of the requested slice
      if (seqRegionEnd < 1 || seqRegionStart > destSliceLength || (destSliceSrId != seqRegionId)) {
        continue;
      }
      ptSlice = destSlice;
    }
    
    // Finally, create the new PredictionTranscript.
    PredictionTranscript *pt = PredictionTranscript_new();

    PredictionTranscript_setStart       (pt, seqRegionStart);
    PredictionTranscript_setEnd         (pt, seqRegionEnd);
    PredictionTranscript_setStrand      (pt, seqRegionStrand);
    PredictionTranscript_setSlice       (pt, ptSlice);
    PredictionTranscript_setAnalysis    (pt, analysis);
    PredictionTranscript_setAdaptor     (pt, (BaseAdaptor *)pta);
    PredictionTranscript_setDbID        (pt, predictionTranscriptId);
    PredictionTranscript_setDisplayLabel(pt, displayLabel);

    Vector_addElement(pTranscripts, pt);
  }

  IDHash_free(sliceHash, NULL);
  return pTranscripts;
}
// This method was a mess - tidied and rearranged
IDType IntronSupportingEvidenceAdaptor_store(IntronSupportingEvidenceAdaptor *isea, IntronSupportingEvidence *sf)  {
  if (sf == NULL) {
    fprintf(stderr,"sf is NULL in IntronSupportingEvidenceAdaptor_store\n");
    exit(1);
  }

  Class_assertType(CLASS_INTRONSUPPORTINGEVIDENCE, sf->objectType);
  
  DBAdaptor *db = isea->dba;
  AnalysisAdaptor *analysisAdaptor = DBAdaptor_getAnalysisAdaptor(db);
  
  if (IntronSupportingEvidence_isStored(sf, db)) {
    fprintf(stderr,"ISE already stored\n");
    return IntronSupportingEvidence_getDbID(sf);
  }
  
  Analysis *analysis = IntronSupportingEvidence_getAnalysis(sf);

  if (!Analysis_isStored(analysis, db)) {
    AnalysisAdaptor_store(analysisAdaptor, analysis);
  }
  IDType analysisId = Analysis_getDbID(analysis);

  // Think the above is equivalent to this horror
  //my $analysis_id = $analysis->is_stored($db) ? $analysis->dbID() : $db->get_AnalysisAdaptor()->store($analysis);
  
/* No transfer (see GeneAdaptor for why)
  my $seq_region_id;
  ($sf, $seq_region_id) = $self->_pre_store($sf);
*/

  IDType seqRegionId = BaseFeatureAdaptor_preStore((BaseFeatureAdaptor *)isea, (SeqFeature*)sf);

  char qStr[1024];
  sprintf(qStr, "INSERT IGNORE INTO intron_supporting_evidence "
                "(analysis_id, seq_region_id, seq_region_start, seq_region_end, seq_region_strand, hit_name, score, score_type, is_splice_canonical) "
                "VALUES ("IDFMTSTR","IDFMTSTR",%ld,%ld,%d,'%s',%f,'%s',%d)", 
                analysisId,
                seqRegionId,
          IntronSupportingEvidence_getSeqRegionStart((SeqFeature*)sf),
          IntronSupportingEvidence_getSeqRegionEnd((SeqFeature*)sf),
          IntronSupportingEvidence_getSeqRegionStrand((SeqFeature*)sf),
                IntronSupportingEvidence_getHitName(sf),
                IntronSupportingEvidence_getScore(sf),
                IntronSupportingEvidence_getScoreType(sf),
                IntronSupportingEvidence_getIsSpliceCanonical(sf));

  StatementHandle *sth = isea->prepare((BaseAdaptor *)isea,qStr,strlen(qStr));
  
  sth->execute(sth);
  IDType sfId = sth->getInsertId(sth);
  sth->finish(sth);

  if (!sfId) {
    sprintf(qStr,"SELECT intron_supporting_evidence_id "
                   "FROM intron_supporting_evidence "
                  "WHERE analysis_id = "IDFMTSTR
                   " AND seq_region_id = "IDFMTSTR
                   " AND seq_region_start = %ld"
                   " AND seq_region_end = %ld" 
                   " AND seq_region_strand = %d"
                   " AND hit_name = '%s'",
                analysisId,
                seqRegionId,
            IntronSupportingEvidence_getSeqRegionStart((SeqFeature*)sf),
            IntronSupportingEvidence_getSeqRegionEnd((SeqFeature*)sf),
            IntronSupportingEvidence_getSeqRegionStrand((SeqFeature*)sf),
                IntronSupportingEvidence_getHitName(sf));

    sth = isea->prepare((BaseAdaptor *)isea,qStr,strlen(qStr));
    sth->execute(sth);
    if (sth->numRows(sth) > 0) {
      ResultRow *row = sth->fetchRow(sth);
      sfId = row->getLongLongAt(row, 0);
    }
    sth->finish(sth);
  }
  
  IntronSupportingEvidence_setAdaptor((SeqFeature*)sf, (BaseAdaptor*)isea);
  IntronSupportingEvidence_setDbID(sf, sfId);

  return IntronSupportingEvidence_getDbID(sf);
}
예제 #27
0
IDType DBEntryAdaptor_store(DBEntryAdaptor *dbea, DBEntry *exObj, 
                            IDType ensObject, char *ensType, int ignoreRelease) {
  fprintf(stderr,"DBEntryAdaptor_store does not implement ignoreRelease functionality yet\n");

  char qStr[512];
  StatementHandle *sth;
  ResultRow *row;
  IDType dbRef;
  IDType dbX;

  //
  // Check for the existance of the external_db, throw if it does not exist
  //
  sprintf(qStr,
     "SELECT external_db_id"
     "  FROM external_db"
     " WHERE db_name = '%s'"
     "   AND db_release = %s",
     DBEntry_getDbName(exObj),
     DBEntry_getRelease(exObj));

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));
  sth->execute(sth);
    
  row = sth->fetchRow(sth);
  if( row == NULL ) {
    sth->finish(sth);
    fprintf(stderr,"Error: external_db [%s] release [%s] does not exist\n", 
            DBEntry_getDbName(exObj), DBEntry_getRelease(exObj));
    exit(1);
  }

  dbRef =  row->getLongLongAt(row,0);
  sth->finish(sth);
    
  //
  // Check for the existance of the external reference, add it if not present
  //
  sprintf(qStr,
       "SELECT xref_id"
       "  FROM xref"
       " WHERE external_db_id = " IDFMTSTR
       "   AND dbprimary_acc = '%s'"
       "   AND version = %s",
      dbRef,
      DBEntry_getPrimaryId(exObj),
      DBEntry_getVersion(exObj));

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));
  sth->execute(sth);

  row = sth->fetchRow(sth);
    
  if (row != NULL) {
    dbX =  row->getLongLongAt(row,0);
    sth->finish(sth);
  } else {
    //
    // store the new xref
    //

    // First finish the old sth
    sth->finish(sth);

// NIY Handling NULL values
    sprintf(qStr,
       "INSERT ignore INTO xref"
       " SET dbprimary_acc = '%s',"
       "    display_label = '%s',"
       "    version = %s,"
       "    description = '%s',"
       "    external_db_id = " IDFMTSTR,
       DBEntry_getPrimaryId(exObj),
       DBEntry_getDisplayId(exObj),
       DBEntry_getVersion(exObj),
       DBEntry_getDescription(exObj),
       dbRef
      );
    sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

    sth->execute(sth);
    dbX = sth->getInsertId(sth);

    sth->finish(sth);
	
    //
    // store the synonyms for the new xref
    // 
    if (DBEntry_getAllSynonyms(exObj)) {
      StatementHandle *checkSth;
      StatementHandle *storeSth;
      int i;
      Vector *synonyms;

      sprintf(qStr,
              "SELECT xref_id, synonym"
              " FROM external_synonym"
              " WHERE xref_id = %" IDFMTSTR
              " AND synonym = '%%s'");

      checkSth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

      sprintf(qStr,
        "INSERT ignore INTO external_synonym"
        " SET xref_id = %" IDFMTSTR ", synonym = '%%s'");     

      storeSth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

      synonyms = DBEntry_getAllSynonyms(exObj);

      for (i=0;i<Vector_getNumElement(synonyms); i++) {	    
        char *syn = Vector_getElementAt(synonyms,i);
        checkSth->execute(checkSth, dbX, syn);
        row = checkSth->fetchRow(checkSth);
        if (!row) {
          storeSth->execute(storeSth, dbX, syn);
        }
      }
  	
      checkSth->finish(checkSth);
      storeSth->finish(storeSth);
    }
  }

  //
  // check if the object mapping was already stored
  //
  sprintf(qStr,
           "SELECT xref_id"
           " FROM object_xref"
           " WHERE xref_id = " IDFMTSTR
           " AND   ensembl_object_type = '%s'"
           " AND   ensembl_id = " IDFMTSTR,
         dbX, ensType, ensObject);

  sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));

  sth->execute(sth);

  row = sth->fetchRow(sth);
// NOTE row will be invalid after this call but will still
//      indicate whether something was found
  sth->finish(sth);
    
  if (!row) {
    IDType Xidt;

    //
    // Store the reference to the internal ensembl object
    //
    sprintf(qStr,
         "INSERT ignore INTO object_xref"
         " SET xref_id = " IDFMTSTR ","
         "     ensembl_object_type = '%s',"
         "     ensembl_id = " IDFMTSTR,
        dbX, ensType, ensObject);

    sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));
	
    sth->execute(sth);
    DBEntry_setDbID(exObj, dbX);
    DBEntry_setAdaptor(exObj, (BaseAdaptor *)dbea);
      
    Xidt = sth->getInsertId(sth);

    //
    // If this is an IdentityXref need to store in that table too
    //
    if (DBEntry_getIdentityXref(exObj)) {
      IdentityXref *idx = DBEntry_getIdentityXref(exObj);
      sprintf(qStr,
             "INSERT ignore INTO identity_xref"
             " SET object_xref_id = " IDFMTSTR ","
             "     query_identity = %f,"
             "     target_identity = %f",
             Xidt, 
             IdentityXref_getQueryIdentity(idx),
             IdentityXref_getTargetIdentity(idx));

      sth = dbea->prepare((BaseAdaptor *)dbea,qStr,strlen(qStr));
      sth->execute(sth);
      sth->finish(sth);
    }
  } 
  return dbX;    
}