Debian Codegraph @

doc/content/en/docs/1.12.0/IDL Language/_index.md

raw
1 ---
2 title: "IDL Language"
3 linkTitle: "IDL Language"
4 weight: 201
5 ---
6
7 <!--
8
9 Licensed to the Apache Software Foundation (ASF) under one
10 or more contributor license agreements. See the NOTICE file
11 distributed with this work for additional information
12 regarding copyright ownership. The ASF licenses this file
13 to you under the Apache License, Version 2.0 (the
14 "License"); you may not use this file except in compliance
15 with the License. You may obtain a copy of the License at
16
17 https://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing,
20 software distributed under the License is distributed on an
21 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
22 KIND, either express or implied. See the License for the
23 specific language governing permissions and limitations
24 under the License.
25
26 -->
27
28 ## Introduction
29 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.
30
31 ## Overview
32
33 ### Purpose
34 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.
35
36 ### Usage
37 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.
38
39 To convert a _.avdl_ file into a _.avpr_ file, it may be processed by the `idl` tool. For example:
40 ```shell
41 $ java -jar avro-tools.jar idl src/test/idl/input/namespaces.avdl /tmp/namespaces.avpr
42 $ head /tmp/namespaces.avpr
43 {
44 "protocol" : "TestNamespace",
45 "namespace" : "avro.test.protocol",
46 ```
47 To convert a _.avdl_ file into a _.avsc_ file, it may be processed by the `idl` tool too. For example:
48 ```shell
49 $ java -jar avro-tools.jar idl src/test/idl/input/schema_syntax_schema.avdl /tmp/schema_syntax.avsc
50 $ head /tmp/schema_syntax.avsc
51 {
52 "type": "array",
53 "items": {
54 "type": "record",
55 "name": "StatusUpdate",
56 ```
57 The `idl` tool can also process input to and from _stdin_ and _stdout_. See `idl --help` for full usage information.
58
59 A Maven plugin is also provided to compile .avdl files. To use it, add something like the following to your pom.xml:
60 ```xml
61 <build>
62 <plugins>
63 <plugin>
64 <groupId>org.apache.avro</groupId>
65 <artifactId>avro-maven-plugin</artifactId>
66 <executions>
67 <execution>
68 <goals>
69 <goal>idl</goal>
70 </goals>
71 </execution>
72 </executions>
73 </plugin>
74 </plugins>
75 </build>
76 ```
77
78 ## Defining a Schema in Avro IDL
79 An Avro IDL file consists of exactly one (main) schema definition. The minimal schema is defined by the following code:
80 ```java
81 schema int;
82 ```
83 This is equivalent to (and generates) the following JSON schema definition:
84 ```json
85 {
86 "type": "int"
87 }
88 ```
89 More complex schemata can also be defined, for example by adding named schemata like this:
90 ```java
91 namespace default.namespace.for.named.schemata;
92 schema Message;
93
94 record Message {
95 string? title = null;
96 string message;
97 }
98 ```
99 This is equivalent to (and generates) the following JSON schema definition:
100 ```json
101 {
102 "type" : "record",
103 "name" : "Message",
104 "namespace" : "default.namespace.for.named.schemata",
105 "fields" : [ {
106 "name" : "title",
107 "type" : [ "null", "string" ],
108 "default": null
109 }, {
110 "name" : "message",
111 "type" : "string"
112 } ]
113 }
114 ```
115 Schemata in Avro IDL can contain the following items:
116
117 * Imports of external protocol and schema files (only named schemata are imported).
118 * Definitions of named schemata, including records, errors, enums, and fixeds.
119
120 ## Defining a Protocol in Avro IDL
121 An Avro IDL file consists of exactly one protocol definition. The minimal protocol is defined by the following code:
122 ```java
123 protocol MyProtocol {
124 }
125 ```
126 This is equivalent to (and generates) the following JSON protocol definition:
127 ```json
128 {
129 "protocol" : "MyProtocol",
130 "types" : [ ],
131 "messages" : {
132 }
133 }
134 ```
135 The namespace of the protocol may be changed using the @namespace annotation:
136 ```java
137 @namespace("mynamespace")
138 protocol MyProtocol {
139 }
140 ```
141 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.
142
143 Protocols in Avro IDL can contain the following items:
144
145 * Imports of external protocol and schema files.
146 * Definitions of named schemata, including records, errors, enums, and fixeds.
147 * Definitions of RPC messages
148
149 ## Imports
150 Files may be imported in one of three formats:
151
152 * An IDL file may be imported with a statement like:
153
154 `import idl "foo.avdl";`
155
156 * A JSON protocol file may be imported with a statement like:
157
158 `import protocol "foo.avpr";`
159
160 * A JSON schema file may be imported with a statement like:
161
162 `import schema "foo.avsc";`
163
164 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.
165
166 Imported file names are resolved relative to the current IDL file.
167
168 ## Defining an Enumeration
169 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.
170
171 Example Writer Enum Definition
172 ```java
173 enum Shapes {
174 SQUARE, TRIANGLE, CIRCLE, OVAL
175 }
176 ```
177 Example Reader Enum Definition
178 ```java
179 enum Shapes {
180 SQUARE, TRIANGLE, CIRCLE
181 } = CIRCLE;
182 ```
183 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.
184
185 ## Defining a Fixed Length Field
186 Fixed fields are defined using the following syntax:
187 ```
188 fixed MD5(16);
189 ```
190 This example defines a fixed-length type called MD5, which contains 16 bytes.
191
192 ## Defining Records and Errors
193 Records are defined in Avro IDL using a syntax similar to a struct definition in C:
194 ```java
195 record Employee {
196 string name;
197 boolean active = true;
198 long salary;
199 }
200 ```
201 The above example defines a record with the name “Employee” with three fields.
202
203 To define an error, simply use the keyword _error_ instead of _record_. For example:
204 ```java
205 error Kaboom {
206 string explanation;
207 int result_code = -1;
208 }
209 ```
210 Each field in a record or error consists of a type and a name, optional property annotations and an optional default value.
211
212 A type reference in Avro IDL must be one of:
213
214 * A primitive type
215 * A logical type
216 * A named schema (either defined or imported)
217 * A complex type (array, map, or union)
218
219 ### Primitive Types
220 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_.
221
222 ### Logical Types
223 Some of the logical types supported by Avro's JSON format are directly supported by Avro IDL. The currently supported types are:
224
225 * _decimal_ (logical type [decimal]({{< relref "../specification#decimal" >}}))
226 * _date_ (logical type [date]({{< relref "../specification#date" >}}))
227 * _time_ms_ (logical type [time-millis]({{< relref "../specification#time-millisecond-precision" >}}))
228 * _timestamp_ms_ (logical type [timestamp-millis]({{< relref "../specification#timestamp-millisecond-precision" >}}))
229 * _local_timestamp_ms_ (logical type [local-timestamp-millis]({{< relref "../specification#local_timestamp_ms" >}}))
230 * _uuid_ (logical type [uuid]({{< relref "../specification#uuid" >}}))
231
232 For example:
233 ```java
234 record Job {
235 string jobid;
236 date submitDate;
237 time_ms submitTime;
238 timestamp_ms finishTime;
239 decimal(9,2) finishRatio;
240 uuid pk = "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8";
241 }
242 ```
243
244 Logical types can also be specified via an annotation, which is useful for logical types for which a keyword does not exist:
245
246 ```java
247 record Job {
248 string jobid;
249 @logicalType("timestamp-micros")
250 long finishTime;
251 }
252 ```
253
254 ### References to Named Schemata
255 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:
256 ```java
257 record Card {
258 Suit suit; // refers to the enum Card defined above
259 int number;
260 }
261 ```
262
263 ### Default Values
264 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" >}}).
265
266 ### Complex Types
267
268 #### Arrays
269 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>>`.
270
271 #### Maps
272 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.
273
274 #### Unions
275 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:
276 ```java
277 record RecordWithUnion {
278 union { null, string } optionalString;
279 union { decimal(12, 6), float } number;
280 }
281 ```
282 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.
283
284 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:
285
286 ```java
287 record RecordWithUnion {
288 union { null, string } optionalString1 = null;
289 string? optionalString2 = null;
290 string? optionalString3; // No default value
291
292 union { string, null } optionalString4 = "something";
293 string? optionalString5 = "something else";
294 }
295 ```
296
297 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.
298
299 ## Defining RPC Messages
300 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:
301 ```java
302 int add(int foo, int bar = 0);
303 ```
304 Message arguments, like record fields, may specify default values.
305
306 To define a message with no response, you may use the alias _void_, equivalent to the Avro _null_ type:
307 ```java
308 void logMessage(string message);
309 ```
310 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:
311 ```java
312 void goKaboom() throws Kaboom;
313 ```
314 To define a one-way message, use the keyword `oneway` after the parameter list, for example:
315 ```java
316 void fireAndForget(string message) oneway;
317 ```
318
319 ## Other Language Features
320
321 ### Comments and documentation
322 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.
323
324 Comments that begin with _/**_ are used as the documentation string for the type or field definition that follows the comment.
325
326 ### Escaping Identifiers
327 Occasionally, one may want to distinguish between identifiers and languages keywords. In order to do so, backticks (`) may be used to escape
328 the identifier. For example, to define a message with the literal name error, you may write:
329 ```java
330 void `error`();
331 ```
332 This syntax is allowed anywhere an identifier is expected.
333
334 ### Annotations for Ordering and Namespaces
335 Java-style annotations may be used to add additional properties to types and fields throughout Avro IDL. These can be custom properties, or
336 special properties as used in the JSON-format Avro Schema and Protocol files.
337
338 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:
339 ```java
340 record MyRecord {
341 string @order("ascending") myAscendingSortField;
342 string @order("descending") myDescendingField;
343 string @order("ignore") myIgnoredField;
344 }
345 ```
346 A field's type (with the exception of type references) may also be preceded by annotations, e.g.:
347 ```java
348 record MyRecord {
349 @java-class("java.util.ArrayList") array<string> myStrings;
350 }
351 ```
352 This can be used to support java classes that can be serialized/deserialized via their `toString`/`String constructor`, e.g.:
353 ```java
354 record MyRecord {
355 @java-class("java.math.BigDecimal") string value;
356 @java-key-class("java.io.File") map<string> fileStates;
357 array<@java-class("java.math.BigDecimal") string> weights;
358 }
359 ```
360 Similarly, a `@namespace` annotation may be used to modify the namespace when defining a named schema. For example:
361 ```java
362 @namespace("org.apache.avro.firstNamespace")
363 protocol MyProto {
364 @namespace("org.apache.avro.someOtherNamespace")
365 record Foo {}
366
367 record Bar {}
368 }
369 ```
370 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.
371
372 Type and field aliases are specified with the `@aliases` annotation as follows:
373 ```java
374 @aliases(["org.old.OldRecord", "org.ancient.AncientRecord"])
375 record MyRecord {
376 string @aliases(["oldField", "ancientField"]) myNewField;
377 }
378 ```
379 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.
380
381 ## Complete Example
382 The following is an example of two Avro IDL files that together show most of the above features:
383
384 ### schema.avdl
385 ```java
386 /*
387 * Header with license information.
388 */
389 // Optional default namespace (if absent, the default namespace is the null namespace).
390 namespace org.apache.avro.test;
391 // Optional main schema definition; if used, the IDL file is equivalent to a .avsc file.
392 schema TestRecord;
393
394 /** Documentation for the enum type Kind */
395 @aliases(["org.foo.KindOf"])
396 enum Kind {
397 FOO,
398 BAR, // the bar enum value
399 BAZ
400 } = FOO; // For schema evolution purposes, unmatched values do not throw an error, but are resolved to FOO.
401
402 /** MD5 hash; good enough to avoid most collisions, and smaller than (for example) SHA256. */
403 fixed MD5(16);
404
405 record TestRecord {
406 /** Record name; has no intrinsic order */
407 string @order("ignore") name;
408
409 Kind @order("descending") kind;
410
411 MD5 hash;
412
413 /*
414 Note that 'null' is the first union type. Just like .avsc / .avpr files, the default value must be of the first union type.
415 */
416 union { null, MD5 } /** Optional field */ @aliases(["hash"]) nullableHash = null;
417 // Shorthand syntax; the null in this union is placed based on the default value (or first is there's no default).
418 MD5? anotherNullableHash = null;
419
420 array<long> arrayOfLongs;
421 }
422 ```
423
424 ### protocol.avdl
425 ```java
426 /*
427 * Header with license information.
428 */
429
430 /**
431 * An example protocol in Avro IDL
432 */
433 @namespace("org.apache.avro.test")
434 protocol Simple {
435 // Import the example file above
436 import idl "schema.avdl";
437
438 /** Errors are records that can be thrown from a method */
439 error TestError {
440 string message;
441 }
442
443 string hello(string greeting);
444 /** Return what was given. Demonstrates the use of backticks to name types/fields/messages/parameters after keywords */
445 TestRecord echo(TestRecord `record`);
446 int add(int arg1, int arg2);
447 bytes echoBytes(bytes data);
448 void `error`() throws TestError;
449 // The oneway keyword forces the method to return null.
450 void ping() oneway;
451 }
452 ```
453
454 Additional examples may be found in the Avro source tree under the `src/test/idl/input` directory.
455
456 ## IDE support
457
458 There are several editors and IDEs that support Avro IDL files, usually via plugins.
459
460 ### JetBrains
461
462 Apache Avro IDL Schema Support 203.1.2 was released in 9 December 2021.
463
464 Features:
465 * Syntax Highlighting
466 * Code Completion
467 * Code Formatting
468 * Error Highlighting
469 * Inspections & quick fixes
470 * JSON schemas for .avpr and .avsc files
471
472 It's available via the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/15728-apache-avro-idl-schema-support)
473 and on [GitHub](https://github.com/opwvhk/avro-schema-support).
474
475 The plugin supports almost the all JetBrains products: IntelliJ IDEA, PyCharm, WebStorm, Android Studio, AppCode, GoLand, Rider, CLion, RubyMine, PhpStorm, DataGrip, DataSpell, MPS, Code With Me Guest and JetBrains Client.
476
477 Only JetBrains Gateway does not support this plugin directly. But the backend (JetBrains) IDE that it connects to does.
478
479 ### Eclipse
480
481 Avroclipse 0.0.11 was released on 4 December 2019.
482
483 Features:
484 * Syntax Highlighting
485 * Error Highlighting
486 * Code Completion
487
488 It is available on the [Eclipse Marketplace](https://marketplace.eclipse.org/content/avroclipse)
489 and [GitHub](https://github.com/dvdkruk/avroclipse).
490
491 ### Visual Studio Code
492
493 avro-idl 0.5.0 was released on 16 June 2021. It provides syntax highlighting.
494
495 It is available on the [VisualStudio Marketplace](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.avro)
496 and [GitHub](https://github.com/Jason3S/vscode-avro-ext)
497
498 ### Atom.io
499
500 atom-language-avro 0.0.13 was released on 14 August 2015. It provides syntax highlighting.
501
502 It is available as [Atom.io package](https://atom.io/packages/atom-language-avro)
503 and [GitHub](https://github.com/jonesetc/atom-language-avro)
504
505 ### Vim
506
507 A `.avdl` detecting plugin by Gurpreet Atwal on [GitHub](https://github.com/gurpreetatwal/vim-avro) (Last change in December 2016)
508
509 [avro-idl.vim](https://github.com/apache/avro/blob/main/share/editors/avro-idl.vim) in the Avro repository `share/editors` directory (last change in September 2010)
510
511 Both provide syntax highlighting.