-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongovi.c
1767 lines (1463 loc) · 36.9 KB
/
mongovi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016, 2022 Tim Kuijsten
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#endif
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <locale.h>
#include <assert.h>
#include <err.h>
#include <histedit.h>
#include <libgen.h>
#include <pwd.h>
#include <string.h>
#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include "compat/compat.h"
#include "jsonify.h"
#include "shorten.h"
#include "prefix_match.h"
#include "parse_path.h"
#ifndef VERSION_MAJOR
#define VERSION_MAJOR 0
#define VERSION_MINOR 0
#define VERSION_PATCH 0
#endif
#define MAXLINE 16 * 100 * 1024
#define MAXUSERNAME 100
#define DFLMONGOURL "mongodb://localhost:27017"
#define MAXMONGOURL 200
#define DOTFILE ".mongovi"
#define MAXPROG 10
#define MAXDOC 16 * 100 * 1024 /* maximum size of a json document */
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#define BULKINSERTMAX 10000
#define MAXPROMPTCOLUMNS 30 /* The maximum number of columns the prompt may
use. Should be at least "/x..y/x..y> " = 4 +
4 + 2 * 4 = 16 since x and y can take at
most two columns for one character.
NOTE: some UTF-8 characters consume 0 or 2
columns. */
static char progname[MAXPROG];
static path_t path, prevpath, homepath;
/* use as temporary one-time storage while building a query or query results */
static uint8_t tmpdocs[16 * 1024 * 1024];
/*
* Make sure the prompt can hold MAXPROMPTCOLUMNS + a trailing null. Since
* MB_CUR_MAX is only defined after setlocale() is executed, we assume it is
* less than 8 bytes.
*/
static char pmpt[8 * MAXPROMPTCOLUMNS + 8] = "/> ";
static mongoc_client_t *client;
static mongoc_collection_t *ccoll; /* current collection */
static bson_t *bsonupsertopt, *bsonprojectid;
/* print human readable or not */
static int hr;
static int ttyin, ttyout;
static int import, homepathset;
static const char *cmds[] = {
"aggregate",
"cd",
"count",
"drop",
"find",
"help",
"insert",
"ls",
"remove",
"update",
"upsert",
"exit",
NULL
};
/*
* Test the results of tok_str(3) and tok_line(3) and print an appropriate
* message on stderr if there was a problem.
*
* Return 0 on success or -1 on failure.
*/
static int
test_tokresult(int rc)
{
if (rc == -1) {
warnx("could not tokenize");
return -1;
}
if (rc == 1) {
warnx("unmatched single quote");
return -1;
} else if (rc == 2) {
warnx("unmatched double quote");
return -1;
} else if (rc == 3) {
warnx("multi-line unsupported");
return -1;
}
if (rc != 0) {
warnx("unknown tokenization error");
return -1;
}
return 0;
}
/*
* Tokenize a list of paths.
*
* Returns the number of paths parsed into *ps on success, -1 on failure. *ps
* must be free(3)d by the caller only on success.
*/
static int
tok_paths(path_t **ps, const char *paths)
{
Tokenizer *t;
const char **av;
int rc, ac;
*ps = NULL;
t = tok_init(NULL);
rc = tok_str(t, paths, &ac, &av);
rc = test_tokresult(rc);
if (rc == -1)
goto cleanup;
if (parse_paths(ps, path, av, ac) == -1) {
warnx("could not parse paths: %s", paths);
free(*ps);
*ps = NULL;
rc = -1;
goto cleanup;
}
rc = ac;
cleanup:
tok_end(t);
return rc;
}
/*
* Given a word, a cursor position in the word and a list of options, complete
* the word to the longest common prefix and print a list of remaining options,
* if any.
*
* Returns 1 if word is now complete to one option in opts (possibly by prefix
* extension) or 0 if not.
*
* If one option is selected and *selected is not NULL, it is updated to point
* into **opts to the selected option.
*
* 0. if no option has the prefix of word or the prefix matches more than one
* option
* 1. if word matches one option
*/
static int
complete_word(EditLine *e, const char *word, size_t wordlen, const char **opts,
const char **selected)
{
const char **matches;
char *prefix;
size_t lcplen;
int r, i;
prefix = strndup(word, wordlen);
if (prefix == NULL) {
warn("complete_word strndup");
abort();
}
if (prefix_match(&matches, opts, prefix) == -1) {
warn("complete_word prefix_match");
abort();
}
free(prefix);
if (matches[0] == NULL) {
free(matches);
return 0;
}
if (matches[1] == NULL) {
lcplen = strlen(matches[0]);
} else {
printf("\n");
for (i = 0; matches[i] != NULL; i++)
printf("%s\n", matches[i]);
lcplen = common_prefix(matches);
}
if (lcplen > wordlen) {
/* zip up */
prefix = strndup(&matches[0][wordlen], lcplen - wordlen);
if (prefix == NULL) {
warn("complete_word strndup matches[0]");
abort();
}
el_insertstr(e, prefix);
free(prefix);
wordlen = lcplen;
}
r = 0;
if (matches[1] == NULL) {
/* word is complete */
if (selected != NULL)
*selected = matches[0];
r = 1;
}
free(matches);
return r;
}
/*
* Complete a /database/collection path.
*
* If more than one option matches the same prefix, all options are printed and
* the common prefix is completed. If exactly one component matches it is
* completed.
*
* Return 0 on success or -1 on failure.
*/
static int
complete_path(EditLine *e, const char *npath, size_t npathlen)
{
path_t tmppath;
bson_error_t error;
mongoc_database_t *db;
char p[PATH_MAX], p2[PATH_MAX], lastchar;
int i, comps;
char **strv;
size_t n;
if (npathlen >= sizeof(p2)) {
warnx("complete_path p2 too small: %s", npath);
return -1;
}
strncpy(p2, npath, npathlen);
p2[npathlen] = '\0';
if (npathlen > 0) {
lastchar = p2[npathlen - 1];
} else {
lastchar = '\0';
}
/* copy current context */
if ((size_t)snprintf(p, sizeof(p), "/%s/%s", path.dbname, path.collname)
>= sizeof(p)) {
warnx("complete_path p too small: %s", p2);
return -1;
}
n = resolvepath(p, sizeof(p), p2, &comps);
if (n == (size_t)-1) {
warnx("complete_path resolvepath error: %s", p2);
return -1;
}
if (parse_path(&tmppath, p) == -1) {
warnx("parse_path error: %s", p2);
abort();
}
if (comps > 1 || (comps == 1 && lastchar == '/') ||
(comps == 1 && lastchar == '\0')) {
db = mongoc_client_get_database(client, tmppath.dbname);
strv = mongoc_database_get_collection_names_with_opts(db, NULL,
&error);
mongoc_database_destroy(db);
db = NULL;
if (strv == NULL) {
warnx("complete collection failed: %d.%d %s",
error.domain, error.code, error.message);
return -1;
}
i = complete_word(e, tmppath.collname, strlen(tmppath.collname),
(const char **)strv, NULL);
bson_strfreev(strv);
strv = NULL;
if (i == 1 && lastchar != ' ' && lastchar != '\0')
el_insertstr(e, " ");
} else {
strv = mongoc_client_get_database_names_with_opts(client, NULL,
&error);
if (strv == NULL) {
warnx("complete db failed: %d.%d %s", error.domain,
error.code, error.message);
return -1;
}
i = complete_word(e, tmppath.dbname, strlen(tmppath.dbname),
(const char **)strv, NULL);
bson_strfreev(strv);
strv = NULL;
/* append trailing "/" if word is completed or relative root */
if ((i == 1 && lastchar != '/') || (comps == 0 && lastchar != '/'))
el_insertstr(e, "/");
}
return 0;
}
/*
* Tab complete commands and path arguments.
*
* if empty, print all commands
* if matches more than one command, print all with matching prefix
* if matches exactly one command and not complete, complete
* if command is complete and needs args, look at that
*/
static unsigned char
complete(EditLine *e, __attribute__((unused)) int ch)
{
Tokenizer *t;
const char **av;
int i, rc, ac, cc, co;
t = tok_init(NULL);
rc = tok_line(t, el_line(e), &ac, &av, &cc, &co);
rc = test_tokresult(rc);
if (rc == -1) {
rc = CC_ERROR;
goto cleanup;
}
if (ac == 0) {
printf("\n");
for (i = 0; cmds[i] != NULL; i++)
printf("%s\n", cmds[i]);
rc = CC_REDISPLAY;
goto cleanup;
}
/*
* If the first word is currently selected, try to complete as a
* command, if the second word is selected and the command (first word)
* supports a path argument, try to complete as a path.
*/
if (cc == 0) {
/* append trailing " " if command is complete(d) */
i = complete_word(e, av[cc], co, cmds, NULL);
if (i == 1)
el_insertstr(e, " ");
rc = CC_REDISPLAY;
} else if (cc >= 1) {
if (strcmp(av[0], "cd") == 0 || strcmp(av[0], "ls") == 0 ||
strcmp(av[0], "drop") == 0) {
if (complete_path(e, av[cc], co) == -1) {
warnx("complete_path error");
goto cleanup;
}
}
rc = CC_REDISPLAY;
}
cleanup:
tok_end(t);
return rc;
}
/*
* Find the next token starting at *line. *line is updated to point to the
* first non-whitespace character.
*
* Note: the separator is always an ASCII SPACE (0x20) or ASCII HTAB (0x09).
*
* Returns the number of bytes of the token starting at *line.
*/
static size_t
nexttok(const char **line)
{
*line = &(*line)[strspn(*line, " \t")];
return strcspn(*line, " \t");
}
/*
* Create a mongo extended JSON id selector document. If selector is 24 hex
* digits treat it as an object id, otherwise as a literal.
*
* dst - resulting json doc is written to dst
* dstsize - the size of dst
* sel - selector, must be NUL terminated
* sellen - length of sel, excluding the terminating NUL character
*
* Return 0 on success, -1 on failure.
*/
static int
idtosel(char *dst, size_t dstsize, const char *sel, size_t sellen)
{
const size_t oidlen = 24;
size_t n;
if (dstsize < 1 || sellen < 1)
return -1;
/* if 24 hex chars, assume an object id otherwise treat as a literal */
if (sellen == oidlen && (strspn(sel, "0123456789abcdefABCDEF") ==
oidlen)) {
n = snprintf(dst, dstsize,
"{ \"_id\": { \"$oid\": \"%.*s\" } }", (int)oidlen, sel);
if (n >= dstsize)
return -1;
} else {
n = snprintf(dst, dstsize, "{ \"_id\": \"%.*s\" }", (int)sellen,
sel);
if (n >= dstsize)
return -1;
}
return 0;
}
/*
* Parse the selector in line, that is the first (relaxed) json object or
* literal id. A strictly conforming JSON object is written in "doc" on
* success.
*
* "line" must be null terminated and "linelen" must exclude the terminating
* null byte.
*
* Return the number of bytes parsed on success or -1 on failure.
* On success, if docsize > 0, a null byte is always written to doc.
*/
static int
parse_selector(uint8_t *doc, size_t docsize, const char *line, size_t linelen)
{
const char *id;
size_t n, idlen;
int offset;
/*
* If the first non-blank char is a "{" then try to parse it as a
* relaxed JSON object. Otherwise try to parse it as a literal and
* convert to an id selector.
*/
n = strspn(line, " \t");
if (line[n] == '{') {
offset = relaxed_to_strict((char *)doc, docsize, line, linelen,
1);
if (offset == -1) {
warnx("could not parse line as JSON object(s): %.*s",
(int)linelen, line);
return -1;
}
return offset;
}
id = line + n;
if (id[0] == '"') {
id++;
idlen = strcspn(id, "\"");
if (idlen == 0) {
warnx("could not parse selector as double quoted id: "
"\"%.*s\"", (int)linelen, line);
return -1;
}
} else if (id[0] == '\'') {
id++;
idlen = strcspn(id, "'");
if (idlen == 0) {
warnx("could not parse selector as single quoted id: "
"\"%.*s\"", (int)linelen, line);
return -1;
}
} else {
idlen = strcspn(id, " \t");
if (idlen == 0) {
if (docsize > 0)
doc[0] = '\0';
return 0;
}
}
if (idtosel((char *)doc, docsize, id, idlen) == -1) {
warnx("could not parse selector as an id: \"%.*s\"", (int)idlen,
id);
return -1;
}
return (id - line) + idlen;
}
static char *
prompt(void)
{
return pmpt;
}
/*
* Update the prompt with the given dbname and collname. If the prompt exceeds
* MAXPROMPTCOLUMNS than shorten the dbname and collname.
*
* The following cases can arise:
* 1. dbname and collname are NULL, then prompt will be "/> "
* 2. dbname is not NULL and collname is NULL:
* a. if columns("/> ") + columns(dbname) is <= MAXPROMPTCOLUMNS
* then the prompt will be "/dbname> "
* b. if columns("/> ") + columns(dbname) is > MAXPROMPTCOLUMNS
* then dbname will be shortened and the prompt will be "/db..me> "
* 3. dbname is not NULL and collname is not NULL:
* a. if columns("//> ") + columns(dbname) + columns(collname) is <= MAXPROMPTCOLUMNS
* then the prompt will be "/dbname/collname> "
* b. if columns("//> ") + columns(dbname) + columns(collname) is > MAXPROMPTCOLUMNS
* then dbname and collname will be shortened and the prompt will be
* "/db..me/co..me> ".
*/
static int
set_prompt(const char *dbname, size_t dbnamelen, const char *collname,
size_t collnamelen)
{
char c1[sizeof(pmpt)], c2[sizeof(pmpt)];
size_t n;
if (dbnamelen == 0 && collnamelen == 0) {
if ((size_t)snprintf(pmpt, sizeof(pmpt), "/> ") >= sizeof(pmpt))
return -1;
return 0;
}
/* err if only collname is provided */
if (dbnamelen == 0)
return -1;
c1[0] = '\0';
c2[0] = '\0';
/* default to db only prompt */
n = strlen("/> ");
if (strlcpy(c1, dbname, sizeof(c1)) >= sizeof(c1))
return -1;
if (collnamelen > 0) {
/* make dbname + collname prompt */
n = strlen("//> ");
if (strlcpy(c2, collname, sizeof(c2)) >= sizeof(c2))
return -1;
}
if (shorten_comps(c1, c2, MAXPROMPTCOLUMNS - n) == (size_t)-1)
return -1;
if (collnamelen == 0) {
n = snprintf(pmpt, sizeof(pmpt), "/%s> ", c1);
if (n >= sizeof(pmpt))
return -1;
} else {
n = snprintf(pmpt, sizeof(pmpt), "/%s/%s> ", c1, c2);
if (n >= sizeof(pmpt))
return -1;
}
return 0;
}
/*
* Exhaust a cursor and print each object.
*/
static int
printcursor(mongoc_cursor_t *cursor)
{
bson_error_t error;
size_t rlen;
const bson_t *doc;
char *str;
struct winsize w;
w.ws_row = 0;
w.ws_col = 0;
if (hr && ttyout) {
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == -1)
warn("could not determine window size: %d %d", w.ws_row,
w.ws_col);
}
while (mongoc_cursor_next(cursor, &doc)) {
if (hr) {
str = bson_as_relaxed_extended_json(doc, &rlen);
} else {
str = bson_as_canonical_extended_json(doc, &rlen);
}
if (hr && rlen > w.ws_col) {
if (human_readable((char *)tmpdocs, sizeof(tmpdocs),
str, rlen) == -1) {
warnx("could not make human readable JSON "
"string");
return -1;
}
printf("%s\n", tmpdocs);
} else {
printf("%s\n", str);
}
bson_free(str);
}
if (mongoc_cursor_error(cursor, &error)) {
warnx("cursor failed: %d.%d %s", error.domain, error.code,
error.message);
return -1;
}
return 0;
}
/*
* List database for the given client.
*
* Return 0 on success, -1 on failure.
*/
static int
exec_lsdbs(mongoc_client_t *client)
{
bson_error_t error;
char **strv;
int i;
strv = mongoc_client_get_database_names_with_opts(client, NULL, &error);
if (strv == NULL) {
warnx("could not get database names: %d.%d %s", error.domain,
error.code, error.message);
return -1;
}
for (i = 0; strv[i] != NULL; i++)
printf("%s\n", strv[i]);
bson_strfreev(strv);
strv = NULL;
return 0;
}
/*
* List collections for the given database.
*
* Return 0 on success, -1 on failure.
*/
static int
exec_lscolls(mongoc_client_t *client, char *dbname)
{
bson_error_t error;
mongoc_database_t *db;
char **strv;
int i;
db = mongoc_client_get_database(client, dbname);
strv = mongoc_database_get_collection_names_with_opts(db, NULL, &error);
mongoc_database_destroy(db);
db = NULL;
if (strv == NULL) {
warnx("could not get collection names: %d.%d %s", error.domain,
error.code, error.message);
return -1;
}
for (i = 0; strv[i] != NULL; i++)
printf("%s\n", strv[i]);
bson_strfreev(strv);
strv = NULL;
return 0;
}
/*
* Change dbname and/or collname, set ccoll and update prompt.
*
* Return 0 on success, -1 on failure.
*/
static int
exec_chcoll(mongoc_client_t *client, const path_t newpath)
{
size_t dbnamelen, collnamelen;
if (strcmp(newpath.dbname, path.dbname) == 0 &&
strcmp(newpath.collname, path.collname) == 0) {
return 0;
}
if (ccoll != NULL) {
mongoc_collection_destroy(ccoll);
ccoll = NULL;
}
dbnamelen = strlen(newpath.dbname);
collnamelen = strlen(newpath.collname);
if (dbnamelen == 0 && collnamelen > 0) {
warnx("can't change collection because no db is set");
return -1;
}
if (collnamelen > 0)
ccoll = mongoc_client_get_collection(client, newpath.dbname,
newpath.collname);
if (set_prompt(newpath.dbname, dbnamelen, newpath.collname, collnamelen)
== -1)
warnx("can't update prompt with db and collection name");
if (homepathset == 0 && dbnamelen > 0) {
homepath = newpath;
homepathset = 1;
}
prevpath = path;
path = newpath;
return 0;
}
/*
* Execute a query.
*
* Return 0 on success, -1 on failure.
*/
static int
exec_query(mongoc_collection_t *collection, const char *line, size_t linelen,
int idsonly)
{
mongoc_cursor_t *cursor;
bson_error_t error;
bson_t *query;
int rc;
if (sizeof(tmpdocs) < 3)
abort();
if (parse_selector(tmpdocs, sizeof(tmpdocs), line, linelen) == -1)
return -1;
/* default to all documents */
if (strlen((char *)tmpdocs) == 0) {
tmpdocs[0] = '{';
tmpdocs[1] = '}';
tmpdocs[2] = '\0';
}
if ((query = bson_new_from_json(tmpdocs, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
tmpdocs);
return -1;
}
cursor = mongoc_collection_find_with_opts(collection, query,
idsonly ? bsonprojectid : NULL, NULL);
bson_destroy(query);
rc = printcursor(cursor);
mongoc_cursor_destroy(cursor);
cursor = NULL;
return rc;
}
/*
* Count number of documents in collection.
*
* Return 0 on success, -1 on failure.
*/
static int
exec_count(mongoc_collection_t *collection, const char *line, size_t linelen)
{
bson_error_t error;
bson_t *query;
int64_t count;
if (sizeof(tmpdocs) < 3)
abort();
if (parse_selector(tmpdocs, sizeof(tmpdocs), line, linelen) == -1)
return -1;
/* default to all documents */
if (strlen((char *)tmpdocs) == 0) {
tmpdocs[0] = '{';
tmpdocs[1] = '}';
tmpdocs[2] = '\0';
}
if ((query = bson_new_from_json(tmpdocs, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
tmpdocs);
return -1;
}
count = mongoc_collection_count_documents(collection, query, NULL, NULL,
NULL, &error);
bson_destroy(query);
if (count == -1) {
warnx("count failed: %d.%d %s: %s", error.domain, error.code,
error.message, tmpdocs);
return -1;
}
printf("%ld\n", count);
return 0;
}
/*
* Parse update command, expect two json objects, a selector, and an update
* doc.
*/
static int
exec_update(mongoc_collection_t *collection, const char *line, size_t linelen,
int upsert)
{
uint8_t update_docs[MAXDOC];
uint8_t *update_doc = update_docs;
bson_error_t error;
bson_t *query, *update, *opts;
int offset;
opts = NULL;
if (upsert)
opts = bsonupsertopt;
/* expect two json objects */
offset = parse_selector(tmpdocs, sizeof(tmpdocs), line, linelen);
if (offset <= 0)
return -1;
line += offset;
linelen -= offset;
offset = relaxed_to_strict((char *)update_doc, MAXDOC, line, linelen,
1);
if (offset <= 0) {
warnx("could not parse update doc: %s", line);
return -1;
}
line += offset;
linelen -= offset;
if ((query = bson_new_from_json(tmpdocs, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
tmpdocs);
return -1;
}
if ((update = bson_new_from_json(update_doc, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
update_doc);
goto cleanuperr;
}
if (!mongoc_collection_update_many(collection, query, update, opts,
NULL, &error)) {
warnx("update failed: %d.%d %s: %s %s", error.domain,
error.code, error.message, tmpdocs, update_doc);
goto cleanuperr;
}
bson_destroy(query);
bson_destroy(update);
return 0;
cleanuperr:
bson_destroy(query);
bson_destroy(update);
return -1;
}
/* parse insert command, expect one json object, the insert doc and exec */
static int
exec_insert(mongoc_collection_t *collection, const char *line, size_t linelen)
{
bson_error_t error;
bson_t *doc;
int offset;
offset = parse_selector(tmpdocs, sizeof(tmpdocs), line, linelen);
if (offset <= 0)
return -1;
if ((doc = bson_new_from_json(tmpdocs, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
tmpdocs);
return -1;
}
if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error))
{
warnx("insert failed: %d.%d %s: %s", error.domain, error.code,
error.message, tmpdocs);
bson_destroy(doc);
return -1;
}
bson_destroy(doc);
return 0;
}
/* parse remove command, expect one selector */
static int
exec_remove(mongoc_collection_t *collection, const char *line, size_t linelen)
{
int offset;
bson_error_t error;
bson_t *selector;
offset = parse_selector(tmpdocs, sizeof(tmpdocs), line, linelen);
if (offset <= 0)
return -1;
if ((selector = bson_new_from_json(tmpdocs, -1, &error)) == NULL) {
warnx("%d.%d %s: %s", error.domain, error.code, error.message,
tmpdocs);
return -1;
}
if (!mongoc_collection_delete_many(collection, selector, NULL, NULL,
&error)) {
warnx("remove failed: %d.%d %s: %s", error.domain, error.code,
error.message, tmpdocs);
bson_destroy(selector);
return -1;
}
bson_destroy(selector);
return 0;
}