Debian Codegraph @

doc/content/en/docs/++version++/IDL Language/_index.md

raw
1 ---
2 title: "IDL Language"
3 linkTitle: "IDL Language"
4 weight: 201
5 aliases:
6 - /docs/current/idl-language/
7 ---
8
9 <!--
10
11 Licensed to the Apache Software Foundation (ASF) under one
12 or more contributor license agreements. See the NOTICE file
13 distributed with this work for additional information
14 regarding copyright ownership. The ASF licenses this file
15 to you under the Apache License, Version 2.0 (the
16 "License"); you may not use this file except in compliance
17 with the License. You may obtain a copy of the License at
18
19 https://www.apache.org/licenses/LICENSE-2.0
20
21 Unless required by applicable law or agreed to in writing,
22 software distributed under the License is distributed on an
23 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
24 KIND, either express or implied. See the License for the
25 specific language governing permissions and limitations
26 under the License.
27
28 -->
29
30 ## Introduction
31 This document defines Avro IDL, a higher-level language for authoring Avro schemata. Before reading this document, you should have familiarity with the concepts of schemata and protocols, as well as the various primitive and complex types available in Avro.
32
33 ## Overview
34
35 ### Purpose
36 The aim of the Avro IDL language is to enable developers to author schemata in a way that feels more similar to common programming languages like Java, C++, or Python. Additionally, the Avro IDL language may feel more familiar for those users who have previously used the interface description languages (IDLs) in other frameworks like Thrift, Protocol Buffers, or CORBA.
37
38 ### Usage
39 Each Avro IDL file defines either a single Avro Protocol, or an Avro Schema with supporting named schemata in a namespace. When parsed, it thus yields either a Protocol or a Schema. These can be respectively written to JSON-format Avro Protocol files with extension .avpr or JSON-format Avro Schema files with extension .avsc.
40
41 To convert a _.avdl_ file into a _.avpr_ file, it may be processed by the `idl` tool. For example:
42 ```shell
43 $ java -jar avro-tools.jar idl src/test/idl/input/namespaces.avdl /tmp/namespaces.avpr
44 $ head /tmp/namespaces.avpr
45 {
46 "protocol" : "TestNamespace",
47 "namespace" : "avro.test.protocol",
48 ```
49 To convert a _.avdl_ file into a _.avsc_ file, it may be processed by the `idl` tool too. For example:
50 ```shell
51 $ java -jar avro-tools.jar idl src/test/idl/input/schema_syntax_schema.avdl /tmp/schema_syntax.avsc
52 $ head /tmp/schema_syntax.avsc
53 {
54 "type": "array",
55 "items": {
56 "type": "record",
57 "name": "StatusUpdate",
58 ```
59 The `idl` tool can also process input to and from _stdin_ and _stdout_. See `idl --help` for full usage information.
60
61 A Maven plugin is also provided to compile .avdl files. To use it, add something like the following to your pom.xml:
62 ```xml
63 <build>
64 <plugins>
65 <plugin>
66 <groupId>org.apache.avro</groupId>
67 <artifactId>avro-maven-plugin</artifactId>
68 <executions>
69 <execution>
70 <goals>
71 <goal>idl</goal>
72 </goals>
73 </execution>
74 </executions>
75 </plugin>
76 </plugins>
77 </build>
78 ```
79
80 ## Defining a Schema in Avro IDL
81 An Avro IDL file consists of exactly one (main) schema definition. The minimal schema is defined by the following code:
82 ```java
83 schema int;
84 ```
85 This is equivalent to (and generates) the following JSON schema definition:
86 ```json
87 {
88 "type": "int"
89 }
90 ```
91 More complex schemata can also be defined, for example by adding named schemata like this:
92 ```java
93 namespace default.namespace.for.named.schemata;
94 schema Message;
95
96 record Message {
97 string? title = null;
98 string message;
99 }
100 ```
101 This is equivalent to (and generates) the following JSON schema definition:
102 ```json
103 {
104 "type" : "record",
105 "name" : "Message",
106 "namespace" : "default.namespace.for.named.schemata",
107 "fields" : [ {
108 "name" : "title",
109 "type" : [ "null", "string" ],
110 "default": null
111 }, {
112 "name" : "message",
113 "type" : "string"
114 } ]
115 }
116 ```
117 Schemata in Avro IDL can contain the following items:
118
119 * Imports of external protocol and schema files (only named schemata are imported).
120 * Definitions of named schemata, including records, errors, enums, and fixeds.
121
122 ## Defining a Protocol in Avro IDL
123 An Avro IDL file consists of exactly one protocol definition. The minimal protocol is defined by the following code:
124 ```java
125 protocol MyProtocol {
126 }
127 ```
128 This is equivalent to (and generates) the following JSON protocol definition:
129 ```json
130 {
131 "protocol" : "MyProtocol",
132 "types" : [ ],
133 "messages" : {
134 }
135 }
136 ```
137 The namespace of the protocol may be changed using the @namespace annotation:
138 ```java
139 @namespace("mynamespace")
140 protocol MyProtocol {
141 }
142 ```
143 This notation is used throughout Avro IDL as a way of specifying properties for the annotated element, as will be described later in this document.
144
145 Protocols in Avro IDL can contain the following items:
146
147 * Imports of external protocol and schema files.
148 * Definitions of named schemata, including records, errors, enums, and fixeds.
149 * Definitions of RPC messages
150
151 ## Imports
152 Files may be imported in one of three formats:
153
154 * An IDL file may be imported with a statement like:
155
156 `import idl "foo.avdl";`
157
158 * A JSON protocol file may be imported with a statement like:
159
160 `import protocol "foo.avpr";`
161
162 * A JSON schema file may be imported with a statement like:
163
164 `import schema "foo.avsc";`
165
166 When importing into an IDL schema file, only (named) types are imported into this file. When importing into an IDL protocol, messages are imported into the protocol as well.
167
168 Imported file names are resolved relative to the current IDL file.
169
170 ## Defining an Enumeration
171 Enums are defined in Avro IDL using a syntax similar to C or Java. An Avro Enum supports optional default values. In the case that a reader schema is unable to recognize a symbol written by the writer, the reader will fall back to using the defined default value. This default is only used when an incompatible symbol is read. It is not used if the enum field is missing.
172
173 Example Writer Enum Definition
174 ```java
175 enum Shapes {
176 SQUARE, TRIANGLE, CIRCLE, OVAL
177 }
178 ```
179 Example Reader Enum Definition
180 ```java
181 enum Shapes {
182 SQUARE, TRIANGLE, CIRCLE
183 } = CIRCLE;
184 ```
185 In the above example, the reader will use the default value of `CIRCLE` whenever reading data written with the `OVAL` symbol of the writer. Also note that, unlike the JSON format, anonymous enums cannot be defined.
186
187 ## Defining a Fixed Length Field
188 Fixed fields are defined using the following syntax:
189 ```
190 fixed MD5(16);
191 ```
192 This example defines a fixed-length type called MD5, which contains 16 bytes.
193
194 ## Defining Records and Errors
195 Records are defined in Avro IDL using a syntax similar to a struct definition in C:
196 ```java
197 record Employee {
198 string name;
199 boolean active = true;
200 long salary;
201 }
202 ```
203 The above example defines a record with the name “Employee” with three fields.
204
205 To define an error, simply use the keyword _error_ instead of _record_. For example:
206 ```java
207 error Kaboom {
208 string explanation;
209 int result_code = -1;
210 }
211 ```
212 Each field in a record or error consists of a type and a name, optional property annotations and an optional default value.
213
214 A type reference in Avro IDL must be one of:
215
216 * A primitive type
217 * A logical type
218 * A named schema (either defined or imported)
219 * A complex type (array, map, or union)
220
221 ### Primitive Types
222 The primitive types supported by Avro IDL are the same as those supported by Avro's JSON format. This list includes _int_, _long_, _string_, _boolean_, _float_, _double_, _null_, and _bytes_.
223
224 ### Logical Types
225 Some of the logical types supported by Avro's JSON format are directly supported by Avro IDL. The currently supported types are:
226
227 * _decimal_ (logical type [decimal]({{< relref "../specification#decimal" >}}))
228 * _date_ (logical type [date]({{< relref "../specification#date" >}}))
229 * _time_ms_ (logical type [time-millis]({{< relref "../specification#time-millisecond-precision" >}}))
230 * _timestamp_ms_ (logical type [timestamp-millis]({{< relref "../specification#timestamp-millisecond-precision" >}}))
231 * _local_timestamp_ms_ (logical type [local-timestamp-millis]({{< relref "../specification#local_timestamp_ms" >}}))
232 * _uuid_ (logical type [uuid]({{< relref "../specification#uuid" >}}))
233
234 For example:
235 ```java
236 record Job {
237 string jobid;
238 date submitDate;
239 time_ms submitTime;
240 timestamp_ms finishTime;
241 decimal(9,2) finishRatio;
242 uuid pk = "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8";
243 }
244 ```
245
246 Logical types can also be specified via an annotation, which is useful for logical types for which a keyword does not exist:
247
248 ```java
249 record Job {
250 string jobid;
251 @logicalType("timestamp-micros")
252 long finishTime;
253 }
254 ```
255
256 ### References to Named Schemata
257 If a named schema has already been defined in the same Avro IDL file, it may be referenced by name as if it were a primitive type:
258 ```java
259 record Card {
260 Suit suit; // refers to the enum Card defined above
261 int number;
262 }
263 ```
264
265 ### Default Values
266 Default values for fields may be optionally specified by using an equals sign after the field name followed by a JSON expression indicating the default value. This JSON is interpreted as described in the [spec]({{< relref "../specification#schema-record" >}}).
267
268 ### Complex Types
269
270 #### Arrays
271 Array types are written in a manner that will seem familiar to C++ or Java programmers. An array of any type t is denoted `array<t>`. For example, an array of strings is denoted `array<string>`, and a multidimensional array of Foo records would be `array<array<Foo>>`.
272
273 #### Maps
274 Map types are written similarly to array types. An array that contains values of type t is written `map<t>`. As in the JSON schema format, all maps contain `string`-type keys.
275
276 #### Unions
277 Union types are denoted as `union { typeA, typeB, typeC, ... }`. For example, this record contains a string field that is optional (unioned with null), and a field containing either a precise or a imprecise number:
278 ```java
279 record RecordWithUnion {
280 union { null, string } optionalString;
281 union { decimal(12, 6), float } number;
282 }
283 ```
284 Note that the same restrictions apply to Avro IDL unions as apply to unions defined in the JSON format; namely, a union may not contain multiple elements of the same type. Also, fields/parameters that use the union type and have a default parameter must specify a default value of the same type as the **first** union type.
285
286 Because it occurs so often, there is a special shorthand to denote a union of `null` with one other schema. The first three fields in the following snippet have identical schemata, as do the last two fields:
287
288 ```java
289 record RecordWithUnion {
290 union { null, string } optionalString1 = null;
291 string? optionalString2 = null;
292 string? optionalString3; // No default value
293
294 union { string, null } optionalString4 = "something";
295 string? optionalString5 = "something else";
296 }
297 ```
298
299 Note that unlike explicit unions, the position of the `null` type is fluid; it will be the first or last type depending on the default value (if any). So all fields are valid in the example above.
300
301 ## Defining RPC Messages
302 The syntax to define an RPC message within a Avro IDL protocol is similar to the syntax for a method declaration within a C header file or a Java interface. To define an RPC message _add_ which takes two arguments named _foo_ and _bar_, returning an _int_, simply include the following definition within the protocol:
303 ```java
304 int add(int foo, int bar = 0);
305 ```
306 Message arguments, like record fields, may specify default values.
307
308 To define a message with no response, you may use the alias _void_, equivalent to the Avro _null_ type:
309 ```java
310 void logMessage(string message);
311 ```
312 If you have defined or imported an error type within the same protocol, you may declare that a message can throw this error using the syntax:
313 ```java
314 void goKaboom() throws Kaboom;
315 ```
316 To define a one-way message, use the keyword `oneway` after the parameter list, for example:
317 ```java
318 void fireAndForget(string message) oneway;
319 ```
320
321 ## Other Language Features
322
323 ### Comments and documentation
324 All Java-style comments are supported within a Avro IDL file. Any text following _//_ on a line is ignored, as is any text between _/*_ and _*/_, possibly spanning multiple lines.
325
326 Comments that begin with _/**_ are used as the documentation string for the type or field definition that follows the comment.
327
328 ### Escaping Identifiers
329 Occasionally, one may want to distinguish between identifiers and languages keywords. In order to do so, backticks (`) may be used to escape
330 the identifier. For example, to define a message with the literal name error, you may write:
331 ```java
332 void `error`();
333 ```
334 This syntax is allowed anywhere an identifier is expected.
335
336 ### Annotations for Ordering and Namespaces
337 Java-style annotations may be used to add additional properties to types and fields throughout Avro IDL. These can be custom properties, or
338 special properties as used in the JSON-format Avro Schema and Protocol files.
339
340 For example, to specify the sort order of a field within a record, one may use the `@order` annotation before the field name as follows:
341 ```java
342 record MyRecord {
343 string @order("ascending") myAscendingSortField;
344 string @order("descending") myDescendingField;
345 string @order("ignore") myIgnoredField;
346 }
347 ```
348 A field's type (with the exception of type references) may also be preceded by annotations, e.g.:
349 ```java
350 record MyRecord {
351 @java-class("java.util.ArrayList") array<string> myStrings;
352 }
353 ```
354 This can be used to support java classes that can be serialized/deserialized via their `toString`/`String constructor`, e.g.:
355 ```java
356 record MyRecord {
357 @java-class("java.math.BigDecimal") string value;
358 @java-key-class("java.io.File") map<string> fileStates;
359 array<@java-class("java.math.BigDecimal") string> weights;
360 }
361 ```
362 Similarly, a `@namespace` annotation may be used to modify the namespace when defining a named schema. For example:
363 ```java
364 @namespace("org.apache.avro.firstNamespace")
365 protocol MyProto {
366 @namespace("org.apache.avro.someOtherNamespace")
367 record Foo {}
368
369 record Bar {}
370 }
371 ```
372 will define a protocol in the _firstNamespace_ namespace. The record _Foo_ will be defined in _someOtherNamespace_ and _Bar_ will be defined in _firstNamespace_ as it inherits its default from its container.
373
374 Type and field aliases are specified with the `@aliases` annotation as follows:
375 ```java
376 @aliases(["org.old.OldRecord", "org.ancient.AncientRecord"])
377 record MyRecord {
378 string @aliases(["oldField", "ancientField"]) myNewField;
379 }
380 ```
381 Some annotations like those listed above are handled specially. All other annotations are added as properties to the protocol, message, schema or field. You can use any identifier or series of identifiers separated by dots and/or dashes as property name.
382
383 ## Complete Example
384 The following is an example of two Avro IDL files that together show most of the above features:
385
386 ### schema.avdl
387 ```java
388 /*
389 * Header with license information.
390 */
391 // Optional default namespace (if absent, the default namespace is the null namespace).
392 namespace org.apache.avro.test;
393 // Optional main schema definition; if used, the IDL file is equivalent to a .avsc file.
394 schema TestRecord;
395
396 /** Documentation for the enum type Kind */
397 @aliases(["org.foo.KindOf"])
398 enum Kind {
399 FOO,
400 BAR, // the bar enum value
401 BAZ
402 } = FOO; // For schema evolution purposes, unmatched values do not throw an error, but are resolved to FOO.
403
404 /** MD5 hash; good enough to avoid most collisions, and smaller than (for example) SHA256. */
405 fixed MD5(16);
406
407 record TestRecord {
408 /** Record name; has no intrinsic order */
409 string @order("ignore") name;
410
411 Kind @order("descending") kind;
412
413 MD5 hash;
414
415 /*
416 Note that 'null' is the first union type. Just like .avsc / .avpr files, the default value must be of the first union type.
417 */
418 union { null, MD5 } /** Optional field */ @aliases(["hash"]) nullableHash = null;
419 // Shorthand syntax; the null in this union is placed based on the default value (or first is there's no default).
420 MD5? anotherNullableHash = null;
421
422 array<long> arrayOfLongs;
423 }
424 ```
425
426 ### protocol.avdl
427 ```java
428 /*
429 * Header with license information.
430 */
431
432 /**
433 * An example protocol in Avro IDL
434 */
435 @namespace("org.apache.avro.test")
436 protocol Simple {
437 // Import the example file above
438 import idl "schema.avdl";
439
440 /** Errors are records that can be thrown from a method */
441 error TestError {
442 string message;
443 }
444
445 string hello(string greeting);
446 /** Return what was given. Demonstrates the use of backticks to name types/fields/messages/parameters after keywords */
447 TestRecord echo(TestRecord `record`);
448 int add(int arg1, int arg2);
449 bytes echoBytes(bytes data);
450 void `error`() throws TestError;
451 // The oneway keyword forces the method to return null.
452 void ping() oneway;
453 }
454 ```
455
456 Additional examples may be found in the Avro source tree under the `src/test/idl/input` directory.