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