ndbquery: compatibility with ndb/query

Added the -m and -a flags to ndbquery as in Plan 9's ndb/query.
This commit is contained in:
gornorn 2024-08-06 14:36:25 +02:00 committed by GitHub
parent a2567fcac9
commit 89137059ed
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,79 +3,110 @@
#include <bio.h> #include <bio.h>
#include <ndb.h> #include <ndb.h>
static int all, multiple;
/* /*
* search the database for matches * search the database for matches
*/ */
void void
usage(void) usage(void)
{ {
fprint(2, "usage: query attr value [returned attribute]\n"); fprint(2, "usage: ndbquery [-am] [-f ndbfile] attr value [returned attribute]\n");
exits("usage"); exits("usage");
}
static void
prmatch(Ndbtuple *nt, char *rattr)
{
for(; nt; nt = nt->entry)
if(strcmp(nt->attr, rattr) == 0)
print("%s\n", nt->val);
} }
void void
search(Ndb *db, char *attr, char *val, char *rattr) search(Ndb *db, char *attr, char *val, char *rattr)
{ {
Ndbs s; Ndbs s;
Ndbtuple *t; Ndbtuple *t;
Ndbtuple *nt; Ndbtuple *nt;
char *p; char *p;
if(rattr){ if(rattr && !all){
p = ndbgetvalue(db, &s, attr, val, rattr, nil); p = ndbgetvalue(db, &s, attr, val, rattr, &t);
if(p){ if(multiple)
print("%s\n", p); prmatch(t, rattr);
free(p); else if(p){
} print("%s\n", p);
return; }
} ndbfree(t);
free(p);
return;
}
t = ndbsearch(db, &s, attr, val); /* all entries with matching rattrs */
while(t){ if(rattr){
for(nt = t; nt; nt = nt->entry) t = ndbsearch(db, &s, attr, val);
print("%s=%s ", nt->attr, nt->val); while(t != nil){
print("\n"); prmatch(t, rattr);
ndbfree(t); ndbfree(t);
t = ndbsnext(&s, attr, val); t = ndbsnext(&s, attr, val);
} }
return;
}
/* all entries */
t = ndbsearch(db, &s, attr, val);
while(t){
for(nt = t; nt; nt = nt->entry)
print("%s=%s ", nt->attr, nt->val);
print("\n");
ndbfree(t);
t = ndbsnext(&s, attr, val);
}
} }
void void
main(int argc, char **argv) main(int argc, char **argv)
{ {
char *rattr = 0; char *rattr = 0;
Ndb *db; Ndb *db;
char *dbfile = 0; char *dbfile = 0;
int reps = 1; int reps = 1;
ARGBEGIN{ ARGBEGIN{
case 'f': case 'a':
dbfile = ARGF(); all++;
break; break;
}ARGEND; case 'm':
multiple++;
break;
case 'f':
dbfile = ARGF();
break;
}ARGEND;
switch(argc){ switch(argc){
case 4: case 4:
reps = atoi(argv[3]); reps = atoi(argv[3]);
/* fall through */ /* fall through */
case 3: case 3:
rattr = argv[2]; rattr = argv[2];
break; break;
case 2: case 2:
rattr = 0; rattr = 0;
break; break;
default: default:
usage(); usage();
} }
db = ndbopen(dbfile); db = ndbopen(dbfile);
if(db == 0){ if(db == 0){
fprint(2, "no db files\n"); fprint(2, "no db files\n");
exits("no db"); exits("no db");
} }
while(reps--) while(reps--)
search(db, argv[0], argv[1], rattr); search(db, argv[0], argv[1], rattr);
ndbclose(db); ndbclose(db);
exits(0); exits(0);
} }