Debian Codegraph @

doc/content/en/docs/1.11.4/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 a single Avro Protocol, and thus generates as its output a JSON-format Avro Protocol file with extension .avpr.
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 The `idl` tool can also process input to and from _stdin_ and _stdout_. See `idl --help` for full usage information.
48
49 A Maven plugin is also provided to compile .avdl files. To use it, add something like the following to your pom.xml:
50 ```xml
51 <build>
52 <plugins>
53 <plugin>
54 <groupId>org.apache.avro</groupId>
55 <artifactId>avro-maven-plugin</artifactId>
56 <executions>
57 <execution>
58 <goals>
59 <goal>idl-protocol</goal>
60 </goals>
61 </execution>
62 </executions>
63 </plugin>
64 </plugins>
65 </build>
66 ```
67
68 ## Defining a Protocol in Avro IDL
69 An Avro IDL file consists of exactly one protocol definition. The minimal protocol is defined by the following code:
70 ```java
71 protocol MyProtocol {
72 }
73 ```
74 This is equivalent to (and generates) the following JSON protocol definition:
75 ```json
76 {
77 "protocol" : "MyProtocol",
78 "types" : [ ],
79 "messages" : {
80 }
81 }
82 ```
83 The namespace of the protocol may be changed using the @namespace annotation:
84 ```java
85 @namespace("mynamespace")
86 protocol MyProtocol {
87 }
88 ```
89 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.
90
91 Protocols in Avro IDL can contain the following items:
92
93 * Imports of external protocol and schema files.
94 * Definitions of named schemata, including records, errors, enums, and fixeds.
95 * Definitions of RPC messages
96
97 ## Imports
98 Files may be imported in one of three formats:
99
100 * An IDL file may be imported with a statement like:
101
102 `import idl "foo.avdl";`
103
104 * A JSON protocol file may be imported with a statement like:
105
106 `import protocol "foo.avpr";`
107
108 * A JSON schema file may be imported with a statement like:
109
110 `import schema "foo.avsc";`
111
112 Messages and types in the imported file are added to this file's protocol.
113
114 Imported file names are resolved relative to the current IDL file.
115
116 ## Defining an Enumeration
117 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.
118
119 Example Writer Enum Definition
120 ```java
121 enum Shapes {
122 SQUARE, TRIANGLE, CIRCLE, OVAL
123 }
124 ```
125 Example Reader Enum Definition
126 ```java
127 enum Shapes {
128 SQUARE, TRIANGLE, CIRCLE
129 } = CIRCLE;
130 ```
131 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.
132
133 ## Defining a Fixed Length Field
134 Fixed fields are defined using the following syntax:
135 ```
136 fixed MD5(16);
137 ```
138 This example defines a fixed-length type called MD5 which contains 16 bytes.
139
140 ## Defining Records and Errors
141 Records are defined in Avro IDL using a syntax similar to a struct definition in C:
142 ```java
143 record Employee {
144 string name;
145 boolean active = true;
146 long salary;
147 }
148 ```
149 The above example defines a record with the name “Employee” with three fields.
150
151 To define an error, simply use the keyword _error_ instead of _record_. For example:
152 ```java
153 error Kaboom {
154 string explanation;
155 int result_code = -1;
156 }
157 ```
158 Each field in a record or error consists of a type and a name, optional property annotations and an optional default value.
159
160 A type reference in Avro IDL must be one of:
161
162 * A primitive type
163 * A logical type
164 * A named schema defined prior to this usage in the same Protocol
165 * A complex type (array, map, or union)
166
167 ### Primitive Types
168 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_.
169
170 ### Logical Types
171 Some of the logical types supported by Avro's JSON format are also supported by Avro IDL. The currently supported types are:
172
173 * _decimal_ (logical type [decimal]({{< relref "../specification#decimal" >}}))
174 * _date_ (logical type [date]({{< relref "../specification#date" >}}))
175 * _time_ms_ (logical type [time-millis]({{< relref "../specification#time-millisecond-precision" >}}))
176 * _timestamp_ms_ (logical type [timestamp-millis]({{< relref "../specification#timestamp-millisecond-precision" >}}))
177 * _uuid_ (logical type [uuid]({{< relref "../specification#uuid" >}}))
178
179 For example:
180 ```java
181 record Job {
182 string jobid;
183 date submitDate;
184 time_ms submitTime;
185 timestamp_ms finishTime;
186 decimal(9,2) finishRatio;
187 uuid pk = "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8";
188 }
189 ```
190
191 Logical types can also be specified via an annotation, which is useful for logical types for which a keyword does not exist:
192
193 ```java
194 record Job {
195 string jobid;
196 @logicalType("timestamp-micros")
197 long finishTime;
198 }
199 ```
200
201 ### References to Named Schemata
202 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:
203 ```java
204 record Card {
205 Suit suit; // refers to the enum Card defined above
206 int number;
207 }
208 ```
209
210 ### Default Values
211 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" >}}).
212
213 ### Complex Types
214
215 #### Arrays
216 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>>`.
217
218 #### Maps
219 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.
220
221 #### Unions
222 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:
223 ```java
224 record RecordWithUnion {
225 union { null, string } optionalString;
226 union { decimal(12, 6), float } number;
227 }
228 ```
229 Note that the same restrictions apply to Avro IDL unions as apply to unions defined in the JSON format; namely, a record 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.
230
231 Because it occurs so often, there is a special shorthand to denote a union of `null` with another type. In the following snippet, the first three fields have identical types:
232
233 ```java
234 record RecordWithUnion {
235 union { null, string } optionalString1 = null;
236 string? optionalString2 = null;
237 string? optionalString3; // No default value
238 string? optionalString4 = "something";
239 }
240 ```
241
242 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 in the example above, all fields are valid.
243
244 ## Defining RPC Messages
245 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:
246 ```java
247 int add(int foo, int bar = 0);
248 ```
249 Message arguments, like record fields, may specify default values.
250
251 To define a message with no response, you may use the alias _void_, equivalent to the Avro _null_ type:
252 ```java
253 void logMessage(string message);
254 ```
255 If you have previously defined an error type within the same protocol, you may declare that a message can throw this error using the syntax:
256 ```java
257 void goKaboom() throws Kaboom;
258 ```
259 To define a one-way message, use the keyword `oneway` after the parameter list, for example:
260 ```java
261 void fireAndForget(string message) oneway;
262 ```
263
264 ## Other Language Features
265
266 ### Comments
267 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.
268
269 Comments that begin with _/**_ are used as the documentation string for the type or field definition that follows the comment.
270
271 ### Escaping Identifiers
272 Occasionally, one will need to use a reserved language keyword as an identifier. In order to do so, backticks (`) may be used to escape the identifier. For example, to define a message with the literal name error, you may write:
273 ```java
274 void `error`();
275 ```
276 This syntax is allowed anywhere an identifier is expected.
277
278 ### Annotations for Ordering and Namespaces
279 Java-style annotations may be used to add additional properties to types and fields throughout Avro IDL.
280
281 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:
282 ```java
283 record MyRecord {
284 string @order("ascending") myAscendingSortField;
285 string @order("descending") myDescendingField;
286 string @order("ignore") myIgnoredField;
287 }
288 ```
289 A field's type (with the exception of type references) may also be preceded by annotations, e.g.:
290 ```java
291 record MyRecord {
292 @java-class("java.util.ArrayList") array<string> myStrings;
293 }
294 ```
295 This can be used to support java classes that can be serialized/deserialized via their `toString`/`String constructor`, e.g.:
296 ```java
297 record MyRecord {
298 @java-class("java.math.BigDecimal") string value;
299 @java-key-class("java.io.File") map<string> fileStates;
300 array<@java-class("java.math.BigDecimal") string> weights;
301 }
302 ```
303 Similarly, a `@namespace` annotation may be used to modify the namespace when defining a named schema. For example:
304 ```java
305 @namespace("org.apache.avro.firstNamespace")
306 protocol MyProto {
307 @namespace("org.apache.avro.someOtherNamespace")
308 record Foo {}
309
310 record Bar {}
311 }
312 ```
313 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.
314
315 Type and field aliases are specified with the `@aliases` annotation as follows:
316 ```java
317 @aliases(["org.old.OldRecord", "org.ancient.AncientRecord"])
318 record MyRecord {
319 string @aliases(["oldField", "ancientField"]) myNewField;
320 }
321 ```
322 Some annotations like those listed above are handled specially. All other annotations are added as properties to the protocol, message, schema or field.
323
324 ## Complete Example
325 The following is an example of an Avro IDL file that shows most of the above features:
326 ```java
327 /*
328 * Header with license information.
329 */
330
331 /**
332 * An example protocol in Avro IDL
333 */
334 @namespace("org.apache.avro.test")
335 protocol Simple {
336 /** Documentation for the enum type Kind */
337 @aliases(["org.foo.KindOf"])
338 enum Kind {
339 FOO,
340 BAR, // the bar enum value
341 BAZ
342 } = FOO; // For schema evolution purposes, unmatched values do not throw an error, but are resolved to FOO.
343
344 /** MD5 hash; good enough to avoid most collisions, and smaller than (for example) SHA256. */
345 fixed MD5(16);
346
347 record TestRecord {
348 /** Record name; has no intrinsic order */
349 string @order("ignore") name;
350
351 Kind @order("descending") kind;
352
353 MD5 hash;
354
355 /*
356 Note that 'null' is the first union type. Just like .avsc / .avpr files, the default value must be of the first union type.
357 */
358 union { null, MD5 } /** Optional field */ @aliases(["hash"]) nullableHash = null;
359
360 array<long> arrayOfLongs;
361 }
362
363 /** Errors are records that can be thrown from a method */
364 error TestError {
365 string message;
366 }
367
368 string hello(string greeting);
369 /** Return what was given. Demonstrates the use of backticks to name types/fields/messages/parameters after keywords */
370 TestRecord echo(TestRecord `record`);
371 int add(int arg1, int arg2);
372 bytes echoBytes(bytes data);
373 void `error`() throws TestError;
374 // The oneway keyword forces the method to return null.
375 void ping() oneway;
376 }
377 ```
378 Additional examples may be found in the Avro source tree under the `src/test/idl/input` directory.
379
380 ## IDE support
381
382 There are several editors and IDEs that support Avro IDL files, usually via plugins.
383
384 ### JetBrains
385
386 Apache Avro IDL Schema Support 203.1.2 was released in 9 December 2021.
387
388 Features:
389 * Syntax Highlighting
390 * Code Completion
391 * Code Formatting
392 * Error Highlighting
393 * Inspections & quick fixes
394 * JSON schemas for .avpr and .avsc files
395
396 It's available via the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/15728-apache-avro-idl-schema-support)
397 and on [GitHub](https://github.com/opwvhk/avro-schema-support).
398
399 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.
400
401 Only JetBrains Gateway does not support this plugin directly. But the backend (JetBrains) IDE that it connects to does.
402
403 ### Eclipse
404
405 Avroclipse 0.0.11 was released on 4 December 2019.
406
407 Features:
408 * Syntax Highlighting
409 * Error Highlighting
410 * Code Completion
411
412 It is available on the [Eclipse Marketplace](https://marketplace.eclipse.org/content/avroclipse)
413 and [GitHub](https://github.com/dvdkruk/avroclipse).
414
415 ### Visual Studio Code
416
417 avro-idl 0.5.0 was released on 16 June 2021. It provides syntax highlighting.
418
419 It is available on the [VisualStudio Marketplace](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.avro)
420 and [GitHub](https://github.com/Jason3S/vscode-avro-ext)
421
422 ### Atom.io
423
424 atom-language-avro 0.0.13 was released on 14 August 2015. It provides syntax highlighting.
425
426 It is available as [Atom.io package](https://atom.io/packages/atom-language-avro)
427 and [GitHub](https://github.com/jonesetc/atom-language-avro)
428
429 ### Vim
430
431 A `.avdl` detecting plugin by Gurpreet Atwal on [GitHub](https://github.com/gurpreetatwal/vim-avro) (Last change in December 2016)
432
433 [avro-idl.vim](https://github.com/apache/avro/blob/master/share/editors/avro-idl.vim) in the Avro repository `share/editors` directory (last change in September 2010)
434
435 Both provide syntax highlighting.