]> git.proxmox.com Git - mirror_ovs.git/blob - ovsdb/ovsdb-idlc.in
ovsdb-idlc: Declare loop variables in for statements in generated code.
[mirror_ovs.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 import ovs.json
9 import ovs.db.error
10 import ovs.db.schema
11
12 argv0 = sys.argv[0]
13
14 def parseSchema(filename):
15 return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
16
17 def annotateSchema(schemaFile, annotationFile):
18 schemaJson = ovs.json.from_file(schemaFile)
19 execfile(annotationFile, globals(), {"s": schemaJson})
20 ovs.json.to_stream(schemaJson, sys.stdout)
21 sys.stdout.write('\n')
22
23 def constify(cType, const):
24 if (const
25 and cType.endswith('*') and
26 (cType == 'char **' or not cType.endswith('**'))):
27 return 'const %s' % cType
28 else:
29 return cType
30
31 def cMembers(prefix, tableName, columnName, column, const, refTable=True):
32 comment = ""
33 type = column.type
34
35 if type.is_smap():
36 comment = """
37 /* Sets the "%(c)s" column's value from the "%(t)s" table in 'row'
38 * to '%(c)s'.
39 *
40 * The caller retains ownership of '%(c)s' and everything in it. */""" \
41 % {'c': columnName,
42 't': tableName}
43 return (comment, [{'name': columnName,
44 'type': 'struct smap ',
45 'comment': ''}])
46
47 comment = """\n/* Sets the "%s" column from the "%s" table in """\
48 """'row' to\n""" % (columnName, tableName)
49
50 if type.n_min == 1 and type.n_max == 1:
51 singleton = True
52 pointer = ''
53 else:
54 singleton = False
55 if type.is_optional_pointer():
56 pointer = ''
57 else:
58 pointer = '*'
59
60
61 if type.value:
62 keyName = "key_%s" % columnName
63 valueName = "value_%s" % columnName
64
65 key = {'name': keyName,
66 'type': constify(type.key.toCType(prefix, refTable) + pointer, const),
67 'comment': ''}
68 value = {'name': valueName,
69 'type': constify(type.value.toCType(prefix, refTable) + pointer, const),
70 'comment': ''}
71
72 if singleton:
73 comment += " * the map with key '%s' and value '%s'\n *" \
74 % (keyName, valueName)
75 else:
76 comment += " * the map with keys '%s' and values '%s'\n *" \
77 % (keyName, valueName)
78 members = [key, value]
79 else:
80 m = {'name': columnName,
81 'type': constify(type.key.toCType(prefix, refTable) + pointer, const),
82 'comment': type.cDeclComment()}
83
84 if singleton:
85 comment += " * '%s'" % columnName
86 else:
87 comment += " * the '%s' set" % columnName
88 members = [m]
89
90 if not singleton and not type.is_optional_pointer():
91 sizeName = "n_%s" % columnName
92
93 comment += " with '%s' entries" % sizeName
94 members.append({'name': sizeName,
95 'type': 'size_t ',
96 'comment': ''})
97
98 comment += ".\n"
99
100 if type.is_optional() and not type.is_optional_pointer():
101 comment += """ *
102 * '%s' may be 0 or 1; if it is 0, then '%s'
103 * may be NULL.\n""" \
104 % ("n_%s" % columnName, columnName)
105
106 if type.is_optional_pointer():
107 comment += """ *
108 * If "%s" is null, the column will be the empty set,
109 * otherwise it will contain the specified value.\n""" % columnName
110
111 if type.constraintsToEnglish():
112 comment += """ *
113 * Argument constraints: %s\n""" \
114 % type.constraintsToEnglish(lambda s : '"%s"' % s)
115
116 comment += " *\n * The caller retains ownership of the arguments. */"
117
118 return (comment, members)
119
120 def sorted_columns(table):
121 return sorted(table.columns.items())
122
123 def printCIDLHeader(schemaFile):
124 schema = parseSchema(schemaFile)
125 prefix = schema.idlPrefix
126 print '''\
127 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
128
129 #ifndef %(prefix)sIDL_HEADER
130 #define %(prefix)sIDL_HEADER 1
131
132 #include <stdbool.h>
133 #include <stddef.h>
134 #include <stdint.h>
135 #include "ovsdb-data.h"
136 #include "ovsdb-idl-provider.h"
137 #include "smap.h"
138 #include "uuid.h"''' % {'prefix': prefix.upper()}
139
140 for tableName, table in sorted(schema.tables.iteritems()):
141 structName = "%s%s" % (prefix, tableName.lower())
142
143 print "\f"
144 print "/* %s table. */" % tableName
145 print "struct %s {" % structName
146 print "\tstruct ovsdb_idl_row header_;"
147 for columnName, column in sorted_columns(table):
148 print "\n\t/* %s column. */" % columnName
149 comment, members = cMembers(prefix, tableName,
150 columnName, column, False)
151 for member in members:
152 print "\t%(type)s%(name)s;%(comment)s" % member
153 print "};"
154
155 # Column indexes.
156 printEnum("%s_column_id" % structName.lower(), ["%s_COL_%s" % (structName.upper(), columnName.upper())
157 for columnName, column in sorted_columns(table)]
158 + ["%s_N_COLUMNS" % structName.upper()])
159
160 print
161 for columnName in table.columns:
162 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
163 's': structName,
164 'S': structName.upper(),
165 'c': columnName,
166 'C': columnName.upper()}
167
168 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
169
170 print '''
171 const struct %(s)s *%(s)s_get_for_uuid(const struct ovsdb_idl *, const struct uuid *);
172 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
173 const struct %(s)s *%(s)s_next(const struct %(s)s *);
174 #define %(S)s_FOR_EACH(ROW, IDL) \\
175 for ((ROW) = %(s)s_first(IDL); \\
176 (ROW); \\
177 (ROW) = %(s)s_next(ROW))
178 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
179 for ((ROW) = %(s)s_first(IDL); \\
180 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
181 (ROW) = (NEXT))
182
183 unsigned int %(s)s_get_seqno(const struct ovsdb_idl *);
184 unsigned int %(s)s_row_get_seqno(const struct %(s)s *row, enum ovsdb_idl_change change);
185 const struct %(s)s *%(s)s_track_get_first(const struct ovsdb_idl *);
186 const struct %(s)s *%(s)s_track_get_next(const struct %(s)s *);
187 #define %(S)s_FOR_EACH_TRACKED(ROW, IDL) \\
188 for ((ROW) = %(s)s_track_get_first(IDL); \\
189 (ROW); \\
190 (ROW) = %(s)s_track_get_next(ROW))
191
192 /* Returns true if 'row' was inserted since the last change tracking reset. */
193 static inline bool %(s)s_is_new(const struct %(s)s *row)
194 {
195 return %(s)s_row_get_seqno(row, OVSDB_IDL_CHANGE_MODIFY) == 0;
196 }
197
198 /* Returns true if 'row' was deleted since the last change tracking reset. */
199 static inline bool %(s)s_is_deleted(const struct %(s)s *row)
200 {
201 return %(s)s_row_get_seqno(row, OVSDB_IDL_CHANGE_DELETE) > 0;
202 }
203
204 void %(s)s_init(struct %(s)s *);
205 void %(s)s_delete(const struct %(s)s *);
206 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
207 bool %(s)s_is_updated(const struct %(s)s *, enum %(s)s_column_id);
208 ''' % {'s': structName, 'S': structName.upper()}
209
210 for columnName, column in sorted_columns(table):
211 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
212
213 print
214 for columnName, column in sorted_columns(table):
215 if column.type.value:
216 valueParam = ', enum ovsdb_atomic_type value_type'
217 else:
218 valueParam = ''
219 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
220 's': structName, 'c': columnName, 'v': valueParam}
221
222 print
223 for columnName, column in sorted_columns(table):
224 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
225 if column.type.is_smap():
226 args = ['const struct smap *']
227 else:
228 comment, members = cMembers(prefix, tableName, columnName,
229 column, True)
230 args = ['%(type)s%(name)s' % member for member in members]
231 print '%s);' % ', '.join(args)
232
233 print
234 for columnName, column in sorted_columns(table):
235 if column.type.is_map():
236 print 'void %(s)s_update_%(c)s_setkey(const struct %(s)s *, ' % {'s': structName, 'c': columnName},
237 print '%(coltype)s, %(valtype)s);' % {'coltype':column.type.key.to_const_c_type(prefix), 'valtype':column.type.value.to_const_c_type(prefix)}
238 print 'void %(s)s_update_%(c)s_delkey(const struct %(s)s *, ' % {'s': structName, 'c': columnName},
239 print '%(coltype)s);' % {'coltype':column.type.key.to_const_c_type(prefix)}
240 if column.type.is_set():
241 print 'void %(s)s_update_%(c)s_addvalue(const struct %(s)s *, ' % {'s': structName, 'c': columnName},
242 print '%(valtype)s);' % {'valtype':column.type.key.to_const_c_type(prefix)}
243 print 'void %(s)s_update_%(c)s_delvalue(const struct %(s)s *, ' % {'s': structName, 'c': columnName},
244 print '%(valtype)s);' % {'valtype':column.type.key.to_const_c_type(prefix)}
245
246 print 'void %(s)s_add_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function,' % {'s': structName, 'c': columnName},
247 if column.type.is_smap():
248 args = ['const struct smap *']
249 else:
250 comment, members = cMembers(prefix, tableName, columnName,
251 column, True, refTable=False)
252 args = ['%(type)s%(name)s' % member for member in members]
253 print '%s);' % ', '.join(args)
254
255 print 'void %s_add_clause_true(struct ovsdb_idl *idl);' % structName
256 print 'void %s_add_clause_false(struct ovsdb_idl *idl);' % structName
257
258 print
259 for columnName, column in sorted_columns(table):
260 print 'void %(s)s_remove_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function,' % {'s': structName, 'c': columnName},
261 if column.type.is_smap():
262 args = ['const struct smap *']
263 else:
264 comment, members = cMembers(prefix, tableName, columnName,
265 column, True, refTable=False)
266 args = ['%(type)s%(name)s' % member for member in members]
267 print '%s);' % ', '.join(args)
268
269 print 'void %s_remove_clause_true(struct ovsdb_idl *idl);' % structName
270 print 'void %s_remove_clause_false(struct ovsdb_idl *idl);' % structName
271
272 print
273
274 # Table indexes.
275 printEnum("%stable_id" % prefix.lower(), ["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
276 print
277 for tableName in schema.tables:
278 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
279 'p': prefix,
280 'P': prefix.upper(),
281 't': tableName.lower(),
282 'T': tableName.upper()}
283 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
284
285 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
286 print "\nvoid %sinit(void);" % prefix
287
288 print "\nconst char * %sget_db_version(void);" % prefix
289 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
290
291 def printEnum(type, members):
292 if len(members) == 0:
293 return
294
295 print "\nenum %s {" % type
296 for member in members[:-1]:
297 print " %s," % member
298 print " %s" % members[-1]
299 print "};"
300
301 def printCIDLSource(schemaFile):
302 schema = parseSchema(schemaFile)
303 prefix = schema.idlPrefix
304 print '''\
305 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
306
307 #include <config.h>
308 #include %s
309 #include <limits.h>
310 #include "ovs-thread.h"
311 #include "ovsdb-data.h"
312 #include "ovsdb-error.h"
313 #include "util.h"
314
315 #ifdef __CHECKER__
316 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
317 enum { sizeof_bool = 1 };
318 #else
319 enum { sizeof_bool = sizeof(bool) };
320 #endif
321
322 static bool inited;
323 ''' % schema.idlHeader
324
325 # Cast functions.
326 for tableName, table in sorted(schema.tables.iteritems()):
327 structName = "%s%s" % (prefix, tableName.lower())
328 print '''
329 static struct %(s)s *
330 %(s)s_cast(const struct ovsdb_idl_row *row)
331 {
332 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
333 }\
334 ''' % {'s': structName}
335
336
337 for tableName, table in sorted(schema.tables.iteritems()):
338 structName = "%s%s" % (prefix, tableName.lower())
339 print "\f"
340 print "/* %s table. */" % (tableName)
341
342 # Parse functions.
343 for columnName, column in sorted_columns(table):
344 print '''
345 static void
346 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
347 {
348 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
349 'c': columnName}
350 type = column.type
351 if type.value:
352 keyVar = "row->key_%s" % columnName
353 valueVar = "row->value_%s" % columnName
354 else:
355 keyVar = "row->%s" % columnName
356 valueVar = None
357
358 if type.is_smap():
359 print " ovs_assert(inited);"
360 print " smap_init(&row->%s);" % columnName
361 print " for (size_t i = 0; i < datum->n; i++) {"
362 print " smap_add(&row->%s," % columnName
363 print " datum->keys[i].string,"
364 print " datum->values[i].string);"
365 print " }"
366 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
367 print
368 print " ovs_assert(inited);"
369 print " if (datum->n >= 1) {"
370 if not type.key.ref_table:
371 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
372 else:
373 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_%s, &datum->keys[0].uuid));" % (keyVar, prefix, type.key.ref_table.name.lower(), prefix, type.key.ref_table.name.lower())
374
375 if valueVar:
376 if not type.value.ref_table:
377 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
378 else:
379 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_%s, &datum->values[0].uuid));" % (valueVar, prefix, type.value.ref_table.name.lower(), prefix, type.value.ref_table.name.lower())
380 print " } else {"
381 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
382 if valueVar:
383 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
384 print " }"
385 else:
386 if type.n_max != sys.maxint:
387 print " size_t n = MIN(%d, datum->n);" % type.n_max
388 nMax = "n"
389 else:
390 nMax = "datum->n"
391 print " ovs_assert(inited);"
392 print " %s = NULL;" % keyVar
393 if valueVar:
394 print " %s = NULL;" % valueVar
395 print " row->n_%s = 0;" % columnName
396 print " for (size_t i = 0; i < %s; i++) {" % nMax
397 if type.key.ref_table:
398 print """\
399 struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_%s, &datum->keys[i].uuid));
400 if (!keyRow) {
401 continue;
402 }\
403 """ % (prefix, type.key.ref_table.name.lower(), prefix, type.key.ref_table.name.lower(), prefix, type.key.ref_table.name.lower())
404 keySrc = "keyRow"
405 else:
406 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
407 if type.value and type.value.ref_table:
408 print """\
409 struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_%s, &datum->values[i].uuid));
410 if (!valueRow) {
411 continue;
412 }\
413 """ % (prefix, type.value.ref_table.name.lower(), prefix, type.value.ref_table.name.lower(), prefix, type.value.ref_table.name.lower())
414 valueSrc = "valueRow"
415 elif valueVar:
416 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
417 print " if (!row->n_%s) {" % (columnName)
418
419 # Special case for boolean types. This is only here because
420 # sparse does not like the "normal" case ("warning: expression
421 # using sizeof bool").
422 if type.key.type == ovs.db.types.BooleanType:
423 sizeof = "sizeof_bool"
424 else:
425 sizeof = "sizeof *%s" % keyVar
426 print " %s = xmalloc(%s * %s);" % (keyVar, nMax,
427 sizeof)
428 if valueVar:
429 # Special case for boolean types (see above).
430 if type.value.type == ovs.db.types.BooleanType:
431 sizeof = " * sizeof_bool"
432 else:
433 sizeof = "sizeof *%s" % valueVar
434 print " %s = xmalloc(%s * %s);" % (valueVar,
435 nMax, sizeof)
436 print " }"
437 print " %s[row->n_%s] = %s;" % (keyVar, columnName, keySrc)
438 if valueVar:
439 print " %s[row->n_%s] = %s;" % (valueVar, columnName, valueSrc)
440 print " row->n_%s++;" % columnName
441 print " }"
442 print "}"
443
444 # Unparse functions.
445 for columnName, column in sorted_columns(table):
446 type = column.type
447 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
448 print '''
449 static void
450 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
451 {
452 struct %(s)s *row = %(s)s_cast(row_);
453
454 ovs_assert(inited);''' % {'s': structName, 'c': columnName}
455
456 if type.is_smap():
457 print " smap_destroy(&row->%s);" % columnName
458 else:
459 if type.value:
460 keyVar = "row->key_%s" % columnName
461 valueVar = "row->value_%s" % columnName
462 else:
463 keyVar = "row->%s" % columnName
464 valueVar = None
465 print " free(%s);" % keyVar
466 if valueVar:
467 print " free(%s);" % valueVar
468 print '}'
469 else:
470 print '''
471 static void
472 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
473 {
474 /* Nothing to do. */
475 }''' % {'s': structName, 'c': columnName}
476
477 # Generic Row Initialization function.
478 print """
479 static void
480 %(s)s_init__(struct ovsdb_idl_row *row)
481 {
482 %(s)s_init(%(s)s_cast(row));
483 }""" % {'s': structName}
484
485 # Row Initialization function.
486 print """
487 /* Clears the contents of 'row' in table "%(t)s". */
488 void
489 %(s)s_init(struct %(s)s *row)
490 {
491 memset(row, 0, sizeof *row); """ % {'s': structName, 't': tableName}
492 for columnName, column in sorted_columns(table):
493 if column.type.is_smap():
494 print " smap_init(&row->%s);" % columnName
495 print "}"
496
497 # First, next functions.
498 print '''
499 /* Searches table "%(t)s" in 'idl' for a row with UUID 'uuid'. Returns
500 * a pointer to the row if there is one, otherwise a null pointer. */
501 const struct %(s)s *
502 %(s)s_get_for_uuid(const struct ovsdb_idl *idl, const struct uuid *uuid)
503 {
504 return %(s)s_cast(ovsdb_idl_get_row_for_uuid(idl, &%(p)stable_%(tl)s, uuid));
505 }
506
507 /* Returns a row in table "%(t)s" in 'idl', or a null pointer if that
508 * table is empty.
509 *
510 * Database tables are internally maintained as hash tables, so adding or
511 * removing rows while traversing the same table can cause some rows to be
512 * visited twice or not at apply. */
513 const struct %(s)s *
514 %(s)s_first(const struct ovsdb_idl *idl)
515 {
516 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_%(tl)s));
517 }
518
519 /* Returns a row following 'row' within its table, or a null pointer if 'row'
520 * is the last row in its table. */
521 const struct %(s)s *
522 %(s)s_next(const struct %(s)s *row)
523 {
524 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
525 }
526
527 unsigned int %(s)s_get_seqno(const struct ovsdb_idl *idl)
528 {
529 return ovsdb_idl_table_get_seqno(idl, &%(p)stable_%(tl)s);
530 }
531
532 unsigned int %(s)s_row_get_seqno(const struct %(s)s *row, enum ovsdb_idl_change change)
533 {
534 return ovsdb_idl_row_get_seqno(&row->header_, change);
535 }
536
537 const struct %(s)s *
538 %(s)s_track_get_first(const struct ovsdb_idl *idl)
539 {
540 return %(s)s_cast(ovsdb_idl_track_get_first(idl, &%(p)stable_%(tl)s));
541 }
542
543 const struct %(s)s
544 *%(s)s_track_get_next(const struct %(s)s *row)
545 {
546 return %(s)s_cast(ovsdb_idl_track_get_next(&row->header_));
547 }''' % {'s': structName,
548 'p': prefix,
549 'P': prefix.upper(),
550 't': tableName,
551 'tl': tableName.lower(),
552 'T': tableName.upper()}
553
554 print '''
555
556 /* Deletes 'row' from table "%(t)s". 'row' may be freed, so it must not be
557 * accessed afterward.
558 *
559 * The caller must have started a transaction with ovsdb_idl_txn_create(). */
560 void
561 %(s)s_delete(const struct %(s)s *row)
562 {
563 ovsdb_idl_txn_delete(&row->header_);
564 }
565
566 /* Inserts and returns a new row in the table "%(t)s" in the database
567 * with open transaction 'txn'.
568 *
569 * The new row is assigned a randomly generated provisional UUID.
570 * ovsdb-server will assign a different UUID when 'txn' is committed,
571 * but the IDL will replace any uses of the provisional UUID in the
572 * data to be to be committed by the UUID assigned by ovsdb-server. */
573 struct %(s)s *
574 %(s)s_insert(struct ovsdb_idl_txn *txn)
575 {
576 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_%(tl)s, NULL));
577 }
578
579 bool
580 %(s)s_is_updated(const struct %(s)s *row, enum %(s)s_column_id column)
581 {
582 return ovsdb_idl_track_is_updated(&row->header_, &%(s)s_columns[column]);
583 }''' % {'s': structName,
584 'p': prefix,
585 'P': prefix.upper(),
586 't': tableName,
587 'tl': tableName.lower(),
588 'T': tableName.upper()}
589
590 # Verify functions.
591 for columnName, column in sorted_columns(table):
592 print '''
593 /* Causes the original contents of column "%(c)s" in 'row' to be
594 * verified as a prerequisite to completing the transaction. That is, if
595 * "%(c)s" in 'row' changed (or if 'row' was deleted) between the
596 * time that the IDL originally read its contents and the time that the
597 * transaction aborts and ovsdb_idl_txn_commit() returns TXN_TRY_AGAIN.
598 *
599 * The intention is that, to ensure that no transaction commits based on dirty
600 * reads, an application should call this function any time "%(c)s" is
601 * read as part of a read-modify-write operation.
602 *
603 * In some cases this function reduces to a no-op, because the current value
604 * of "%(c)s" is already known:
605 *
606 * - If 'row' is a row created by the current transaction (returned by
607 * %(s)s_insert()).
608 *
609 * - If "%(c)s" has already been modified (with
610 * %(s)s_set_%(c)s()) within the current transaction.
611 *
612 * Because of the latter property, always call this function *before*
613 * %(s)s_set_%(c)s() for a given read-modify-write.
614 *
615 * The caller must have started a transaction with ovsdb_idl_txn_create(). */
616 void
617 %(s)s_verify_%(c)s(const struct %(s)s *row)
618 {
619 ovs_assert(inited);
620 ovsdb_idl_txn_verify(&row->header_, &%(s)s_col_%(c)s);
621 }''' % {'s': structName,
622 'S': structName.upper(),
623 'c': columnName,
624 'C': columnName.upper()}
625
626 # Get functions.
627 for columnName, column in sorted_columns(table):
628 if column.type.value:
629 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
630 valueType = '\n ovs_assert(value_type == %s);' % column.type.value.toAtomicType()
631 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
632 else:
633 valueParam = ''
634 valueType = ''
635 valueComment = ''
636 print """
637 /* Returns the "%(c)s" column's value from the "%(t)s" table in 'row'
638 * as a struct ovsdb_datum. This is useful occasionally: for example,
639 * ovsdb_datum_find_key() is an easier and more efficient way to search
640 * for a given key than implementing the same operation on the "cooked"
641 * form in 'row'.
642 *
643 * 'key_type' must be %(kt)s.%(vc)s
644 * (This helps to avoid silent bugs if someone changes %(c)s's
645 * type without updating the caller.)
646 *
647 * The caller must not modify or free the returned value.
648 *
649 * Various kinds of changes can invalidate the returned value: modifying
650 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
651 * If the returned value is needed for a long time, it is best to make a copy
652 * of it with ovsdb_datum_clone().
653 *
654 * This function is rarely useful, since it is easier to access the value
655 * directly through the "%(c)s" member in %(s)s. */
656 const struct ovsdb_datum *
657 %(s)s_get_%(c)s(const struct %(s)s *row,
658 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
659 {
660 ovs_assert(key_type == %(kt)s);%(vt)s
661 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
662 }""" % {'t': tableName, 's': structName, 'c': columnName,
663 'kt': column.type.key.toAtomicType(),
664 'v': valueParam, 'vt': valueType, 'vc': valueComment}
665
666 # Set functions.
667 for columnName, column in sorted_columns(table):
668 type = column.type
669
670 comment, members = cMembers(prefix, tableName, columnName,
671 column, True)
672
673 if type.is_smap():
674 print comment
675 print """void
676 %(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *%(c)s)
677 {
678 struct ovsdb_datum datum;
679
680 ovs_assert(inited);
681 if (%(c)s) {
682 ovsdb_datum_from_smap(&datum, %(c)s);
683 } else {
684 ovsdb_datum_init_empty(&datum);
685 }
686 ovsdb_idl_txn_write(&row->header_,
687 &%(s)s_col_%(c)s,
688 &datum);
689 }
690 """ % {'t': tableName,
691 's': structName,
692 'S': structName.upper(),
693 'c': columnName,
694 'C': columnName.upper()}
695 continue
696
697 keyVar = members[0]['name']
698 nVar = None
699 valueVar = None
700 if type.value:
701 valueVar = members[1]['name']
702 if len(members) > 2:
703 nVar = members[2]['name']
704 else:
705 if len(members) > 1:
706 nVar = members[1]['name']
707
708 print comment
709 print 'void'
710 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
711 {'s': structName, 'c': columnName,
712 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
713 print "{"
714 print " struct ovsdb_datum datum;"
715 if type.n_min == 1 and type.n_max == 1:
716 print " union ovsdb_atom key;"
717 if type.value:
718 print " union ovsdb_atom value;"
719 print
720 print " ovs_assert(inited);"
721 print " datum.n = 1;"
722 print " datum.keys = &key;"
723 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
724 if type.value:
725 print " datum.values = &value;"
726 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar)
727 else:
728 print " datum.values = NULL;"
729 txn_write_func = "ovsdb_idl_txn_write_clone"
730 elif type.is_optional_pointer():
731 print " union ovsdb_atom key;"
732 print
733 print " ovs_assert(inited);"
734 print " if (%s) {" % keyVar
735 print " datum.n = 1;"
736 print " datum.keys = &key;"
737 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
738 print " } else {"
739 print " datum.n = 0;"
740 print " datum.keys = NULL;"
741 print " }"
742 print " datum.values = NULL;"
743 txn_write_func = "ovsdb_idl_txn_write_clone"
744 elif type.n_max == 1:
745 print " union ovsdb_atom key;"
746 print
747 print " ovs_assert(inited);"
748 print " if (%s) {" % nVar
749 print " datum.n = 1;"
750 print " datum.keys = &key;"
751 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar)
752 print " } else {"
753 print " datum.n = 0;"
754 print " datum.keys = NULL;"
755 print " }"
756 print " datum.values = NULL;"
757 txn_write_func = "ovsdb_idl_txn_write_clone"
758 else:
759 print
760 print " ovs_assert(inited);"
761 print " datum.n = %s;" % nVar
762 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
763 if type.value:
764 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
765 else:
766 print " datum.values = NULL;"
767 print " for (size_t i = 0; i < %s; i++) {" % nVar
768 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
769 if type.value:
770 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
771 print " }"
772 if type.value:
773 valueType = type.value.toAtomicType()
774 else:
775 valueType = "OVSDB_TYPE_VOID"
776 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
777 type.key.toAtomicType(), valueType)
778 txn_write_func = "ovsdb_idl_txn_write"
779 print " %(f)s(&row->header_, &%(s)s_col_%(c)s, &datum);" \
780 % {'f': txn_write_func,
781 's': structName,
782 'S': structName.upper(),
783 'c': columnName}
784 print "}"
785 # Update/Delete of partial map column functions
786 for columnName, column in sorted_columns(table):
787 type = column.type
788 if type.is_map():
789 print '''
790 /* Sets an element of the "%(c)s" map column from the "%(t)s" table in 'row'
791 * to 'new_value' given the key value 'new_key'.
792 *
793 */
794 void
795 %(s)s_update_%(c)s_setkey(const struct %(s)s *row, %(coltype)snew_key, %(valtype)snew_value)
796 {
797 struct ovsdb_datum *datum;
798
799 ovs_assert(inited);
800
801 datum = xmalloc(sizeof *datum);
802 datum->n = 1;
803 datum->keys = xmalloc(datum->n * sizeof *datum->keys);
804 datum->values = xmalloc(datum->n * sizeof *datum->values);
805 ''' % {'s': structName, 'c': columnName,'coltype':column.type.key.to_const_c_type(prefix),
806 'valtype':column.type.value.to_const_c_type(prefix), 'S': structName.upper(),
807 'C': columnName.upper(), 't': tableName}
808
809 print " "+ type.key.copyCValue("datum->keys[0].%s" % type.key.type.to_string(), "new_key")
810 print " "+ type.value.copyCValue("datum->values[0].%s" % type.value.type.to_string(), "new_value")
811 print '''
812 ovsdb_idl_txn_write_partial_map(&row->header_,
813 &%(s)s_col_%(c)s,
814 datum);
815 }''' % {'s': structName, 'c': columnName,'coltype':column.type.key.toCType(prefix),
816 'valtype':column.type.value.to_const_c_type(prefix), 'S': structName.upper()}
817 print '''
818 /* Deletes an element of the "%(c)s" map column from the "%(t)s" table in 'row'
819 * given the key value 'delete_key'.
820 *
821 */
822 void
823 %(s)s_update_%(c)s_delkey(const struct %(s)s *row, %(coltype)sdelete_key)
824 {
825 struct ovsdb_datum *datum;
826
827 ovs_assert(inited);
828
829 datum = xmalloc(sizeof *datum);
830 datum->n = 1;
831 datum->keys = xmalloc(datum->n * sizeof *datum->keys);
832 datum->values = NULL;
833 ''' % {'s': structName, 'c': columnName,'coltype':column.type.key.to_const_c_type(prefix),
834 'valtype':column.type.value.to_const_c_type(prefix), 'S': structName.upper(),
835 'C': columnName.upper(), 't': tableName}
836
837 print " "+ type.key.copyCValue("datum->keys[0].%s" % type.key.type.to_string(), "delete_key")
838 print '''
839 ovsdb_idl_txn_delete_partial_map(&row->header_,
840 &%(s)s_col_%(c)s,
841 datum);
842 }''' % {'s': structName, 'c': columnName,'coltype':column.type.key.toCType(prefix),
843 'valtype':column.type.value.to_const_c_type(prefix), 'S': structName.upper()}
844 # End Update/Delete of partial maps
845 # Update/Delete of partial set column functions
846 if type.is_set():
847 print '''
848 /* Adds the value 'new_value' to the "%(c)s" set column from the "%(t)s" table
849 * in 'row'.
850 *
851 */
852 void
853 %(s)s_update_%(c)s_addvalue(const struct %(s)s *row, %(valtype)snew_value)
854 {
855 struct ovsdb_datum *datum;
856
857 ovs_assert(inited);
858
859 datum = xmalloc(sizeof *datum);
860 datum->n = 1;
861 datum->keys = xmalloc(datum->n * sizeof *datum->values);
862 datum->values = NULL;
863 ''' % {'s': structName, 'c': columnName,
864 'valtype':column.type.key.to_const_c_type(prefix), 't': tableName}
865
866 print " "+ type.key.copyCValue("datum->keys[0].%s" % type.key.type.to_string(), "new_value")
867 print '''
868 ovsdb_idl_txn_write_partial_set(&row->header_,
869 &%(s)s_col_%(c)s,
870 datum);
871 }''' % {'s': structName, 'c': columnName,'coltype':column.type.key.toCType(prefix),
872 'valtype':column.type.key.to_const_c_type(prefix), 'S': structName.upper()}
873 print '''
874 /* Deletes the value 'delete_value' from the "%(c)s" set column from the
875 * "%(t)s" table in 'row'.
876 *
877 */
878 void
879 %(s)s_update_%(c)s_delvalue(const struct %(s)s *row, %(valtype)sdelete_value)
880 {
881 struct ovsdb_datum *datum;
882
883 ovs_assert(inited);
884
885 datum = xmalloc(sizeof *datum);
886 datum->n = 1;
887 datum->keys = xmalloc(datum->n * sizeof *datum->values);
888 datum->values = NULL;
889 ''' % {'s': structName, 'c': columnName,'coltype':column.type.key.to_const_c_type(prefix),
890 'valtype':column.type.key.to_const_c_type(prefix), 'S': structName.upper(),
891 'C': columnName.upper(), 't': tableName}
892
893 print " "+ type.key.copyCValue("datum->keys[0].%s" % type.key.type.to_string(), "delete_value")
894 print '''
895 ovsdb_idl_txn_delete_partial_set(&row->header_,
896 &%(s)s_col_%(c)s,
897 datum);
898 }''' % {'s': structName, 'c': columnName,'coltype':column.type.key.toCType(prefix),
899 'valtype':column.type.key.to_const_c_type(prefix), 'S': structName.upper()}
900 # End Update/Delete of partial set
901
902 # Add clause functions.
903 for columnName, column in sorted_columns(table):
904 type = column.type
905
906 comment, members = cMembers(prefix, tableName, columnName,
907 column, True, refTable=False)
908
909 if type.is_smap():
910 print comment
911 print """void
912 %(s)s_add_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function, const struct smap *%(c)s)
913 {
914 struct ovsdb_datum datum;
915
916 ovs_assert(inited);
917 if (%(c)s) {
918 ovsdb_datum_from_smap(&datum, %(c)s);
919 } else {
920 ovsdb_datum_init_empty(&datum);
921 }
922
923 ovsdb_idl_condition_add_clause(idl,
924 &%(p)stable_%(tl)s,
925 function,
926 &%(s)s_col_%(c)s,
927 &datum);
928
929 ovsdb_datum_destroy(&datum, &%(s)s_col_%(c)s.type);
930 }
931 """ % {'t': tableName,
932 'tl': tableName.lower(),
933 'T': tableName.upper(),
934 'p': prefix,
935 'P': prefix.upper(),
936 's': structName,
937 'S': structName.upper(),
938 'c': columnName}
939 continue
940
941 keyVar = members[0]['name']
942 nVar = None
943 valueVar = None
944 if type.value:
945 valueVar = members[1]['name']
946 if len(members) > 2:
947 nVar = members[2]['name']
948 else:
949 if len(members) > 1:
950 nVar = members[1]['name']
951
952 print comment
953 print 'void'
954 print '%(s)s_add_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function, %(args)s)' % \
955 {'s': structName, 'c': columnName,
956 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
957 print "{"
958 print " struct ovsdb_datum datum;"
959 free = []
960 if type.n_min == 1 and type.n_max == 1:
961 print " union ovsdb_atom key;"
962 if type.value:
963 print " union ovsdb_atom value;"
964 print
965 print " ovs_assert(inited);"
966 print " datum.n = 1;"
967 print " datum.keys = &key;"
968 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar, refTable=False)
969 if type.value:
970 print " datum.values = &value;"
971 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar, refTable=False)
972 else:
973 print " datum.values = NULL;"
974 elif type.is_optional_pointer():
975 print " union ovsdb_atom key;"
976 print
977 print " ovs_assert(inited);"
978 print " if (%s) {" % keyVar
979 print " datum.n = 1;"
980 print " datum.keys = &key;"
981 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar, refTable=False)
982 print " } else {"
983 print " datum.n = 0;"
984 print " datum.keys = NULL;"
985 print " }"
986 print " datum.values = NULL;"
987 elif type.n_max == 1:
988 print " union ovsdb_atom key;"
989 print
990 print " ovs_assert(inited);"
991 print " if (%s) {" % nVar
992 print " datum.n = 1;"
993 print " datum.keys = &key;"
994 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar, refTable=False)
995 print " } else {"
996 print " datum.n = 0;"
997 print " datum.keys = NULL;"
998 print " }"
999 print " datum.values = NULL;"
1000 else:
1001 print " ovs_assert(inited);"
1002 print " datum.n = %s;" % nVar
1003 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
1004 free += ['datum.keys']
1005 if type.value:
1006 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
1007 free += ['datum.values']
1008 else:
1009 print " datum.values = NULL;"
1010 print " for (size_t i = 0; i < %s; i++) {" % nVar
1011 print " " + type.key.assign_c_value_casting_away_const("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar, refTable=False)
1012 if type.value:
1013 print " " + type.value.assign_c_value_casting_away_const("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar, refTable=False)
1014 print " }"
1015 if type.value:
1016 valueType = type.value.toAtomicType()
1017 else:
1018 valueType = "OVSDB_TYPE_VOID"
1019 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
1020 type.key.toAtomicType(), valueType)
1021
1022 print""" ovsdb_idl_condition_add_clause(idl, &%(p)stable_%(tl)s,
1023 function,
1024 &%(s)s_col_%(c)s,
1025 &datum);\
1026 """ % {'tl': tableName.lower(),
1027 'T': tableName.upper(),
1028 'p': prefix,
1029 'P': prefix.upper(),
1030 's': structName,
1031 'S': structName.upper(),
1032 'c': columnName}
1033 for var in free:
1034 print " free(%s);" % var
1035 print "}"
1036
1037 print """\
1038 void
1039 %(s)s_add_clause_false(struct ovsdb_idl *idl)
1040 {
1041 struct ovsdb_datum datum;
1042
1043 ovsdb_datum_init_empty(&datum);
1044 ovsdb_idl_condition_add_clause(idl, &%(p)stable_%(tl)s, OVSDB_F_FALSE, NULL, &datum);
1045 }""" % {'s': structName,
1046 'tl': tableName.lower(),
1047 'p': prefix,
1048 'P': prefix.upper()}
1049
1050 print """void
1051 %(s)s_add_clause_true(struct ovsdb_idl *idl)
1052 {
1053 struct ovsdb_datum datum;
1054
1055 ovsdb_datum_init_empty(&datum);
1056 ovsdb_idl_condition_add_clause(idl, &%(p)stable_%(tl)s, OVSDB_F_TRUE, NULL, &datum);
1057 }""" % {'s': structName,
1058 'tl': tableName.lower(),
1059 'p': prefix,
1060 'P': prefix.upper()}
1061
1062 # Remove clause functions.
1063 for columnName, column in sorted_columns(table):
1064 type = column.type
1065
1066 comment, members = cMembers(prefix, tableName, columnName,
1067 column, True, refTable=False)
1068
1069 if type.is_smap():
1070 print comment
1071 print """void
1072 %(s)s_remove_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function, const struct smap *%(c)s)
1073 {
1074 struct ovsdb_datum datum;
1075
1076 ovs_assert(inited);
1077 if (%(c)s) {
1078 ovsdb_datum_from_smap(&datum, %(c)s);
1079 } else {
1080 ovsdb_datum_init_empty(&datum);
1081 }
1082
1083 ovsdb_idl_condition_remove_clause(idl, &%(p)stable_%(tl)s,
1084 function,
1085 &%(s)s_col_%(c)s,
1086 &datum);
1087
1088 ovsdb_datum_destroy(&datum, &%(s)s_col_%(c)s.type);
1089 }
1090 """ % {'tl': tableName.lower(),
1091 'p': prefix,
1092 'P': prefix.upper(),
1093 's': structName,
1094 'S': structName.upper(),
1095 'c': columnName}
1096 continue
1097
1098 keyVar = members[0]['name']
1099 nVar = None
1100 valueVar = None
1101 if type.value:
1102 valueVar = members[1]['name']
1103 if len(members) > 2:
1104 nVar = members[2]['name']
1105 else:
1106 if len(members) > 1:
1107 nVar = members[1]['name']
1108
1109 print comment
1110 print 'void'
1111 print '%(s)s_remove_clause_%(c)s(struct ovsdb_idl *idl, enum ovsdb_function function, %(args)s)' % \
1112 {'s': structName, 'c': columnName,
1113 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
1114 print "{"
1115 print " struct ovsdb_datum datum;"
1116 free = []
1117 if type.n_min == 1 and type.n_max == 1:
1118 print " union ovsdb_atom key;"
1119 if type.value:
1120 print " union ovsdb_atom value;"
1121 print
1122 print " ovs_assert(inited);"
1123 print " datum.n = 1;"
1124 print " datum.keys = &key;"
1125 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar, refTable=False)
1126 if type.value:
1127 print " datum.values = &value;"
1128 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar, refTable=False)
1129 else:
1130 print " datum.values = NULL;"
1131 elif type.is_optional_pointer():
1132 print " union ovsdb_atom key;"
1133 print
1134 print " ovs_assert(inited);"
1135 print " if (%s) {" % keyVar
1136 print " datum.n = 1;"
1137 print " datum.keys = &key;"
1138 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar, refTable=False)
1139 print " } else {"
1140 print " datum.n = 0;"
1141 print " datum.keys = NULL;"
1142 print " }"
1143 print " datum.values = NULL;"
1144 elif type.n_max == 1:
1145 print " union ovsdb_atom key;"
1146 print
1147 print " ovs_assert(inited);"
1148 print " if (%s) {" % nVar
1149 print " datum.n = 1;"
1150 print " datum.keys = &key;"
1151 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar, refTable=False)
1152 print " } else {"
1153 print " datum.n = 0;"
1154 print " datum.keys = NULL;"
1155 print " }"
1156 print " datum.values = NULL;"
1157 else:
1158 print " ovs_assert(inited);"
1159 print " datum.n = %s;" % nVar
1160 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
1161 free += ['datum.keys']
1162 if type.value:
1163 free += ['datum.values']
1164 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
1165 else:
1166 print " datum.values = NULL;"
1167 print " for (size_t i = 0; i < %s; i++) {" % nVar
1168 print " " + type.key.assign_c_value_casting_away_const("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar, refTable=False)
1169 if type.value:
1170 print " " + type.value.assign_c_value_casting_away_const("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar, refTable=False)
1171 print " }"
1172 if type.value:
1173 valueType = type.value.toAtomicType()
1174 else:
1175 valueType = "OVSDB_TYPE_VOID"
1176 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
1177 type.key.toAtomicType(), valueType)
1178
1179 print""" ovsdb_idl_condition_remove_clause(idl, &%(p)stable_%(tl)s,
1180 function,
1181 &%(s)s_col_%(c)s,
1182 &datum);\
1183 """ % {'tl': tableName.lower(),
1184 'p': prefix,
1185 'P': prefix.upper(),
1186 's': structName,
1187 'S': structName.upper(),
1188 'c': columnName}
1189 for var in free:
1190 print " free(%s);" % var
1191 print "}"
1192
1193 print """void
1194 %(s)s_remove_clause_false(struct ovsdb_idl *idl)
1195 {
1196 struct ovsdb_datum datum;
1197
1198 ovsdb_datum_init_empty(&datum);
1199 ovsdb_idl_condition_remove_clause(idl, &%(p)stable_%(tl)s, OVSDB_F_FALSE, NULL, &datum);
1200 }
1201
1202 void
1203 %(s)s_remove_clause_true(struct ovsdb_idl *idl)
1204 {
1205 struct ovsdb_datum datum;
1206
1207 ovsdb_datum_init_empty(&datum);
1208 ovsdb_idl_condition_remove_clause(idl, &%(p)stable_%(tl)s, OVSDB_F_TRUE, NULL, &datum);
1209 }""" % {'s': structName,
1210 'tl': tableName.lower(),
1211 'p': prefix,
1212 'P': prefix.upper(),}
1213
1214 # Table columns.
1215 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
1216 structName, structName.upper())
1217 print """
1218 static void\n%s_columns_init(void)
1219 {
1220 struct ovsdb_idl_column *c;\
1221 """ % structName
1222 for columnName, column in sorted_columns(table):
1223 cs = "%s_col_%s" % (structName, columnName)
1224 d = {'cs': cs, 'c': columnName, 's': structName}
1225 if column.mutable:
1226 mutable = "true"
1227 else:
1228 mutable = "false"
1229 print
1230 print " /* Initialize %(cs)s. */" % d
1231 print " c = &%(cs)s;" % d
1232 print " c->name = \"%(c)s\";" % d
1233 print column.type.cInitType(" ", "c->type")
1234 print " c->mutable = %s;" % mutable
1235 print " c->parse = %(s)s_parse_%(c)s;" % d
1236 print " c->unparse = %(s)s_unparse_%(c)s;" % d
1237 print "}"
1238
1239 # Table classes.
1240 print "\f"
1241 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
1242 for tableName, table in sorted(schema.tables.iteritems()):
1243 structName = "%s%s" % (prefix, tableName.lower())
1244 if table.is_root:
1245 is_root = "true"
1246 else:
1247 is_root = "false"
1248 print " {\"%s\", %s," % (tableName, is_root)
1249 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
1250 structName, structName)
1251 print " sizeof(struct %s), %s_init__}," % (structName, structName)
1252 print "};"
1253
1254 # IDL class.
1255 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
1256 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
1257 schema.name, prefix, prefix)
1258 print "};"
1259
1260 # global init function
1261 print """
1262 void
1263 %sinit(void)
1264 {
1265 if (inited) {
1266 return;
1267 }
1268 assert_single_threaded();
1269 inited = true;
1270 """ % prefix
1271 for tableName, table in sorted(schema.tables.iteritems()):
1272 structName = "%s%s" % (prefix, tableName.lower())
1273 print " %s_columns_init();" % structName
1274 print "}"
1275
1276 print """
1277 /* Return the schema version. The caller must not free the returned value. */
1278 const char *
1279 %sget_db_version(void)
1280 {
1281 return "%s";
1282 }
1283 """ % (prefix, schema.version)
1284
1285
1286
1287 def ovsdb_escape(string):
1288 def escape(match):
1289 c = match.group(0)
1290 if c == '\0':
1291 raise ovs.db.error.Error("strings may not contain null bytes")
1292 elif c == '\\':
1293 return '\\\\'
1294 elif c == '\n':
1295 return '\\n'
1296 elif c == '\r':
1297 return '\\r'
1298 elif c == '\t':
1299 return '\\t'
1300 elif c == '\b':
1301 return '\\b'
1302 elif c == '\a':
1303 return '\\a'
1304 else:
1305 return '\\x%02x' % ord(c)
1306 return re.sub(r'["\\\000-\037]', escape, string)
1307
1308 def usage():
1309 print """\
1310 %(argv0)s: ovsdb schema compiler
1311 usage: %(argv0)s [OPTIONS] COMMAND ARG...
1312
1313 The following commands are supported:
1314 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
1315 c-idl-header IDL print C header file for IDL
1316 c-idl-source IDL print C source file for IDL implementation
1317
1318 The following options are also available:
1319 -h, --help display this help message
1320 -V, --version display version information\
1321 """ % {'argv0': argv0}
1322 sys.exit(0)
1323
1324 if __name__ == "__main__":
1325 try:
1326 try:
1327 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
1328 ['directory',
1329 'help',
1330 'version'])
1331 except getopt.GetoptError, geo:
1332 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
1333 sys.exit(1)
1334
1335 for key, value in options:
1336 if key in ['-h', '--help']:
1337 usage()
1338 elif key in ['-V', '--version']:
1339 print "ovsdb-idlc (Open vSwitch) @VERSION@"
1340 elif key in ['-C', '--directory']:
1341 os.chdir(value)
1342 else:
1343 sys.exit(0)
1344
1345 optKeys = [key for key, value in options]
1346
1347 if not args:
1348 sys.stderr.write("%s: missing command argument "
1349 "(use --help for help)\n" % argv0)
1350 sys.exit(1)
1351
1352 commands = {"annotate": (annotateSchema, 2),
1353 "c-idl-header": (printCIDLHeader, 1),
1354 "c-idl-source": (printCIDLSource, 1)}
1355
1356 if not args[0] in commands:
1357 sys.stderr.write("%s: unknown command \"%s\" "
1358 "(use --help for help)\n" % (argv0, args[0]))
1359 sys.exit(1)
1360
1361 func, n_args = commands[args[0]]
1362 if len(args) - 1 != n_args:
1363 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
1364 "provided\n"
1365 % (argv0, args[0], n_args, len(args) - 1))
1366 sys.exit(1)
1367
1368 func(*args[1:])
1369 except ovs.db.error.Error, e:
1370 sys.stderr.write("%s: %s\n" % (argv0, e))
1371 sys.exit(1)
1372
1373 # Local variables:
1374 # mode: python
1375 # End: