ndbgetval.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include "ndb.h"
  5. /*
  6. * search for a tuple that has the given 'attr=val' and also 'rattr=x'.
  7. * copy 'x' into 'buf' and return the whole tuple.
  8. *
  9. * return 0 if not found.
  10. */
  11. char*
  12. ndbgetvalue(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr, Ndbtuple **pp)
  13. {
  14. Ndbtuple *t, *nt;
  15. char *rv;
  16. Ndbs temps;
  17. if(s == nil)
  18. s = &temps;
  19. if(pp)
  20. *pp = nil;
  21. t = ndbsearch(db, s, attr, val);
  22. while(t){
  23. /* first look on same line (closer binding) */
  24. nt = s->t;
  25. for(;;){
  26. if(strcmp(rattr, nt->attr) == 0){
  27. rv = strdup(nt->val);
  28. if(pp != nil)
  29. *pp = t;
  30. else
  31. ndbfree(t);
  32. return rv;
  33. }
  34. nt = nt->line;
  35. if(nt == s->t)
  36. break;
  37. }
  38. /* search whole tuple */
  39. for(nt = t; nt; nt = nt->entry){
  40. if(strcmp(rattr, nt->attr) == 0){
  41. rv = strdup(nt->val);
  42. if(pp != nil)
  43. *pp = t;
  44. else
  45. ndbfree(t);
  46. return rv;
  47. }
  48. }
  49. ndbfree(t);
  50. t = ndbsnext(s, attr, val);
  51. }
  52. return nil;
  53. }
  54. Ndbtuple*
  55. ndbgetval(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr, char *buf)
  56. {
  57. Ndbtuple *t;
  58. char *p;
  59. p = ndbgetvalue(db, s, attr, val, rattr, &t);
  60. if(p == nil){
  61. if(buf != nil)
  62. *buf = 0;
  63. } else {
  64. if(buf != nil){
  65. strncpy(buf, p, Ndbvlen-1);
  66. buf[Ndbvlen-1] = 0;
  67. }
  68. free(p);
  69. }
  70. ndbsetmalloctag(t, getcallerpc(&db));
  71. return t;
  72. }