Avoid printf type modifiers not supported by MSVC C runtime library.
[cascardo/ovs.git] / tests / test-ovsdb.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include <assert.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "command-line.h"
27 #include "dynamic-string.h"
28 #include "json.h"
29 #include "jsonrpc.h"
30 #include "ovsdb-data.h"
31 #include "ovsdb-error.h"
32 #include "ovsdb-idl.h"
33 #include "ovsdb-types.h"
34 #include "ovsdb/column.h"
35 #include "ovsdb/condition.h"
36 #include "ovsdb/file.h"
37 #include "ovsdb/log.h"
38 #include "ovsdb/mutation.h"
39 #include "ovsdb/ovsdb.h"
40 #include "ovsdb/query.h"
41 #include "ovsdb/row.h"
42 #include "ovsdb/server.h"
43 #include "ovsdb/table.h"
44 #include "ovsdb/transaction.h"
45 #include "ovsdb/trigger.h"
46 #include "poll-loop.h"
47 #include "stream.h"
48 #include "svec.h"
49 #include "tests/idltest.h"
50 #include "timeval.h"
51 #include "util.h"
52 #include "vlog.h"
53
54 static struct command all_commands[];
55
56 static void usage(void) NO_RETURN;
57 static void parse_options(int argc, char *argv[]);
58
59 int
60 main(int argc, char *argv[])
61 {
62     set_program_name(argv[0]);
63     parse_options(argc, argv);
64     run_command(argc - optind, argv + optind, all_commands);
65     return 0;
66 }
67
68 static void
69 parse_options(int argc, char *argv[])
70 {
71     static const struct option long_options[] = {
72         {"timeout", required_argument, NULL, 't'},
73         {"verbose", optional_argument, NULL, 'v'},
74         {"help", no_argument, NULL, 'h'},
75         {NULL, 0, NULL, 0},
76     };
77     char *short_options = long_options_to_short_options(long_options);
78
79     for (;;) {
80         unsigned long int timeout;
81         int c;
82
83         c = getopt_long(argc, argv, short_options, long_options, NULL);
84         if (c == -1) {
85             break;
86         }
87
88         switch (c) {
89         case 't':
90             timeout = strtoul(optarg, NULL, 10);
91             if (timeout <= 0) {
92                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
93                           optarg);
94             } else {
95                 time_alarm(timeout);
96             }
97             break;
98
99         case 'h':
100             usage();
101
102         case 'v':
103             vlog_set_verbosity(optarg);
104             break;
105
106         case '?':
107             exit(EXIT_FAILURE);
108
109         default:
110             abort();
111         }
112     }
113     free(short_options);
114 }
115
116 static void
117 usage(void)
118 {
119     printf("%s: Open vSwitch database test utility\n"
120            "usage: %s [OPTIONS] COMMAND [ARG...]\n\n"
121            "  log-io FILE FLAGS COMMAND...\n"
122            "    open FILE with FLAGS, run COMMANDs\n"
123            "  default-atoms\n"
124            "    test ovsdb_atom_default()\n"
125            "  default-data\n"
126            "    test ovsdb_datum_default()\n"
127            "  parse-atomic-type TYPE\n"
128            "    parse TYPE as OVSDB atomic type, and re-serialize\n"
129            "  parse-base-type TYPE\n"
130            "    parse TYPE as OVSDB base type, and re-serialize\n"
131            "  parse-type JSON\n"
132            "    parse JSON as OVSDB type, and re-serialize\n"
133            "  parse-atoms TYPE ATOM...\n"
134            "    parse JSON ATOMs as atoms of TYPE, and re-serialize\n"
135            "  parse-atom-strings TYPE ATOM...\n"
136            "    parse string ATOMs as atoms of given TYPE, and re-serialize\n"
137            "  sort-atoms TYPE ATOM...\n"
138            "    print JSON ATOMs in sorted order\n"
139            "  parse-data TYPE DATUM...\n"
140            "    parse JSON DATUMs as data of given TYPE, and re-serialize\n"
141            "  parse-data-strings TYPE DATUM...\n"
142            "    parse string DATUMs as data of given TYPE, and re-serialize\n"
143            "  parse-column NAME OBJECT\n"
144            "    parse column NAME with info OBJECT, and re-serialize\n"
145            "  parse-table NAME OBJECT [DEFAULT-IS-ROOT]\n"
146            "    parse table NAME with info OBJECT\n"
147            "  parse-row TABLE ROW..., and re-serialize\n"
148            "    parse each ROW of defined TABLE\n"
149            "  compare-row TABLE ROW...\n"
150            "    mutually compare all of the ROWs, print those that are equal\n"
151            "  parse-conditions TABLE CONDITION...\n"
152            "    parse each CONDITION on TABLE, and re-serialize\n"
153            "  evaluate-conditions TABLE [CONDITION,...] [ROW,...]\n"
154            "    test CONDITIONS on TABLE against each ROW, print results\n"
155            "  parse-mutations TABLE MUTATION...\n"
156            "    parse each MUTATION on TABLE, and re-serialize\n"
157            "  execute-mutations TABLE [MUTATION,...] [ROW,...]\n"
158            "    execute MUTATIONS on TABLE on each ROW, print results\n"
159            "  query TABLE [ROW,...] [CONDITION,...]\n"
160            "    add each ROW to TABLE, then query and print the rows that\n"
161            "    satisfy each CONDITION.\n"
162            "  query-distinct TABLE [ROW,...] [CONDITION,...] COLUMNS\n"
163            "    add each ROW to TABLE, then query and print the rows that\n"
164            "    satisfy each CONDITION and have distinct COLUMNS.\n"
165            "  parse-schema JSON\n"
166            "    parse JSON as an OVSDB schema, and re-serialize\n"
167            "  transact COMMAND\n"
168            "    execute each specified transactional COMMAND:\n"
169            "      commit\n"
170            "      abort\n"
171            "      insert UUID I J\n"
172            "      delete UUID\n"
173            "      modify UUID I J\n"
174            "      print\n"
175            "  execute SCHEMA TRANSACTION...\n"
176            "    executes each TRANSACTION on an initially empty database\n"
177            "    the specified SCHEMA\n"
178            "  trigger SCHEMA TRANSACTION...\n"
179            "    executes each TRANSACTION on an initially empty database\n"
180            "    the specified SCHEMA.   A TRANSACTION of the form\n"
181            "    [\"advance\", NUMBER] advances NUMBER milliseconds in\n"
182            "    simulated time, for causing triggers to time out.\n"
183            "  idl SERVER [TRANSACTION...]\n"
184            "    connect to SERVER and dump the contents of the database\n"
185            "    as seen initially by the IDL implementation and after\n"
186            "    executing each TRANSACTION.  (Each TRANSACTION must modify\n"
187            "    the database or this command will hang.)\n",
188            program_name, program_name);
189     vlog_usage();
190     printf("\nOther options:\n"
191            "  -t, --timeout=SECS          give up after SECS seconds\n"
192            "  -h, --help                  display this help message\n");
193     exit(EXIT_SUCCESS);
194 }
195 \f
196 /* Command helper functions. */
197
198 static struct json *
199 parse_json(const char *s)
200 {
201     struct json *json = json_from_string(s);
202     if (json->type == JSON_STRING) {
203         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
204     }
205     return json;
206 }
207
208 static struct json *
209 unbox_json(struct json *json)
210 {
211     if (json->type == JSON_ARRAY && json->u.array.n == 1) {
212         struct json *inner = json->u.array.elems[0];
213         json->u.array.elems[0] = NULL;
214         json_destroy(json);
215         return inner;
216     } else {
217         return json;
218     }
219 }
220
221 static size_t
222 print_and_free_json(struct json *json)
223 {
224     char *string = json_to_string(json, JSSF_SORT);
225     size_t length = strlen(string);
226     json_destroy(json);
227     puts(string);
228     free(string);
229
230     return length;
231 }
232
233 static void
234 print_and_free_ovsdb_error(struct ovsdb_error *error)
235 {
236     char *string = ovsdb_error_to_string(error);
237     ovsdb_error_destroy(error);
238     puts(string);
239     free(string);
240 }
241
242 static void
243 check_ovsdb_error(struct ovsdb_error *error)
244 {
245     if (error) {
246         char *s = ovsdb_error_to_string(error);
247         ovsdb_error_destroy(error);
248         ovs_fatal(0, "%s", s);
249     }
250 }
251
252 static void
253 die_if_error(char *error)
254 {
255     if (error) {
256         ovs_fatal(0, "%s", error);
257     }
258 }
259 \f
260 /* Command implementations. */
261
262 static void
263 do_log_io(int argc, char *argv[])
264 {
265     const char *name = argv[1];
266     char *mode_string = argv[2];
267
268     struct ovsdb_error *error;
269     enum ovsdb_log_open_mode mode;
270     struct ovsdb_log *log;
271     int i;
272
273     if (!strcmp(mode_string, "read-only")) {
274         mode = OVSDB_LOG_READ_ONLY;
275     } else if (!strcmp(mode_string, "read/write")) {
276         mode = OVSDB_LOG_READ_WRITE;
277     } else if (!strcmp(mode_string, "create")) {
278         mode = OVSDB_LOG_CREATE;
279     } else {
280         ovs_fatal(0, "unknown log-io open mode \"%s\"", mode_string);
281     }
282
283     check_ovsdb_error(ovsdb_log_open(name, mode, -1, &log));
284     printf("%s: open successful\n", name);
285
286     for (i = 3; i < argc; i++) {
287         const char *command = argv[i];
288         if (!strcmp(command, "read")) {
289             struct json *json;
290
291             error = ovsdb_log_read(log, &json);
292             if (!error) {
293                 printf("%s: read: ", name);
294                 if (json) {
295                     print_and_free_json(json);
296                 } else {
297                     printf("end of log\n");
298                 }
299                 continue;
300             }
301         } else if (!strncmp(command, "write:", 6)) {
302             struct json *json = parse_json(command + 6);
303             error = ovsdb_log_write(log, json);
304             json_destroy(json);
305         } else if (!strcmp(command, "commit")) {
306             error = ovsdb_log_commit(log);
307         } else {
308             ovs_fatal(0, "unknown log-io command \"%s\"", command);
309         }
310         if (error) {
311             char *s = ovsdb_error_to_string(error);
312             printf("%s: %s failed: %s\n", name, command, s);
313             free(s);
314             ovsdb_error_destroy(error);
315         } else {
316             printf("%s: %s successful\n", name, command);
317         }
318     }
319
320     ovsdb_log_close(log);
321 }
322
323 static void
324 do_default_atoms(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
325 {
326     int type;
327
328     for (type = 0; type < OVSDB_N_TYPES; type++) {
329         union ovsdb_atom atom;
330
331         if (type == OVSDB_TYPE_VOID) {
332             continue;
333         }
334
335         printf("%s: ", ovsdb_atomic_type_to_string(type));
336
337         ovsdb_atom_init_default(&atom, type);
338         if (!ovsdb_atom_equals(&atom, ovsdb_atom_default(type), type)) {
339             printf("wrong\n");
340             exit(1);
341         }
342         ovsdb_atom_destroy(&atom, type);
343
344         printf("OK\n");
345     }
346 }
347
348 static void
349 do_default_data(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
350 {
351     unsigned int n_min;
352     int key, value;
353
354     for (n_min = 0; n_min <= 1; n_min++) {
355         for (key = 0; key < OVSDB_N_TYPES; key++) {
356             if (key == OVSDB_TYPE_VOID) {
357                 continue;
358             }
359             for (value = 0; value < OVSDB_N_TYPES; value++) {
360                 struct ovsdb_datum datum;
361                 struct ovsdb_type type;
362
363                 ovsdb_base_type_init(&type.key, key);
364                 ovsdb_base_type_init(&type.value, value);
365                 type.n_min = n_min;
366                 type.n_max = 1;
367                 assert(ovsdb_type_is_valid(&type));
368
369                 printf("key %s, value %s, n_min %u: ",
370                        ovsdb_atomic_type_to_string(key),
371                        ovsdb_atomic_type_to_string(value), n_min);
372
373                 ovsdb_datum_init_default(&datum, &type);
374                 if (!ovsdb_datum_equals(&datum, ovsdb_datum_default(&type),
375                                         &type)) {
376                     printf("wrong\n");
377                     exit(1);
378                 }
379                 ovsdb_datum_destroy(&datum, &type);
380                 ovsdb_type_destroy(&type);
381
382                 printf("OK\n");
383             }
384         }
385     }
386 }
387
388 static void
389 do_parse_atomic_type(int argc OVS_UNUSED, char *argv[])
390 {
391     enum ovsdb_atomic_type type;
392     struct json *json;
393
394     json = unbox_json(parse_json(argv[1]));
395     check_ovsdb_error(ovsdb_atomic_type_from_json(&type, json));
396     json_destroy(json);
397     print_and_free_json(ovsdb_atomic_type_to_json(type));
398 }
399
400 static void
401 do_parse_base_type(int argc OVS_UNUSED, char *argv[])
402 {
403     struct ovsdb_base_type base;
404     struct json *json;
405
406     json = unbox_json(parse_json(argv[1]));
407     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
408     json_destroy(json);
409     print_and_free_json(ovsdb_base_type_to_json(&base));
410     ovsdb_base_type_destroy(&base);
411 }
412
413 static void
414 do_parse_type(int argc OVS_UNUSED, char *argv[])
415 {
416     struct ovsdb_type type;
417     struct json *json;
418
419     json = unbox_json(parse_json(argv[1]));
420     check_ovsdb_error(ovsdb_type_from_json(&type, json));
421     json_destroy(json);
422     print_and_free_json(ovsdb_type_to_json(&type));
423     ovsdb_type_destroy(&type);
424 }
425
426 static void
427 do_parse_atoms(int argc, char *argv[])
428 {
429     struct ovsdb_base_type base;
430     struct json *json;
431     int i;
432
433     json = unbox_json(parse_json(argv[1]));
434     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
435     json_destroy(json);
436
437     for (i = 2; i < argc; i++) {
438         struct ovsdb_error *error;
439         union ovsdb_atom atom;
440
441         json = unbox_json(parse_json(argv[i]));
442         error = ovsdb_atom_from_json(&atom, &base, json, NULL);
443         json_destroy(json);
444
445         if (error) {
446             print_and_free_ovsdb_error(error);
447         } else {
448             size_t length;
449
450             length = print_and_free_json(ovsdb_atom_to_json(&atom, base.type));
451             ovs_assert(length == ovsdb_atom_json_length(&atom, base.type));
452             ovsdb_atom_destroy(&atom, base.type);
453         }
454     }
455     ovsdb_base_type_destroy(&base);
456 }
457
458 static void
459 do_parse_atom_strings(int argc, char *argv[])
460 {
461     struct ovsdb_base_type base;
462     struct json *json;
463     int i;
464
465     json = unbox_json(parse_json(argv[1]));
466     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
467     json_destroy(json);
468
469     for (i = 2; i < argc; i++) {
470         union ovsdb_atom atom;
471         struct ds out;
472
473         die_if_error(ovsdb_atom_from_string(&atom, &base, argv[i], NULL));
474
475         ds_init(&out);
476         ovsdb_atom_to_string(&atom, base.type, &out);
477         puts(ds_cstr(&out));
478         ds_destroy(&out);
479
480         ovsdb_atom_destroy(&atom, base.type);
481     }
482     ovsdb_base_type_destroy(&base);
483 }
484
485 static void
486 do_parse_data__(int argc, char *argv[],
487                 struct ovsdb_error *
488                 (*parse)(struct ovsdb_datum *datum,
489                          const struct ovsdb_type *type,
490                          const struct json *json,
491                          struct ovsdb_symbol_table *symtab))
492 {
493     struct ovsdb_type type;
494     struct json *json;
495     int i;
496
497     json = unbox_json(parse_json(argv[1]));
498     check_ovsdb_error(ovsdb_type_from_json(&type, json));
499     json_destroy(json);
500
501     for (i = 2; i < argc; i++) {
502         struct ovsdb_datum datum;
503         size_t length;
504
505         json = unbox_json(parse_json(argv[i]));
506         check_ovsdb_error(parse(&datum, &type, json, NULL));
507         json_destroy(json);
508
509         length = print_and_free_json(ovsdb_datum_to_json(&datum, &type));
510         ovs_assert(length == ovsdb_datum_json_length(&datum, &type));
511
512         ovsdb_datum_destroy(&datum, &type);
513     }
514     ovsdb_type_destroy(&type);
515 }
516
517 static void
518 do_parse_data(int argc, char *argv[])
519 {
520     do_parse_data__(argc, argv, ovsdb_datum_from_json);
521 }
522
523 static void
524 do_parse_data_strings(int argc, char *argv[])
525 {
526     struct ovsdb_type type;
527     struct json *json;
528     int i;
529
530     json = unbox_json(parse_json(argv[1]));
531     check_ovsdb_error(ovsdb_type_from_json(&type, json));
532     json_destroy(json);
533
534     for (i = 2; i < argc; i++) {
535         struct ovsdb_datum datum;
536         struct ds out;
537
538         die_if_error(ovsdb_datum_from_string(&datum, &type, argv[i], NULL));
539
540         ds_init(&out);
541         ovsdb_datum_to_string(&datum, &type, &out);
542         puts(ds_cstr(&out));
543         ds_destroy(&out);
544
545         ovsdb_datum_destroy(&datum, &type);
546     }
547     ovsdb_type_destroy(&type);
548 }
549
550 static enum ovsdb_atomic_type compare_atoms_atomic_type;
551
552 static int
553 compare_atoms(const void *a_, const void *b_)
554 {
555     const union ovsdb_atom *a = a_;
556     const union ovsdb_atom *b = b_;
557
558     return ovsdb_atom_compare_3way(a, b, compare_atoms_atomic_type);
559 }
560
561 static void
562 do_sort_atoms(int argc OVS_UNUSED, char *argv[])
563 {
564     struct ovsdb_base_type base;
565     union ovsdb_atom *atoms;
566     struct json *json, **json_atoms;
567     size_t n_atoms;
568     int i;
569
570     json = unbox_json(parse_json(argv[1]));
571     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
572     json_destroy(json);
573
574     json = unbox_json(parse_json(argv[2]));
575     if (json->type != JSON_ARRAY) {
576         ovs_fatal(0, "second argument must be array");
577     }
578
579     /* Convert JSON atoms to internal representation. */
580     n_atoms = json->u.array.n;
581     atoms = xmalloc(n_atoms * sizeof *atoms);
582     for (i = 0; i < n_atoms; i++) {
583         check_ovsdb_error(ovsdb_atom_from_json(&atoms[i], &base,
584                                                json->u.array.elems[i], NULL));
585     }
586     json_destroy(json);
587
588     /* Sort atoms. */
589     compare_atoms_atomic_type = base.type;
590     qsort(atoms, n_atoms, sizeof *atoms, compare_atoms);
591
592     /* Convert internal representation back to JSON. */
593     json_atoms = xmalloc(n_atoms * sizeof *json_atoms);
594     for (i = 0; i < n_atoms; i++) {
595         json_atoms[i] = ovsdb_atom_to_json(&atoms[i], base.type);
596         ovsdb_atom_destroy(&atoms[i], base.type);
597     }
598     print_and_free_json(json_array_create(json_atoms, n_atoms));
599     free(atoms);
600     ovsdb_base_type_destroy(&base);
601 }
602
603 static void
604 do_parse_column(int argc OVS_UNUSED, char *argv[])
605 {
606     struct ovsdb_column *column;
607     struct json *json;
608
609     json = parse_json(argv[2]);
610     check_ovsdb_error(ovsdb_column_from_json(json, argv[1], &column));
611     json_destroy(json);
612     print_and_free_json(ovsdb_column_to_json(column));
613     ovsdb_column_destroy(column);
614 }
615
616 static void
617 do_parse_table(int argc OVS_UNUSED, char *argv[])
618 {
619     struct ovsdb_table_schema *ts;
620     bool default_is_root;
621     struct json *json;
622
623     default_is_root = argc > 3 && !strcmp(argv[3], "true");
624
625     json = parse_json(argv[2]);
626     check_ovsdb_error(ovsdb_table_schema_from_json(json, argv[1], &ts));
627     json_destroy(json);
628     print_and_free_json(ovsdb_table_schema_to_json(ts, default_is_root));
629     ovsdb_table_schema_destroy(ts);
630 }
631
632 static void
633 do_parse_rows(int argc, char *argv[])
634 {
635     struct ovsdb_column_set all_columns;
636     struct ovsdb_table_schema *ts;
637     struct ovsdb_table *table;
638     struct json *json;
639     int i;
640
641     json = unbox_json(parse_json(argv[1]));
642     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
643     json_destroy(json);
644
645     table = ovsdb_table_create(ts);
646     ovsdb_column_set_init(&all_columns);
647     ovsdb_column_set_add_all(&all_columns, table);
648
649     for (i = 2; i < argc; i++) {
650         struct ovsdb_column_set columns;
651         struct ovsdb_row *row;
652
653         ovsdb_column_set_init(&columns);
654         row = ovsdb_row_create(table);
655
656         json = unbox_json(parse_json(argv[i]));
657         check_ovsdb_error(ovsdb_row_from_json(row, json, NULL, &columns));
658         json_destroy(json);
659
660         print_and_free_json(ovsdb_row_to_json(row, &all_columns));
661
662         if (columns.n_columns) {
663             struct svec names;
664             size_t j;
665             char *s;
666
667             svec_init(&names);
668             for (j = 0; j < columns.n_columns; j++) {
669                 svec_add(&names, columns.columns[j]->name);
670             }
671             svec_sort(&names);
672             s = svec_join(&names, ", ", "");
673             puts(s);
674             free(s);
675             svec_destroy(&names);
676         } else {
677             printf("<none>\n");
678         }
679
680         ovsdb_column_set_destroy(&columns);
681         ovsdb_row_destroy(row);
682     }
683
684     ovsdb_column_set_destroy(&all_columns);
685     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
686 }
687
688 static void
689 do_compare_rows(int argc, char *argv[])
690 {
691     struct ovsdb_column_set all_columns;
692     struct ovsdb_table_schema *ts;
693     struct ovsdb_table *table;
694     struct ovsdb_row **rows;
695     struct json *json;
696     char **names;
697     int n_rows;
698     int i, j;
699
700     json = unbox_json(parse_json(argv[1]));
701     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
702     json_destroy(json);
703
704     table = ovsdb_table_create(ts);
705     ovsdb_column_set_init(&all_columns);
706     ovsdb_column_set_add_all(&all_columns, table);
707
708     n_rows = argc - 2;
709     rows = xmalloc(sizeof *rows * n_rows);
710     names = xmalloc(sizeof *names * n_rows);
711     for (i = 0; i < n_rows; i++) {
712         rows[i] = ovsdb_row_create(table);
713
714         json = parse_json(argv[i + 2]);
715         if (json->type != JSON_ARRAY || json->u.array.n != 2
716             || json->u.array.elems[0]->type != JSON_STRING) {
717             ovs_fatal(0, "\"%s\" does not have expected form "
718                       "[\"name\", {data}]", argv[i]);
719         }
720         names[i] = xstrdup(json->u.array.elems[0]->u.string);
721         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[1],
722                                               NULL, NULL));
723         json_destroy(json);
724     }
725     for (i = 0; i < n_rows; i++) {
726         uint32_t i_hash = ovsdb_row_hash_columns(rows[i], &all_columns, 0);
727         for (j = i + 1; j < n_rows; j++) {
728             uint32_t j_hash = ovsdb_row_hash_columns(rows[j], &all_columns, 0);
729             if (ovsdb_row_equal_columns(rows[i], rows[j], &all_columns)) {
730                 printf("%s == %s\n", names[i], names[j]);
731                 if (i_hash != j_hash) {
732                     printf("but hash(%s) != hash(%s)\n", names[i], names[j]);
733                     abort();
734                 }
735             } else if (i_hash == j_hash) {
736                 printf("hash(%s) == hash(%s)\n", names[i], names[j]);
737             }
738         }
739     }
740     for (i = 0; i < n_rows; i++) {
741         ovsdb_row_destroy(rows[i]);
742         free(names[i]);
743     }
744     free(rows);
745     free(names);
746
747     ovsdb_column_set_destroy(&all_columns);
748     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
749 }
750
751 static void
752 do_parse_conditions(int argc, char *argv[])
753 {
754     struct ovsdb_table_schema *ts;
755     struct json *json;
756     int exit_code = 0;
757     int i;
758
759     json = unbox_json(parse_json(argv[1]));
760     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
761     json_destroy(json);
762
763     for (i = 2; i < argc; i++) {
764         struct ovsdb_condition cnd;
765         struct ovsdb_error *error;
766
767         json = parse_json(argv[i]);
768         error = ovsdb_condition_from_json(ts, json, NULL, &cnd);
769         if (!error) {
770             print_and_free_json(ovsdb_condition_to_json(&cnd));
771         } else {
772             char *s = ovsdb_error_to_string(error);
773             ovs_error(0, "%s", s);
774             free(s);
775             ovsdb_error_destroy(error);
776             exit_code = 1;
777         }
778         json_destroy(json);
779
780         ovsdb_condition_destroy(&cnd);
781     }
782     ovsdb_table_schema_destroy(ts);
783
784     exit(exit_code);
785 }
786
787 static void
788 do_evaluate_conditions(int argc OVS_UNUSED, char *argv[])
789 {
790     struct ovsdb_table_schema *ts;
791     struct ovsdb_table *table;
792     struct ovsdb_condition *conditions;
793     size_t n_conditions;
794     struct ovsdb_row **rows;
795     size_t n_rows;
796     struct json *json;
797     size_t i, j;
798
799     /* Parse table schema, create table. */
800     json = unbox_json(parse_json(argv[1]));
801     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
802     json_destroy(json);
803
804     table = ovsdb_table_create(ts);
805
806     /* Parse conditions. */
807     json = parse_json(argv[2]);
808     if (json->type != JSON_ARRAY) {
809         ovs_fatal(0, "CONDITION argument is not JSON array");
810     }
811     n_conditions = json->u.array.n;
812     conditions = xmalloc(n_conditions * sizeof *conditions);
813     for (i = 0; i < n_conditions; i++) {
814         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
815                                                     NULL, &conditions[i]));
816     }
817     json_destroy(json);
818
819     /* Parse rows. */
820     json = parse_json(argv[3]);
821     if (json->type != JSON_ARRAY) {
822         ovs_fatal(0, "ROW argument is not JSON array");
823     }
824     n_rows = json->u.array.n;
825     rows = xmalloc(n_rows * sizeof *rows);
826     for (i = 0; i < n_rows; i++) {
827         rows[i] = ovsdb_row_create(table);
828         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[i],
829                                               NULL, NULL));
830     }
831     json_destroy(json);
832
833     for (i = 0; i < n_conditions; i++) {
834         printf("condition %2"PRIuSIZE":", i);
835         for (j = 0; j < n_rows; j++) {
836             bool result = ovsdb_condition_evaluate(rows[j], &conditions[i]);
837             if (j % 5 == 0) {
838                 putchar(' ');
839             }
840             putchar(result ? 'T' : '-');
841         }
842         printf("\n");
843     }
844
845     for (i = 0; i < n_conditions; i++) {
846         ovsdb_condition_destroy(&conditions[i]);
847     }
848     free(conditions);
849     for (i = 0; i < n_rows; i++) {
850         ovsdb_row_destroy(rows[i]);
851     }
852     free(rows);
853     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
854 }
855
856 static void
857 do_parse_mutations(int argc, char *argv[])
858 {
859     struct ovsdb_table_schema *ts;
860     struct json *json;
861     int exit_code = 0;
862     int i;
863
864     json = unbox_json(parse_json(argv[1]));
865     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
866     json_destroy(json);
867
868     for (i = 2; i < argc; i++) {
869         struct ovsdb_mutation_set set;
870         struct ovsdb_error *error;
871
872         json = parse_json(argv[i]);
873         error = ovsdb_mutation_set_from_json(ts, json, NULL, &set);
874         if (!error) {
875             print_and_free_json(ovsdb_mutation_set_to_json(&set));
876         } else {
877             char *s = ovsdb_error_to_string(error);
878             ovs_error(0, "%s", s);
879             free(s);
880             ovsdb_error_destroy(error);
881             exit_code = 1;
882         }
883         json_destroy(json);
884
885         ovsdb_mutation_set_destroy(&set);
886     }
887     ovsdb_table_schema_destroy(ts);
888
889     exit(exit_code);
890 }
891
892 static void
893 do_execute_mutations(int argc OVS_UNUSED, char *argv[])
894 {
895     struct ovsdb_table_schema *ts;
896     struct ovsdb_table *table;
897     struct ovsdb_mutation_set *sets;
898     size_t n_sets;
899     struct ovsdb_row **rows;
900     size_t n_rows;
901     struct json *json;
902     size_t i, j;
903
904     /* Parse table schema, create table. */
905     json = unbox_json(parse_json(argv[1]));
906     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
907     json_destroy(json);
908
909     table = ovsdb_table_create(ts);
910
911     /* Parse mutations. */
912     json = parse_json(argv[2]);
913     if (json->type != JSON_ARRAY) {
914         ovs_fatal(0, "MUTATION argument is not JSON array");
915     }
916     n_sets = json->u.array.n;
917     sets = xmalloc(n_sets * sizeof *sets);
918     for (i = 0; i < n_sets; i++) {
919         check_ovsdb_error(ovsdb_mutation_set_from_json(ts,
920                                                        json->u.array.elems[i],
921                                                        NULL, &sets[i]));
922     }
923     json_destroy(json);
924
925     /* Parse rows. */
926     json = parse_json(argv[3]);
927     if (json->type != JSON_ARRAY) {
928         ovs_fatal(0, "ROW argument is not JSON array");
929     }
930     n_rows = json->u.array.n;
931     rows = xmalloc(n_rows * sizeof *rows);
932     for (i = 0; i < n_rows; i++) {
933         rows[i] = ovsdb_row_create(table);
934         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[i],
935                                               NULL, NULL));
936     }
937     json_destroy(json);
938
939     for (i = 0; i < n_sets; i++) {
940         printf("mutation %2"PRIuSIZE":\n", i);
941         for (j = 0; j < n_rows; j++) {
942             struct ovsdb_error *error;
943             struct ovsdb_row *row;
944
945             row = ovsdb_row_clone(rows[j]);
946             error = ovsdb_mutation_set_execute(row, &sets[i]);
947
948             printf("row %"PRIuSIZE": ", j);
949             if (error) {
950                 print_and_free_ovsdb_error(error);
951             } else {
952                 struct ovsdb_column_set columns;
953                 struct shash_node *node;
954
955                 ovsdb_column_set_init(&columns);
956                 SHASH_FOR_EACH (node, &ts->columns) {
957                     struct ovsdb_column *c = node->data;
958                     if (!ovsdb_datum_equals(&row->fields[c->index],
959                                             &rows[j]->fields[c->index],
960                                             &c->type)) {
961                         ovsdb_column_set_add(&columns, c);
962                     }
963                 }
964                 if (columns.n_columns) {
965                     print_and_free_json(ovsdb_row_to_json(row, &columns));
966                 } else {
967                     printf("no change\n");
968                 }
969                 ovsdb_column_set_destroy(&columns);
970             }
971             ovsdb_row_destroy(row);
972         }
973         printf("\n");
974     }
975
976     for (i = 0; i < n_sets; i++) {
977         ovsdb_mutation_set_destroy(&sets[i]);
978     }
979     free(sets);
980     for (i = 0; i < n_rows; i++) {
981         ovsdb_row_destroy(rows[i]);
982     }
983     free(rows);
984     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
985 }
986
987 /* Inserts a row, without bothering to update metadata such as refcounts. */
988 static void
989 put_row(struct ovsdb_table *table, struct ovsdb_row *row)
990 {
991     const struct uuid *uuid = ovsdb_row_get_uuid(row);
992     if (!ovsdb_table_get_row(table, uuid)) {
993         hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
994     }
995 }
996
997 struct do_query_cbdata {
998     struct uuid *row_uuids;
999     int *counts;
1000     size_t n_rows;
1001 };
1002
1003 static bool
1004 do_query_cb(const struct ovsdb_row *row, void *cbdata_)
1005 {
1006     struct do_query_cbdata *cbdata = cbdata_;
1007     size_t i;
1008
1009     for (i = 0; i < cbdata->n_rows; i++) {
1010         if (uuid_equals(ovsdb_row_get_uuid(row), &cbdata->row_uuids[i])) {
1011             cbdata->counts[i]++;
1012         }
1013     }
1014
1015     return true;
1016 }
1017
1018 static void
1019 do_query(int argc OVS_UNUSED, char *argv[])
1020 {
1021     struct do_query_cbdata cbdata;
1022     struct ovsdb_table_schema *ts;
1023     struct ovsdb_table *table;
1024     struct json *json;
1025     int exit_code = 0;
1026     size_t i;
1027
1028     /* Parse table schema, create table. */
1029     json = unbox_json(parse_json(argv[1]));
1030     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
1031     json_destroy(json);
1032
1033     table = ovsdb_table_create(ts);
1034
1035     /* Parse rows, add to table. */
1036     json = parse_json(argv[2]);
1037     if (json->type != JSON_ARRAY) {
1038         ovs_fatal(0, "ROW argument is not JSON array");
1039     }
1040     cbdata.n_rows = json->u.array.n;
1041     cbdata.row_uuids = xmalloc(cbdata.n_rows * sizeof *cbdata.row_uuids);
1042     cbdata.counts = xmalloc(cbdata.n_rows * sizeof *cbdata.counts);
1043     for (i = 0; i < cbdata.n_rows; i++) {
1044         struct ovsdb_row *row = ovsdb_row_create(table);
1045         uuid_generate(ovsdb_row_get_uuid_rw(row));
1046         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
1047                                               NULL, NULL));
1048         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
1049             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
1050                       UUID_ARGS(ovsdb_row_get_uuid(row)));
1051         }
1052         cbdata.row_uuids[i] = *ovsdb_row_get_uuid(row);
1053         put_row(table, row);
1054     }
1055     json_destroy(json);
1056
1057     /* Parse conditions and execute queries. */
1058     json = parse_json(argv[3]);
1059     if (json->type != JSON_ARRAY) {
1060         ovs_fatal(0, "CONDITION argument is not JSON array");
1061     }
1062     for (i = 0; i < json->u.array.n; i++) {
1063         struct ovsdb_condition cnd;
1064         size_t j;
1065
1066         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
1067                                                     NULL, &cnd));
1068
1069         memset(cbdata.counts, 0, cbdata.n_rows * sizeof *cbdata.counts);
1070         ovsdb_query(table, &cnd, do_query_cb, &cbdata);
1071
1072         printf("query %2"PRIuSIZE":", i);
1073         for (j = 0; j < cbdata.n_rows; j++) {
1074             if (j % 5 == 0) {
1075                 putchar(' ');
1076             }
1077             if (cbdata.counts[j]) {
1078                 printf("%d", cbdata.counts[j]);
1079                 if (cbdata.counts[j] > 1) {
1080                     /* Dup! */
1081                     exit_code = 1;
1082                 }
1083             } else {
1084                 putchar('-');
1085             }
1086         }
1087         putchar('\n');
1088
1089         ovsdb_condition_destroy(&cnd);
1090     }
1091     json_destroy(json);
1092
1093     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
1094
1095     exit(exit_code);
1096 }
1097
1098 struct do_query_distinct_class {
1099     struct ovsdb_row *example;
1100     int count;
1101 };
1102
1103 struct do_query_distinct_row {
1104     struct uuid uuid;
1105     struct do_query_distinct_class *class;
1106 };
1107
1108 static void
1109 do_query_distinct(int argc OVS_UNUSED, char *argv[])
1110 {
1111     struct ovsdb_column_set columns;
1112     struct ovsdb_table_schema *ts;
1113     struct ovsdb_table *table;
1114     struct do_query_distinct_row *rows;
1115     size_t n_rows;
1116     struct do_query_distinct_class *classes;
1117     size_t n_classes;
1118     struct json *json;
1119     int exit_code = 0;
1120     size_t i;
1121
1122     /* Parse table schema, create table. */
1123     json = unbox_json(parse_json(argv[1]));
1124     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
1125     json_destroy(json);
1126
1127     table = ovsdb_table_create(ts);
1128
1129     /* Parse column set. */
1130     json = parse_json(argv[4]);
1131     check_ovsdb_error(ovsdb_column_set_from_json(json, table->schema,
1132                                                  &columns));
1133     json_destroy(json);
1134
1135     /* Parse rows, add to table. */
1136     json = parse_json(argv[2]);
1137     if (json->type != JSON_ARRAY) {
1138         ovs_fatal(0, "ROW argument is not JSON array");
1139     }
1140     n_rows = json->u.array.n;
1141     rows = xmalloc(n_rows * sizeof *rows);
1142     classes = xmalloc(n_rows * sizeof *classes);
1143     n_classes = 0;
1144     for (i = 0; i < n_rows; i++) {
1145         struct ovsdb_row *row;
1146         size_t j;
1147
1148         /* Parse row. */
1149         row = ovsdb_row_create(table);
1150         uuid_generate(ovsdb_row_get_uuid_rw(row));
1151         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
1152                                               NULL, NULL));
1153
1154         /* Initialize row and find equivalence class. */
1155         rows[i].uuid = *ovsdb_row_get_uuid(row);
1156         rows[i].class = NULL;
1157         for (j = 0; j < n_classes; j++) {
1158             if (ovsdb_row_equal_columns(row, classes[j].example, &columns)) {
1159                 rows[i].class = &classes[j];
1160                 break;
1161             }
1162         }
1163         if (!rows[i].class) {
1164             rows[i].class = &classes[n_classes];
1165             classes[n_classes].example = ovsdb_row_clone(row);
1166             n_classes++;
1167         }
1168
1169         /* Add row to table. */
1170         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
1171             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
1172                       UUID_ARGS(ovsdb_row_get_uuid(row)));
1173         }
1174         put_row(table, row);
1175
1176     }
1177     json_destroy(json);
1178
1179     /* Parse conditions and execute queries. */
1180     json = parse_json(argv[3]);
1181     if (json->type != JSON_ARRAY) {
1182         ovs_fatal(0, "CONDITION argument is not JSON array");
1183     }
1184     for (i = 0; i < json->u.array.n; i++) {
1185         struct ovsdb_row_set results;
1186         struct ovsdb_condition cnd;
1187         size_t j;
1188
1189         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
1190                                                     NULL, &cnd));
1191
1192         for (j = 0; j < n_classes; j++) {
1193             classes[j].count = 0;
1194         }
1195         ovsdb_row_set_init(&results);
1196         ovsdb_query_distinct(table, &cnd, &columns, &results);
1197         for (j = 0; j < results.n_rows; j++) {
1198             size_t k;
1199
1200             for (k = 0; k < n_rows; k++) {
1201                 if (uuid_equals(ovsdb_row_get_uuid(results.rows[j]),
1202                                 &rows[k].uuid)) {
1203                     rows[k].class->count++;
1204                 }
1205             }
1206         }
1207         ovsdb_row_set_destroy(&results);
1208
1209         printf("query %2"PRIuSIZE":", i);
1210         for (j = 0; j < n_rows; j++) {
1211             int count = rows[j].class->count;
1212
1213             if (j % 5 == 0) {
1214                 putchar(' ');
1215             }
1216             if (count > 1) {
1217                 /* Dup! */
1218                 printf("%d", count);
1219                 exit_code = 1;
1220             } else if (count == 1) {
1221                 putchar("abcdefghijklmnopqrstuvwxyz"[rows[j].class - classes]);
1222             } else {
1223                 putchar('-');
1224             }
1225         }
1226         putchar('\n');
1227
1228         ovsdb_condition_destroy(&cnd);
1229     }
1230     json_destroy(json);
1231
1232     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
1233
1234     exit(exit_code);
1235 }
1236
1237 static void
1238 do_parse_schema(int argc OVS_UNUSED, char *argv[])
1239 {
1240     struct ovsdb_schema *schema;
1241     struct json *json;
1242
1243     json = parse_json(argv[1]);
1244     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1245     json_destroy(json);
1246     print_and_free_json(ovsdb_schema_to_json(schema));
1247     ovsdb_schema_destroy(schema);
1248 }
1249
1250 static void
1251 do_execute(int argc OVS_UNUSED, char *argv[])
1252 {
1253     struct ovsdb_schema *schema;
1254     struct json *json;
1255     struct ovsdb *db;
1256     int i;
1257
1258     /* Create database. */
1259     json = parse_json(argv[1]);
1260     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1261     json_destroy(json);
1262     db = ovsdb_create(schema);
1263
1264     for (i = 2; i < argc; i++) {
1265         struct json *params, *result;
1266         char *s;
1267
1268         params = parse_json(argv[i]);
1269         result = ovsdb_execute(db, NULL, params, 0, NULL);
1270         s = json_to_string(result, JSSF_SORT);
1271         printf("%s\n", s);
1272         free(s);
1273         json_destroy(params);
1274         json_destroy(result);
1275     }
1276
1277     ovsdb_destroy(db);
1278 }
1279
1280 struct test_trigger {
1281     struct ovsdb_trigger trigger;
1282     int number;
1283 };
1284
1285 static void
1286 do_trigger_dump(struct test_trigger *t, long long int now, const char *title)
1287 {
1288     struct json *result;
1289     char *s;
1290
1291     result = ovsdb_trigger_steal_result(&t->trigger);
1292     s = json_to_string(result, JSSF_SORT);
1293     printf("t=%lld: trigger %d (%s): %s\n", now, t->number, title, s);
1294     free(s);
1295     json_destroy(result);
1296     ovsdb_trigger_destroy(&t->trigger);
1297     free(t);
1298 }
1299
1300 static void
1301 do_trigger(int argc OVS_UNUSED, char *argv[])
1302 {
1303     struct ovsdb_schema *schema;
1304     struct ovsdb_session session;
1305     struct ovsdb_server server;
1306     struct json *json;
1307     struct ovsdb *db;
1308     long long int now;
1309     int number;
1310     int i;
1311
1312     /* Create database. */
1313     json = parse_json(argv[1]);
1314     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1315     json_destroy(json);
1316     db = ovsdb_create(schema);
1317
1318     ovsdb_server_init(&server);
1319     ovsdb_server_add_db(&server, db);
1320     ovsdb_session_init(&session, &server);
1321
1322     now = 0;
1323     number = 0;
1324     for (i = 2; i < argc; i++) {
1325         struct json *params = parse_json(argv[i]);
1326         if (params->type == JSON_ARRAY
1327             && json_array(params)->n == 2
1328             && json_array(params)->elems[0]->type == JSON_STRING
1329             && !strcmp(json_string(json_array(params)->elems[0]), "advance")
1330             && json_array(params)->elems[1]->type == JSON_INTEGER) {
1331             now += json_integer(json_array(params)->elems[1]);
1332             json_destroy(params);
1333         } else {
1334             struct test_trigger *t = xmalloc(sizeof *t);
1335             ovsdb_trigger_init(&session, db, &t->trigger, params, now);
1336             t->number = number++;
1337             if (ovsdb_trigger_is_complete(&t->trigger)) {
1338                 do_trigger_dump(t, now, "immediate");
1339             } else {
1340                 printf("t=%lld: new trigger %d\n", now, t->number);
1341             }
1342         }
1343
1344         ovsdb_trigger_run(db, now);
1345         while (!list_is_empty(&session.completions)) {
1346             do_trigger_dump(CONTAINER_OF(list_pop_front(&session.completions),
1347                                          struct test_trigger, trigger.node),
1348                             now, "delayed");
1349         }
1350
1351         ovsdb_trigger_wait(db, now);
1352         poll_immediate_wake();
1353         poll_block();
1354     }
1355
1356     ovsdb_server_destroy(&server);
1357     ovsdb_destroy(db);
1358 }
1359
1360 static void
1361 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1362 {
1363     usage();
1364 }
1365 \f
1366 /* "transact" command. */
1367
1368 static struct ovsdb *do_transact_db;
1369 static struct ovsdb_txn *do_transact_txn;
1370 static struct ovsdb_table *do_transact_table;
1371
1372 static void
1373 do_transact_commit(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1374 {
1375     ovsdb_error_destroy(ovsdb_txn_commit(do_transact_txn, false));
1376     do_transact_txn = NULL;
1377 }
1378
1379 static void
1380 do_transact_abort(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1381 {
1382     ovsdb_txn_abort(do_transact_txn);
1383     do_transact_txn = NULL;
1384 }
1385
1386 static void
1387 uuid_from_integer(int integer, struct uuid *uuid)
1388 {
1389     uuid_zero(uuid);
1390     uuid->parts[3] = integer;
1391 }
1392
1393 static const struct ovsdb_row *
1394 do_transact_find_row(const char *uuid_string)
1395 {
1396     const struct ovsdb_row *row;
1397     struct uuid uuid;
1398
1399     uuid_from_integer(atoi(uuid_string), &uuid);
1400     row = ovsdb_table_get_row(do_transact_table, &uuid);
1401     if (!row) {
1402         ovs_fatal(0, "table does not contain row with UUID "UUID_FMT,
1403                   UUID_ARGS(&uuid));
1404     }
1405     return row;
1406 }
1407
1408 static void
1409 do_transact_set_integer(struct ovsdb_row *row, const char *column_name,
1410                         int integer)
1411 {
1412     if (integer != -1) {
1413         const struct ovsdb_column *column;
1414
1415         column = ovsdb_table_schema_get_column(do_transact_table->schema,
1416                                                column_name);
1417         row->fields[column->index].keys[0].integer = integer;
1418     }
1419 }
1420
1421 static int
1422 do_transact_get_integer(const struct ovsdb_row *row, const char *column_name)
1423 {
1424     const struct ovsdb_column *column;
1425
1426     column = ovsdb_table_schema_get_column(do_transact_table->schema,
1427                                            column_name);
1428     return row->fields[column->index].keys[0].integer;
1429 }
1430
1431 static void
1432 do_transact_set_i_j(struct ovsdb_row *row,
1433                     const char *i_string, const char *j_string)
1434 {
1435     do_transact_set_integer(row, "i", atoi(i_string));
1436     do_transact_set_integer(row, "j", atoi(j_string));
1437 }
1438
1439 static void
1440 do_transact_insert(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1441 {
1442     struct ovsdb_row *row;
1443     struct uuid *uuid;
1444
1445     row = ovsdb_row_create(do_transact_table);
1446
1447     /* Set UUID. */
1448     uuid = ovsdb_row_get_uuid_rw(row);
1449     uuid_from_integer(atoi(argv[1]), uuid);
1450     if (ovsdb_table_get_row(do_transact_table, uuid)) {
1451         ovs_fatal(0, "table already contains row with UUID "UUID_FMT,
1452                   UUID_ARGS(uuid));
1453     }
1454
1455     do_transact_set_i_j(row, argv[2], argv[3]);
1456
1457     /* Insert row. */
1458     ovsdb_txn_row_insert(do_transact_txn, row);
1459 }
1460
1461 static void
1462 do_transact_delete(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1463 {
1464     const struct ovsdb_row *row = do_transact_find_row(argv[1]);
1465     ovsdb_txn_row_delete(do_transact_txn, row);
1466 }
1467
1468 static void
1469 do_transact_modify(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1470 {
1471     const struct ovsdb_row *row_ro;
1472     struct ovsdb_row *row_rw;
1473
1474     row_ro = do_transact_find_row(argv[1]);
1475     row_rw = ovsdb_txn_row_modify(do_transact_txn, row_ro);
1476     do_transact_set_i_j(row_rw, argv[2], argv[3]);
1477 }
1478
1479 static int
1480 compare_rows_by_uuid(const void *a_, const void *b_)
1481 {
1482     struct ovsdb_row *const *ap = a_;
1483     struct ovsdb_row *const *bp = b_;
1484
1485     return uuid_compare_3way(ovsdb_row_get_uuid(*ap), ovsdb_row_get_uuid(*bp));
1486 }
1487
1488 static void
1489 do_transact_print(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1490 {
1491     const struct ovsdb_row **rows;
1492     const struct ovsdb_row *row;
1493     size_t n_rows;
1494     size_t i;
1495
1496     n_rows = hmap_count(&do_transact_table->rows);
1497     rows = xmalloc(n_rows * sizeof *rows);
1498     i = 0;
1499     HMAP_FOR_EACH (row, hmap_node, &do_transact_table->rows) {
1500         rows[i++] = row;
1501     }
1502     assert(i == n_rows);
1503
1504     qsort(rows, n_rows, sizeof *rows, compare_rows_by_uuid);
1505
1506     for (i = 0; i < n_rows; i++) {
1507         printf("\n%"PRId32": i=%d, j=%d",
1508                ovsdb_row_get_uuid(rows[i])->parts[3],
1509                do_transact_get_integer(rows[i], "i"),
1510                do_transact_get_integer(rows[i], "j"));
1511     }
1512
1513     free(rows);
1514 }
1515
1516 static void
1517 do_transact(int argc, char *argv[])
1518 {
1519     static const struct command do_transact_commands[] = {
1520         { "commit", 0, 0, do_transact_commit },
1521         { "abort", 0, 0, do_transact_abort },
1522         { "insert", 2, 3, do_transact_insert },
1523         { "delete", 1, 1, do_transact_delete },
1524         { "modify", 2, 3, do_transact_modify },
1525         { "print", 0, 0, do_transact_print },
1526         { NULL, 0, 0, NULL },
1527     };
1528
1529     struct ovsdb_schema *schema;
1530     struct json *json;
1531     int i;
1532
1533     /* Create table. */
1534     json = parse_json("{\"name\": \"testdb\", "
1535                       " \"tables\": "
1536                       "  {\"mytable\": "
1537                       "    {\"columns\": "
1538                       "      {\"i\": {\"type\": \"integer\"}, "
1539                       "       \"j\": {\"type\": \"integer\"}}}}}");
1540     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1541     json_destroy(json);
1542     do_transact_db = ovsdb_create(schema);
1543     do_transact_table = ovsdb_get_table(do_transact_db, "mytable");
1544     assert(do_transact_table != NULL);
1545
1546     for (i = 1; i < argc; i++) {
1547         struct json *command;
1548         size_t n_args;
1549         char **args;
1550         int j;
1551
1552         command = parse_json(argv[i]);
1553         if (command->type != JSON_ARRAY) {
1554             ovs_fatal(0, "transaction %d must be JSON array "
1555                       "with at least 1 element", i);
1556         }
1557
1558         n_args = command->u.array.n;
1559         args = xmalloc((n_args + 1) * sizeof *args);
1560         for (j = 0; j < n_args; j++) {
1561             struct json *s = command->u.array.elems[j];
1562             if (s->type != JSON_STRING) {
1563                 ovs_fatal(0, "transaction %d argument %d must be JSON string",
1564                           i, j);
1565             }
1566             args[j] = xstrdup(json_string(s));
1567         }
1568         args[n_args] = NULL;
1569
1570         if (!do_transact_txn) {
1571             do_transact_txn = ovsdb_txn_create(do_transact_db);
1572         }
1573
1574         for (j = 0; j < n_args; j++) {
1575             if (j) {
1576                 putchar(' ');
1577             }
1578             fputs(args[j], stdout);
1579         }
1580         fputs(":", stdout);
1581         run_command(n_args, args, do_transact_commands);
1582         putchar('\n');
1583
1584         for (j = 0; j < n_args; j++) {
1585             free(args[j]);
1586         }
1587         free(args);
1588         json_destroy(command);
1589     }
1590     ovsdb_txn_abort(do_transact_txn);
1591     ovsdb_destroy(do_transact_db); /* Also destroys 'schema'. */
1592 }
1593
1594 static int
1595 compare_link1(const void *a_, const void *b_)
1596 {
1597     const struct idltest_link1 *const *ap = a_;
1598     const struct idltest_link1 *const *bp = b_;
1599     const struct idltest_link1 *a = *ap;
1600     const struct idltest_link1 *b = *bp;
1601
1602     return a->i < b->i ? -1 : a->i > b->i;
1603 }
1604
1605 static void
1606 print_idl(struct ovsdb_idl *idl, int step)
1607 {
1608     const struct idltest_simple *s;
1609     const struct idltest_link1 *l1;
1610     const struct idltest_link2 *l2;
1611     int n = 0;
1612
1613     IDLTEST_SIMPLE_FOR_EACH (s, idl) {
1614         size_t i;
1615
1616         printf("%03d: i=%"PRId64" r=%g b=%s s=%s u="UUID_FMT" ia=[",
1617                step, s->i, s->r, s->b ? "true" : "false",
1618                s->s, UUID_ARGS(&s->u));
1619         for (i = 0; i < s->n_ia; i++) {
1620             printf("%s%"PRId64, i ? " " : "", s->ia[i]);
1621         }
1622         printf("] ra=[");
1623         for (i = 0; i < s->n_ra; i++) {
1624             printf("%s%g", i ? " " : "", s->ra[i]);
1625         }
1626         printf("] ba=[");
1627         for (i = 0; i < s->n_ba; i++) {
1628             printf("%s%s", i ? " " : "", s->ba[i] ? "true" : "false");
1629         }
1630         printf("] sa=[");
1631         for (i = 0; i < s->n_sa; i++) {
1632             printf("%s%s", i ? " " : "", s->sa[i]);
1633         }
1634         printf("] ua=[");
1635         for (i = 0; i < s->n_ua; i++) {
1636             printf("%s"UUID_FMT, i ? " " : "", UUID_ARGS(&s->ua[i]));
1637         }
1638         printf("] uuid="UUID_FMT"\n", UUID_ARGS(&s->header_.uuid));
1639         n++;
1640     }
1641     IDLTEST_LINK1_FOR_EACH (l1, idl) {
1642         struct idltest_link1 **links;
1643         size_t i;
1644
1645         printf("%03d: i=%"PRId64" k=", step, l1->i);
1646         if (l1->k) {
1647             printf("%"PRId64, l1->k->i);
1648         }
1649         printf(" ka=[");
1650         links = xmemdup(l1->ka, l1->n_ka * sizeof *l1->ka);
1651         qsort(links, l1->n_ka, sizeof *links, compare_link1);
1652         for (i = 0; i < l1->n_ka; i++) {
1653             printf("%s%"PRId64, i ? " " : "", links[i]->i);
1654         }
1655         free(links);
1656         printf("] l2=");
1657         if (l1->l2) {
1658             printf("%"PRId64, l1->l2->i);
1659         }
1660         printf(" uuid="UUID_FMT"\n", UUID_ARGS(&l1->header_.uuid));
1661         n++;
1662     }
1663     IDLTEST_LINK2_FOR_EACH (l2, idl) {
1664         printf("%03d: i=%"PRId64" l1=", step, l2->i);
1665         if (l2->l1) {
1666             printf("%"PRId64, l2->l1->i);
1667         }
1668         printf(" uuid="UUID_FMT"\n", UUID_ARGS(&l2->header_.uuid));
1669         n++;
1670     }
1671     if (!n) {
1672         printf("%03d: empty\n", step);
1673     }
1674 }
1675
1676 static void
1677 parse_uuids(const struct json *json, struct ovsdb_symbol_table *symtab,
1678             size_t *n)
1679 {
1680     struct uuid uuid;
1681
1682     if (json->type == JSON_STRING && uuid_from_string(&uuid, json->u.string)) {
1683         char *name = xasprintf("#%"PRIuSIZE"#", *n);
1684         fprintf(stderr, "%s = "UUID_FMT"\n", name, UUID_ARGS(&uuid));
1685         ovsdb_symbol_table_put(symtab, name, &uuid, false);
1686         free(name);
1687         *n += 1;
1688     } else if (json->type == JSON_ARRAY) {
1689         size_t i;
1690
1691         for (i = 0; i < json->u.array.n; i++) {
1692             parse_uuids(json->u.array.elems[i], symtab, n);
1693         }
1694     } else if (json->type == JSON_OBJECT) {
1695         const struct shash_node *node;
1696
1697         SHASH_FOR_EACH (node, json_object(json)) {
1698             parse_uuids(node->data, symtab, n);
1699         }
1700     }
1701 }
1702
1703 static void
1704 substitute_uuids(struct json *json, const struct ovsdb_symbol_table *symtab)
1705 {
1706     if (json->type == JSON_STRING) {
1707         const struct ovsdb_symbol *symbol;
1708
1709         symbol = ovsdb_symbol_table_get(symtab, json->u.string);
1710         if (symbol) {
1711             free(json->u.string);
1712             json->u.string = xasprintf(UUID_FMT, UUID_ARGS(&symbol->uuid));
1713         }
1714     } else if (json->type == JSON_ARRAY) {
1715         size_t i;
1716
1717         for (i = 0; i < json->u.array.n; i++) {
1718             substitute_uuids(json->u.array.elems[i], symtab);
1719         }
1720     } else if (json->type == JSON_OBJECT) {
1721         const struct shash_node *node;
1722
1723         SHASH_FOR_EACH (node, json_object(json)) {
1724             substitute_uuids(node->data, symtab);
1725         }
1726     }
1727 }
1728
1729 static const struct idltest_simple *
1730 idltest_find_simple(struct ovsdb_idl *idl, int i)
1731 {
1732     const struct idltest_simple *s;
1733
1734     IDLTEST_SIMPLE_FOR_EACH (s, idl) {
1735         if (s->i == i) {
1736             return s;
1737         }
1738     }
1739     return NULL;
1740 }
1741
1742 static void
1743 idl_set(struct ovsdb_idl *idl, char *commands, int step)
1744 {
1745     char *cmd, *save_ptr1 = NULL;
1746     struct ovsdb_idl_txn *txn;
1747     enum ovsdb_idl_txn_status status;
1748     bool increment = false;
1749
1750     txn = ovsdb_idl_txn_create(idl);
1751     for (cmd = strtok_r(commands, ",", &save_ptr1); cmd;
1752          cmd = strtok_r(NULL, ",", &save_ptr1)) {
1753         char *save_ptr2 = NULL;
1754         char *name, *arg1, *arg2, *arg3;
1755
1756         name = strtok_r(cmd, " ", &save_ptr2);
1757         arg1 = strtok_r(NULL, " ", &save_ptr2);
1758         arg2 = strtok_r(NULL, " ", &save_ptr2);
1759         arg3 = strtok_r(NULL, " ", &save_ptr2);
1760
1761         if (!strcmp(name, "set")) {
1762             const struct idltest_simple *s;
1763
1764             if (!arg3) {
1765                 ovs_fatal(0, "\"set\" command requires 3 arguments");
1766             }
1767
1768             s = idltest_find_simple(idl, atoi(arg1));
1769             if (!s) {
1770                 ovs_fatal(0, "\"set\" command asks for nonexistent "
1771                           "i=%d", atoi(arg1));
1772             }
1773
1774             if (!strcmp(arg2, "b")) {
1775                 idltest_simple_set_b(s, atoi(arg3));
1776             } else if (!strcmp(arg2, "s")) {
1777                 idltest_simple_set_s(s, arg3);
1778             } else if (!strcmp(arg2, "u")) {
1779                 struct uuid uuid;
1780                 if (!uuid_from_string(&uuid, arg3)) {
1781                     ovs_fatal(0, "\"%s\" is not a valid UUID", arg3);
1782                 }
1783                 idltest_simple_set_u(s, uuid);
1784             } else if (!strcmp(arg2, "r")) {
1785                 idltest_simple_set_r(s, atof(arg3));
1786             } else {
1787                 ovs_fatal(0, "\"set\" command asks for unknown column %s",
1788                           arg2);
1789             }
1790         } else if (!strcmp(name, "insert")) {
1791             struct idltest_simple *s;
1792
1793             if (!arg1 || arg2) {
1794                 ovs_fatal(0, "\"insert\" command requires 1 argument");
1795             }
1796
1797             s = idltest_simple_insert(txn);
1798             idltest_simple_set_i(s, atoi(arg1));
1799         } else if (!strcmp(name, "delete")) {
1800             const struct idltest_simple *s;
1801
1802             if (!arg1 || arg2) {
1803                 ovs_fatal(0, "\"delete\" command requires 1 argument");
1804             }
1805
1806             s = idltest_find_simple(idl, atoi(arg1));
1807             if (!s) {
1808                 ovs_fatal(0, "\"delete\" command asks for nonexistent "
1809                           "i=%d", atoi(arg1));
1810             }
1811             idltest_simple_delete(s);
1812         } else if (!strcmp(name, "verify")) {
1813             const struct idltest_simple *s;
1814
1815             if (!arg2 || arg3) {
1816                 ovs_fatal(0, "\"verify\" command requires 2 arguments");
1817             }
1818
1819             s = idltest_find_simple(idl, atoi(arg1));
1820             if (!s) {
1821                 ovs_fatal(0, "\"verify\" command asks for nonexistent "
1822                           "i=%d", atoi(arg1));
1823             }
1824
1825             if (!strcmp(arg2, "i")) {
1826                 idltest_simple_verify_i(s);
1827             } else if (!strcmp(arg2, "b")) {
1828                 idltest_simple_verify_b(s);
1829             } else if (!strcmp(arg2, "s")) {
1830                 idltest_simple_verify_s(s);
1831             } else if (!strcmp(arg2, "u")) {
1832                 idltest_simple_verify_s(s);
1833             } else if (!strcmp(arg2, "r")) {
1834                 idltest_simple_verify_r(s);
1835             } else {
1836                 ovs_fatal(0, "\"verify\" command asks for unknown column %s",
1837                           arg2);
1838             }
1839         } else if (!strcmp(name, "increment")) {
1840             const struct idltest_simple *s;
1841
1842             if (!arg1 || arg2) {
1843                 ovs_fatal(0, "\"increment\" command requires 1 argument");
1844             }
1845
1846             s = idltest_find_simple(idl, atoi(arg1));
1847             if (!s) {
1848                 ovs_fatal(0, "\"set\" command asks for nonexistent "
1849                           "i=%d", atoi(arg1));
1850             }
1851
1852             ovsdb_idl_txn_increment(txn, &s->header_, &idltest_simple_col_i);
1853             increment = true;
1854         } else if (!strcmp(name, "abort")) {
1855             ovsdb_idl_txn_abort(txn);
1856             break;
1857         } else if (!strcmp(name, "destroy")) {
1858             printf("%03d: destroy\n", step);
1859             ovsdb_idl_txn_destroy(txn);
1860             return;
1861         } else {
1862             ovs_fatal(0, "unknown command %s", name);
1863         }
1864     }
1865
1866     status = ovsdb_idl_txn_commit_block(txn);
1867     printf("%03d: commit, status=%s",
1868            step, ovsdb_idl_txn_status_to_string(status));
1869     if (increment) {
1870         printf(", increment=%"PRId64,
1871                ovsdb_idl_txn_get_increment_new_value(txn));
1872     }
1873     putchar('\n');
1874     ovsdb_idl_txn_destroy(txn);
1875 }
1876
1877 static void
1878 do_idl(int argc, char *argv[])
1879 {
1880     struct jsonrpc *rpc;
1881     struct ovsdb_idl *idl;
1882     unsigned int seqno = 0;
1883     struct ovsdb_symbol_table *symtab;
1884     size_t n_uuids = 0;
1885     int step = 0;
1886     int error;
1887     int i;
1888
1889     idltest_init();
1890
1891     idl = ovsdb_idl_create(argv[1], &idltest_idl_class, true, true);
1892     if (argc > 2) {
1893         struct stream *stream;
1894
1895         error = stream_open_block(jsonrpc_stream_open(argv[1], &stream,
1896                                   DSCP_DEFAULT), &stream);
1897         if (error) {
1898             ovs_fatal(error, "failed to connect to \"%s\"", argv[1]);
1899         }
1900         rpc = jsonrpc_open(stream);
1901     } else {
1902         rpc = NULL;
1903     }
1904
1905     setvbuf(stdout, NULL, _IOLBF, 0);
1906
1907     symtab = ovsdb_symbol_table_create();
1908     for (i = 2; i < argc; i++) {
1909         char *arg = argv[i];
1910         struct jsonrpc_msg *request, *reply;
1911
1912         if (*arg == '+') {
1913             /* The previous transaction didn't change anything. */
1914             arg++;
1915         } else {
1916             /* Wait for update. */
1917             for (;;) {
1918                 ovsdb_idl_run(idl);
1919                 if (ovsdb_idl_get_seqno(idl) != seqno) {
1920                     break;
1921                 }
1922                 jsonrpc_run(rpc);
1923
1924                 ovsdb_idl_wait(idl);
1925                 jsonrpc_wait(rpc);
1926                 poll_block();
1927             }
1928
1929             /* Print update. */
1930             print_idl(idl, step++);
1931         }
1932         seqno = ovsdb_idl_get_seqno(idl);
1933
1934         if (!strcmp(arg, "reconnect")) {
1935             printf("%03d: reconnect\n", step++);
1936             ovsdb_idl_force_reconnect(idl);
1937         } else if (arg[0] != '[') {
1938             idl_set(idl, arg, step++);
1939         } else {
1940             struct json *json = parse_json(arg);
1941             substitute_uuids(json, symtab);
1942             request = jsonrpc_create_request("transact", json, NULL);
1943             error = jsonrpc_transact_block(rpc, request, &reply);
1944             if (error || reply->error) {
1945                 ovs_fatal(error, "jsonrpc transaction failed");
1946             }
1947             printf("%03d: ", step++);
1948             if (reply->result) {
1949                 parse_uuids(reply->result, symtab, &n_uuids);
1950             }
1951             json_destroy(reply->id);
1952             reply->id = NULL;
1953             print_and_free_json(jsonrpc_msg_to_json(reply));
1954         }
1955     }
1956     ovsdb_symbol_table_destroy(symtab);
1957
1958     if (rpc) {
1959         jsonrpc_close(rpc);
1960     }
1961     for (;;) {
1962         ovsdb_idl_run(idl);
1963         if (ovsdb_idl_get_seqno(idl) != seqno) {
1964             break;
1965         }
1966         ovsdb_idl_wait(idl);
1967         poll_block();
1968     }
1969     print_idl(idl, step++);
1970     ovsdb_idl_destroy(idl);
1971     printf("%03d: done\n", step);
1972 }
1973
1974 static struct command all_commands[] = {
1975     { "log-io", 2, INT_MAX, do_log_io },
1976     { "default-atoms", 0, 0, do_default_atoms },
1977     { "default-data", 0, 0, do_default_data },
1978     { "parse-atomic-type", 1, 1, do_parse_atomic_type },
1979     { "parse-base-type", 1, 1, do_parse_base_type },
1980     { "parse-type", 1, 1, do_parse_type },
1981     { "parse-atoms", 2, INT_MAX, do_parse_atoms },
1982     { "parse-atom-strings", 2, INT_MAX, do_parse_atom_strings },
1983     { "parse-data", 2, INT_MAX, do_parse_data },
1984     { "parse-data-strings", 2, INT_MAX, do_parse_data_strings },
1985     { "sort-atoms", 2, 2, do_sort_atoms },
1986     { "parse-column", 2, 2, do_parse_column },
1987     { "parse-table", 2, 3, do_parse_table },
1988     { "parse-rows", 2, INT_MAX, do_parse_rows },
1989     { "compare-rows", 2, INT_MAX, do_compare_rows },
1990     { "parse-conditions", 2, INT_MAX, do_parse_conditions },
1991     { "evaluate-conditions", 3, 3, do_evaluate_conditions },
1992     { "parse-mutations", 2, INT_MAX, do_parse_mutations },
1993     { "execute-mutations", 3, 3, do_execute_mutations },
1994     { "query", 3, 3, do_query },
1995     { "query-distinct", 4, 4, do_query_distinct },
1996     { "transact", 1, INT_MAX, do_transact },
1997     { "parse-schema", 1, 1, do_parse_schema },
1998     { "execute", 2, INT_MAX, do_execute },
1999     { "trigger", 2, INT_MAX, do_trigger },
2000     { "idl", 1, INT_MAX, do_idl },
2001     { "help", 0, INT_MAX, do_help },
2002     { NULL, 0, 0, NULL },
2003 };