Exemplo n.º 1
0
/** Basic query functionality
 */
void query(void *db, char **argv, int argc) {
  int qargc;
  void *rec = NULL;
  wg_query *q;
  wg_query_arg *arglist;
  gint lock_id;

  arglist = make_arglist(db, argv, argc, &qargc);
  if(!arglist)
    return;

  if(!(lock_id = wg_start_read(db))) {
    fprintf(stderr, "failed to get lock on database\n");
    goto abrt1;
  }

  q = wg_make_query(db, NULL, 0, arglist, qargc);
  if(!q)
    goto abrt2;

/*  printf("query col: %d type: %d\n", q->column, q->qtype); */
  rec = wg_fetch(db, q);
  while(rec) {
    wg_print_record(db, (gint *) rec);
    printf("\n");
    rec = wg_fetch(db, q);
  }

  wg_free_query(db, q);
abrt2:
  wg_end_read(db, lock_id);
abrt1:
  free_arglist(db, arglist, qargc);
}
Exemplo n.º 2
0
/** Print rows from database
 *
 */
void selectdata(void *db, int howmany, int startingat) {

  void *rec = wg_get_first_record(db);
  int i, count;

  for(i=0;i<startingat;i++){
    if(rec == NULL) return;
    rec=wg_get_next_record(db,rec);
  }

  count=0;
  while(rec != NULL) {
    wg_print_record(db, (gint *) rec);
    printf("\n");
    count++;
    if(count == howmany) break;
    rec=wg_get_next_record(db,rec);
  }

  return;
}
Exemplo n.º 3
0
void run_demo(void* db) {
  void *rec = NULL, *firstrec = NULL, *nextrec = NULL;
                                /* Pointers to a database record */
  wg_int enc; /* Encoded data */
  wg_int lock_id; /* Id of an acquired lock (for releasing it later) */
  wg_int len;
  int i;
  int intdata, datedata, timedata;
  char strbuf[80];

  printf("********* Starting demo ************\n");

  /* Begin by creating a simple record of 3 fields and fill it
   * with integer data.
   */

  printf("Creating first record.\n");

  rec=wg_create_record(db, 3);
  if (rec==NULL) {
    printf("rec creation error.\n");
    return;
  }

  /* Encode a field, checking for errors */
  enc = wg_encode_int(db, 44);
  if(enc==WG_ILLEGAL) {
    printf("failed to encode an integer.\n");
    return;
  }

  /* Negative return value shows that an error occurred */
  if(wg_set_field(db, rec, 0, enc) < 0) {
    printf("failed to store a field.\n");
    return;
  }
  
  /* Skip error checking for the sake of brevity for the rest of fields */
  enc = wg_encode_int(db, -199999);
  wg_set_field(db, rec, 1, enc);
  wg_set_field(db, rec, 2, wg_encode_int(db, 0));

  /* Now examine the record we have created. Get record length,
   * encoded value of each field, data type and decoded value.
   */

  /* Negative return value shows an error. */
  len = wg_get_record_len(db, rec);
  if(len < 0) {
    printf("failed to get record length.\n");
    return;
  }
  printf("Size of created record at %p was: %d\n", rec, (int) len);

  for(i=0; i<len; i++) {
    printf("Reading field %d:", i);
    enc = wg_get_field(db, rec, i);
    if(wg_get_encoded_type(db, enc) != WG_INTTYPE) {
      printf("data was of unexpected type.\n");
      return;
    }
    intdata = wg_decode_int(db, enc);
    /* No error checking here. All integers are valid. */
    printf(" %d\n", intdata);
  }

  /* Fields can be erased by setting their value to 0 which always stands for NULL value. */
  printf("Clearing field 1.\n");
  
  wg_set_field(db, rec, 1, 0);

  if(wg_get_field(db, rec, 1)==0) {
    printf("Re-reading field 1 returned a 0 (NULL) field.\n");
  } else {
    printf("unexpected value \n");
    return;
  }

  /* Fields can be updated with data of any type (the type is not fixed). */
  printf("Updating field 0 to a floating-point number.\n");

  enc = wg_encode_double(db, 56.9988);
  wg_set_field(db, rec, 0, enc);
  
  enc = wg_get_field(db, rec, 0);
  if(wg_get_encoded_type(db, enc) == WG_DOUBLETYPE) {
    printf("Re-reading field 0 returned %f.\n", wg_decode_double(db, enc));
  } else {
    printf("data was of unexpected type.\n");
    return;
  }

  /* Create a next record. Let's assume we're in an environment where
   * the database is used concurrently, so there's a need to use locking.
   */

  printf("Creating second record.\n");

  /* Lock id of 0 means that the operation failed */
  lock_id = wg_start_write(db);
  if(!lock_id) {
    printf("failed to acquire lock.\n");
    return;
  }
    
  /* Do the write operation we acquired the lock for. */
  rec=wg_create_record(db, 6);
  
  /* Failing to release the lock would be fatal to database operation. */
  if(!wg_end_write(db, lock_id)) {
    printf("failed to release lock.\n");
    return;
  }

  if (!rec) {
    printf("rec creation error.\n");
    return;
  }

  /* Reading also requires locking./ */
  lock_id = wg_start_read(db);
  if(!lock_id) {
    printf("failed to acquire lock.\n");
    return;
  }

  /* Do our read operation... */
  len = wg_get_record_len(db, rec);

  /* ... and unlock immediately */
  if(!wg_end_read(db, lock_id)) {
    printf("failed to release lock.\n");
    return;
  }

  if(len < 0) {
    printf("failed to get record length.\n");
    return;
  }
  printf("Size of created record at %p was: %d\n", rec, (int) len);

  /* Let's find the first record in the database */
  lock_id = wg_start_read(db);
  firstrec = wg_get_first_record(db);
  wg_end_read(db, lock_id);
  if(!firstrec) {
    printf("Failed to find first record.\n");
    return;
  }

  printf("First record of database had address %p.\n", firstrec);
  
  /* Let's check what the next record is to demonstrate scanning records. */
  nextrec = firstrec;
  lock_id = wg_start_read(db);
  do {
    
    nextrec = wg_get_next_record(db, nextrec);
    if(nextrec)
      printf("Next record had address %p.\n", nextrec);   
  } while(nextrec);
  printf("Finished scanning database records.\n");
  wg_end_read(db, lock_id);
  
  /* Set fields to various values. Field 0 is not touched at all (un-
   * initialized). Field 1 is set to point to another record.
   */

  printf("Populating second record with data.\n");

  /* Let's use the first record we found to demonstrate storing
   * a link to a record in a field inside another record. */
  lock_id = wg_start_write(db);
  enc = wg_encode_record(db, firstrec);
  wg_set_field(db, rec, 1, enc);
  wg_end_write(db, lock_id);

  /* Now set other fields to various data types. To keep the example shorter,
   * the locking and unlocking operations are omitted (in real applications,
   * this would be incorrect usage if concurrent access is expected).
   */

  wg_set_field(db, rec, 2, wg_encode_str(db, "This is a char array", NULL));
  wg_set_field(db, rec, 3, wg_encode_char(db, 'a'));

  /* For time and date, we use current time in local timezone */
  enc = wg_encode_date(db, wg_current_localdate(db));
  if(enc==WG_ILLEGAL) {
    printf("failed to encode date.\n");
    return;
  }
  wg_set_field(db, rec, 4, enc);

  enc = wg_encode_time(db, wg_current_localtime(db));
  if(enc==WG_ILLEGAL) {
    printf("failed to encode time.\n");
    return;
  }
  wg_set_field(db, rec, 5, enc);

  /* Now read and print all the fields. */
  
  wg_print_record(db, (wg_int *) rec);   
  printf("\n");

  /* Date and time can be handled together as a datetime object. */
  datedata = wg_decode_date(db, wg_get_field(db, rec, 4));
  timedata = wg_decode_time(db, wg_get_field(db, rec, 5));
  wg_strf_iso_datetime(db, datedata, timedata, strbuf);
  printf("Reading datetime: %s.\n", strbuf);
  
  printf("Setting date and time to 2010-03-31, 12:59\n");

  /* Update date and time to arbitrary values using wg_strp_iso_date/time */
  wg_set_field(db, rec, 4,
    wg_encode_date(db, wg_strp_iso_date(db, "2010-03-31")));
  wg_set_field(db, rec, 5,
    wg_encode_time(db, wg_strp_iso_time(db, "12:59:00.33")));

  printf("Dumping the contents of the database:\n");
  wg_print_db(db);

  printf("********* Demo ended ************\n");
}
Exemplo n.º 4
0
static char* search(thread_data_p tdata, char* inparams[], char* invalues[], 
             int incount, int opcode) {
  char* database=tdata->database;             
  char *token=NULL;             
  int i,j,x,itmp;
  wg_int type=0;
  char* fields[MAXPARAMS]; // search fields
  char* values[MAXPARAMS]; // search values
  char* compares[MAXPARAMS]; // search comparisons
  char* types[MAXPARAMS]; // search value types
  char* cids=NULL;             
  wg_int ids[MAXIDS];  // select these ids only         
  int fcount=0, vcount=0, ccount=0, tcount=0; // array el counters for above
  char* sfields[MAXPARAMS]; // set / selected fields
  char* svalues[MAXPARAMS]; // set field values
  char* stypes[MAXPARAMS];  // set field types  
  int sfcount; // array el counters for above              
  int from=0;             
  unsigned long count,rcount,gcount,handlecount;
  void* db=NULL; // actual database pointer
  void *rec, *oldrec; 
  char* res;
  wg_query *wgquery;  // query datastructure built later
  wg_query_arg wgargs[MAXPARAMS]; 
  wg_int lock_id=0;  // non-0 iff lock set
  int searchtype=0; // 0: full scan, 1: record ids, 2: by fields             
  char errbuf[ERRBUF_LEN]; // used for building variable-content input param error strings only               
  
  // default max nr of rows shown/handled
  if (opcode==COUNT_CODE) count=LONG_MAX;  
  else count=MAXCOUNT;
  // -------check and parse cgi parameters, attach database ------------
  // set params to defaults
  for(i=0;i<MAXPARAMS;i++) {
    fields[i]=NULL; values[i]=NULL; compares[i]=NULL; types[i]=NULL;
    sfields[i]=NULL; svalues[i]=NULL; stypes[i]=NULL;
  }
  // set printing params to defaults
  tdata->format=1; // 1: json
  tdata->maxdepth=MAX_DEPTH_DEFAULT; // rec depth limit for printer
  tdata->showid=0; // add record id as first extra elem: 0: no, 1: yes
  tdata->strenc=2; // string special chars escaping:  0: just ", 1: urlencode, 2: json, 3: csv
  // find search parameters
  for(i=0;i<incount;i++) {
    if (strncmp(inparams[i],"recids",MAXQUERYLEN)==0) {
      cids=invalues[i];         
      x=0;     
      // set ids to defaults
      for(j=0;j<MAXIDS;j++) ids[j]=0;
      // split csv int list to ids int array      
      for(j=0;j<strlen(cids);j++) {
        if (atoi(cids+j) && atoi(cids+j)>0) ids[x++]=atoi(cids+j);        
        if (x>=MAXIDS) break;
        for(;j<strlen(cids) && cids[j]!=','; j++) {};
      }             
    } else if (strncmp(inparams[i],"fld",MAXQUERYLEN)==0) {
      res=handle_fld_param(tdata,inparams[i],invalues[i],
                           &sfields[sfcount],&svalues[sfcount],&stypes[sfcount],sfcount,errbuf);
      if (res!=NULL) return res; // return error string
      sfcount++;     
    } else if (strncmp(inparams[i],"field",MAXQUERYLEN)==0) {
      fields[fcount++]=invalues[i];       
    } else if (strncmp(inparams[i],"value",MAXQUERYLEN)==0) {
      values[vcount++]=invalues[i];
    } else if (strncmp(inparams[i],"compare",MAXQUERYLEN)==0) {
      compares[ccount++]=invalues[i];
    } else if (strncmp(inparams[i],"type",MAXQUERYLEN)==0) {
      types[tcount++]=invalues[i];
    } else if (strncmp(inparams[i],"from",MAXQUERYLEN)==0) {      
      from=atoi(invalues[i]);
    } else if (strncmp(inparams[i],"count",MAXQUERYLEN)==0) {      
      count=atoi(invalues[i]);    
    } else {  
      // handle generic parameters for all queries: at end of param check
      res=handle_generic_param(tdata,inparams[i],invalues[i],&token,errbuf);      
      if (res!=NULL) return res;  // return error string
    }      
  }
  // authorization
  if (opcode==DELETE_CODE || opcode==UPDATE_CODE) {
    if (!authorize(WRITE_LEVEL,tdata,database,token))
      return errhalt(NOT_AUTHORIZED_ERR,tdata); 
  } else {  
    if (!authorize(READ_LEVEL,tdata,database,token))
      return errhalt(NOT_AUTHORIZED_ERR,tdata);
  }  
  // all parameters and values were understood 
  if (tdata->format==0) {
    // csv     
    tdata->maxdepth=0; // record structure not printed for csv
    tdata->strenc=3; // only " replaced with ""
  }  
  // check search parameters
  if (cids!=NULL) {
    // query by record ids
    if (fcount) return errhalt(RECIDS_COMBINED_ERR,tdata);
    searchtype=1;
  } else if (!fcount) {
    // no search fields given
    if (vcount || ccount || tcount) return errhalt(NO_FIELD_ERR,tdata);
    else searchtype=0; // scan everything
  } else {
    // search by fields
    searchtype=2;
  }    
  // attach to database
  db=op_attach_database(tdata,database,READ_LEVEL);
  if (!db) return errhalt(DB_ATTACH_ERR,tdata);   
  // database attached OK
  // create output string buffer (may be reallocated later)  
  tdata->buf=str_new(INITIAL_MALLOC);
  if (tdata->buf==NULL) return errhalt(MALLOC_ERR,tdata);
  tdata->bufsize=INITIAL_MALLOC;
  tdata->bufptr=tdata->buf; 
  // check printing depth
  if (tdata->maxdepth>MAX_DEPTH_HARD) tdata->maxdepth=MAX_DEPTH_HARD;  
  // initial print
  if(!op_print_data_start(tdata,opcode==SEARCH_CODE))
  return err_clear_detach_halt(MALLOC_ERR,tdata);
  // zero counters
  rcount=0;
  gcount=0;  
  handlecount=0; // actual nr of records handled
  // get lock
  if (tdata->realthread && tdata->common->shutdown) return NULL; // for multithreading only
  lock_id = wg_start_read(db); // get read lock
  tdata->lock_id=lock_id;
  tdata->lock_type=READ_LOCK_TYPE;
  if (!lock_id) return err_clear_detach_halt(LOCK_ERR,tdata);
  // handle one of the cases
  if (searchtype==0) {
    // ------- full scan case  ---     
    rec=wg_get_first_record(db);
    while (rec!=NULL) {    
      if (rcount>=from) {
        gcount++;
        if (gcount>count) break;  
        if (opcode==COUNT_CODE) { 
          handlecount++; 
        } else if (opcode==SEARCH_CODE) {
          itmp=op_print_record(tdata,rec,gcount);
          if (!itmp) return err_clear_detach_halt(MALLOC_ERR,tdata);
        } else if (opcode==UPDATE_CODE) {
          itmp=op_update_record(tdata,db,rec,0,0);
          if (!itmp) handlecount++;
        }
      }
      oldrec=rec;
      rec=wg_get_next_record(db,rec);
      if (opcode==DELETE_CODE) {
        x=wg_get_record_len(db,oldrec);
        if (x>0) {
          itmp=op_delete_record(tdata,oldrec);
          if (!itmp) handlecount++;
          //else err_clear_detach_halt(DELETE_ERR,tdata);
        }  
      } 
      rcount++;
    }   
  } else if (searchtype==1) {
    // ------------ search by record ids: ------------               
    for(j=0; ids[j]!=0 && j<MAXIDS; j++) {    
      x=wg_get_encoded_type(db,ids[j]);
      if (x!=WG_RECORDTYPE) continue;
      rec=wg_decode_record(db,ids[j]);    
      if (rec==NULL) continue;
      x=wg_get_record_len(db,rec);
      if (x<=0) continue;      
      gcount++;
      if (gcount>count) break; 
      if (opcode==COUNT_CODE) handlecount++;
      else if (opcode==SEARCH_CODE) {
        itmp=op_print_record(tdata,rec,gcount);
        if (!itmp) return err_clear_detach_halt(MALLOC_ERR,tdata);
      } else if (opcode==UPDATE_CODE) {
          itmp=op_update_record(tdata,db,rec,0,0);
          if (!itmp) handlecount++;         
      } else if (opcode==DELETE_CODE) {
        // test that db is not null, otherwise we may corrupt the database
        oldrec=wg_get_first_record(db);
        if (oldrec!=NULL) {
          //wg_int objecthead=dbfetch((void*)db,(void*)rec);
          //printf("isfreeobject %d\n",isfreeobject((int)objecthead));
          wg_print_record(db,rec);
          itmp=op_delete_record(tdata,rec);
          printf("deletion result %d\n",itmp);
          if (!itmp) handlecount++;
          //else return err_clear_detach_halt(DELETE_ERR,tdata);        
        }  
      }      
    }           
  } else if (searchtype==2) {
    // ------------by field search case: ---------

    // create a query list datastructure    
    for(i=0;i<fcount;i++) {   
      // field num    
      if (!isint(fields[i])) return err_clear_detach_halt(NO_FIELD_ERR,tdata);
      itmp=atoi(fields[i]);
      if(itmp<0) return err_clear_detach_halt(NO_FIELD_ERR,tdata);
      // column to compare
      wgargs[i].column = itmp;    
      // comparison op: default equal
      wgargs[i].cond = encode_incomp(db,compares[i]);
      if (wgargs[i].cond==BAD_WG_VALUE) return err_clear_detach_halt(COND_ERR,tdata);    
      // valuetype: default guess from value later
      type=encode_intype(db,types[i]); 
      if (type==BAD_WG_VALUE) return err_clear_detach_halt(INTYPE_ERR,tdata);
      // encode value to compare with   
      wgargs[i].value =  encode_invalue(db,values[i],type);        
      if (wgargs[i].value==WG_ILLEGAL) return err_clear_detach_halt(INTYPE_ERR,tdata);
    }   
    
    // make the query structure       
    wgquery = wg_make_query(db, NULL, 0, wgargs, i);
    if (!wgquery) return err_clear_detach_halt(QUERY_ERR,tdata);
    
    // actually perform the query           
    if (tdata->maxdepth>MAX_DEPTH_HARD) tdata->maxdepth=MAX_DEPTH_HARD;
    while((rec = wg_fetch(db, wgquery))) {
      if (rcount>=from) {
        gcount++;                           
        if (opcode==COUNT_CODE) handlecount++;
        else if (opcode==SEARCH_CODE) {
          itmp=op_print_record(tdata,rec,gcount);
          if (!itmp) return err_clear_detach_halt(MALLOC_ERR,tdata);
        } else if (opcode==UPDATE_CODE) {
          itmp=op_update_record(tdata,db,rec,0,0);
          if (!itmp) handlecount++;          
        } else if (opcode==DELETE_CODE) {
          itmp=op_delete_record(tdata,rec);
          if (!itmp) handlecount++;
          //else return err_clear_detach_halt(DELETE_ERR,tdata);  
        }
      }  
      rcount++;
      if (gcount>=count) break;    
    }   
    // free query datastructure, 
    for(i=0;i<fcount;i++) wg_free_query_param(db, wgargs[i].value);
    wg_free_query(db,wgquery); 
  }
  // ----- cases  handled  ------
  // print a single number for count and delete
  if (opcode==COUNT_CODE || opcode==DELETE_CODE) {
    if(!str_guarantee_space(tdata,MIN_STRLEN)) 
      return err_clear_detach_halt(MALLOC_ERR,tdata);
    itmp=snprintf(tdata->bufptr,MIN_STRLEN,"%lu",handlecount);    
    tdata->bufptr+=itmp;
  }
  // release locks and detach
  if (!wg_end_read(db, lock_id)) {  // release read lock
    return err_clear_detach_halt(LOCK_RELEASE_ERR,tdata);
  }
  tdata->lock_id=0;
  op_detach_database(tdata,db);
  if(!op_print_data_end(tdata,opcode==SEARCH_CODE))
    return err_clear_detach_halt(MALLOC_ERR,tdata);
  return tdata->buf;
}