Debian Codegraph @

petl/io/avro.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, division, print_function
3
4 import sys
5 import math
6 from collections import OrderedDict
7 from datetime import datetime, date, time
8 from decimal import Decimal
9
10 from petl.compat import izip_longest, text_type, string_types, PY3
11 from petl.io.sources import read_source_from_arg, write_source_from_arg
12 from petl.transform.headers import skip, setheader
13 from petl.util.base import Table, dicts, fieldnames, iterpeek, wrap
14
15 # region API
16
17
18 def fromavro(source, limit=None, skips=0, **avro_args):
19 """Extract a table from the records of a avro file.
20
21 The `source` argument (string or file-like or fastavro.reader) can either
22 be the path of the file, a file-like input stream or a instance from
23 fastavro.reader.
24
25 The `limit` and `skip` arguments can be used to limit the range of rows
26 to extract.
27
28 The `sample` argument (int, optional) defines how many rows are inspected
29 for discovering the field types and building a schema for the avro file
30 when the `schema` argument is not passed.
31
32 The rows fields read from file can have scalar values like int, string,
33 float, datetime, date and decimal but can also have compound types like
34 enum, :ref:`array <array_schema>`, map, union and record.
35 The fields types can also have recursive structures defined
36 in :ref:`complex schemas <complex_schema>`.
37
38 Also types with :ref:`logical types <logical_schema>` types are read and
39 translated to coresponding python types: long timestamp-millis and
40 long timestamp-micros: datetime.datetime, int date: datetime.date,
41 bytes decimal and fixed decimal: Decimal, int time-millis and
42 long time-micros: datetime.time.
43
44 Example usage for reading files::
45
46 >>> # set up a Avro file to demonstrate with
47 ...
48 >>> schema1 = {
49 ... 'doc': 'Some people records.',
50 ... 'name': 'People',
51 ... 'namespace': 'test',
52 ... 'type': 'record',
53 ... 'fields': [
54 ... {'name': 'name', 'type': 'string'},
55 ... {'name': 'friends', 'type': 'int'},
56 ... {'name': 'age', 'type': 'int'},
57 ... ]
58 ... }
59 ...
60 >>> records1 = [
61 ... {'name': 'Bob', 'friends': 42, 'age': 33},
62 ... {'name': 'Jim', 'friends': 13, 'age': 69},
63 ... {'name': 'Joe', 'friends': 86, 'age': 17},
64 ... {'name': 'Ted', 'friends': 23, 'age': 51}
65 ... ]
66 ...
67 >>> import fastavro
68 >>> parsed_schema1 = fastavro.parse_schema(schema1)
69 >>> with open('example.file1.avro', 'wb') as f1:
70 ... fastavro.writer(f1, parsed_schema1, records1)
71 ...
72 >>> # now demonstrate the use of fromavro()
73 >>> import petl as etl
74 >>> tbl1 = etl.fromavro('example.file1.avro')
75 >>> tbl1
76 +-------+---------+-----+
77 | name | friends | age |
78 +=======+=========+=====+
79 | 'Bob' | 42 | 33 |
80 +-------+---------+-----+
81 | 'Jim' | 13 | 69 |
82 +-------+---------+-----+
83 | 'Joe' | 86 | 17 |
84 +-------+---------+-----+
85 | 'Ted' | 23 | 51 |
86 +-------+---------+-----+
87
88 .. versionadded:: 1.4.0
89
90 """
91
92 source2 = read_source_from_arg(source)
93 return AvroView(source=source2,
94 limit=limit,
95 skips=skips,
96 **avro_args)
97
98
99 def toavro(table, target, schema=None, sample=9,
100 codec='deflate', compression_level=None, **avro_args):
101 """
102 Write the table into a new avro file according to schema passed.
103
104 This method assume that each column has values with the same type
105 for all rows of the source `table`.
106
107 `Apache Avro`_ is a data
108 serialization framework. It is used in data serialization (especially in
109 Hadoop ecosystem), for dataexchange for databases (Redshift) and RPC
110 protocols (like in Kafka). It has libraries to support many languages and
111 generally is faster and safer than text formats like Json, XML or CSV.
112
113 The `target` argument is the file path for creating the avro file.
114 Note that if a file already exists at the given location, it will be
115 overwritten.
116
117 The `schema` argument (dict) defines the rows field structure of the file.
118 Check fastavro `documentation`_ and Avro schema `reference`_ for details.
119
120 The `sample` argument (int, optional) defines how many rows are inspected
121 for discovering the field types and building a schema for the avro file
122 when the `schema` argument is not passed.
123
124 The `codec` argument (string, optional) sets the compression codec used to
125 shrink data in the file. It can be 'null', 'deflate' (default), 'bzip2' or
126 'snappy', 'zstandard', 'lz4', 'xz' (if installed)
127
128 The `compression_level` argument (int, optional) sets the level of
129 compression to use with the specified codec (if the codec supports it)
130
131 Additionally there are support for passing extra options in the
132 argument `**avro_args` that are fowarded directly to fastavro. Check the
133 fastavro `documentation`_ for reference.
134
135 The avro file format preserves type information, i.e., reading and writing
136 is round-trippable for tables with non-string data values. However the
137 conversion from Python value types to avro fields is not perfect. Use the
138 `schema` argument to define proper type to the conversion.
139
140 The following avro types are supported by the schema: null, boolean,
141 string, int, long, float, double, bytes, fixed, enum,
142 :ref:`array <array_schema>`, map, union, record, and recursive types
143 defined in :ref:`complex schemas <complex_schema>`.
144
145 Also :ref:`logical types <logical_schema>` are supported and translated to
146 coresponding python types: long timestamp-millis, long timestamp-micros, int date,
147 bytes decimal, fixed decimal, string uuid, int time-millis, long time-micros.
148
149 Example usage for writing files::
150
151 >>> # set up a Avro file to demonstrate with
152 >>> table2 = [['name', 'friends', 'age'],
153 ... ['Bob', 42, 33],
154 ... ['Jim', 13, 69],
155 ... ['Joe', 86, 17],
156 ... ['Ted', 23, 51]]
157 ...
158 >>> schema2 = {
159 ... 'doc': 'Some people records.',
160 ... 'name': 'People',
161 ... 'namespace': 'test',
162 ... 'type': 'record',
163 ... 'fields': [
164 ... {'name': 'name', 'type': 'string'},
165 ... {'name': 'friends', 'type': 'int'},
166 ... {'name': 'age', 'type': 'int'},
167 ... ]
168 ... }
169 ...
170 >>> # now demonstrate what writing with toavro()
171 >>> import petl as etl
172 >>> etl.toavro(table2, 'example.file2.avro', schema=schema2)
173 ...
174 >>> # this was what was saved above
175 >>> tbl2 = etl.fromavro('example.file2.avro')
176 >>> tbl2
177 +-------+---------+-----+
178 | name | friends | age |
179 +=======+=========+=====+
180 | 'Bob' | 42 | 33 |
181 +-------+---------+-----+
182 | 'Jim' | 13 | 69 |
183 +-------+---------+-----+
184 | 'Joe' | 86 | 17 |
185 +-------+---------+-----+
186 | 'Ted' | 23 | 51 |
187 +-------+---------+-----+
188
189 .. versionadded:: 1.4.0
190
191 .. _Apache Avro: https://avro.apache.org/docs/current/spec.html
192 .. _reference: https://avro.apache.org/docs/current/spec.html#schemas
193 .. _documentation : https://fastavro.readthedocs.io/en/latest/writer.html
194
195 """
196 _write_toavro(table,
197 target=target,
198 mode='wb',
199 schema=schema,
200 sample=sample,
201 codec=codec,
202 compression_level=compression_level,
203 **avro_args)
204
205
206 def appendavro(table, target, schema=None, sample=9, **avro_args):
207 """
208 Append rows into a avro existing avro file or create a new one.
209
210 The `target` argument can be either an existing avro file or the file
211 path for creating new one.
212
213 The `schema` argument is checked against the schema of the existing file.
214 So it must be the same schema as used by `toavro()` or the schema of the
215 existing file.
216
217 The `sample` argument (int, optional) defines how many rows are inspected
218 for discovering the field types and building a schema for the avro file
219 when the `schema` argument is not passed.
220
221 Additionally there are support for passing extra options in the
222 argument `**avro_args` that are fowarded directly to fastavro. Check the
223 fastavro documentation for reference.
224
225 See :meth:`petl.io.avro.toavro` method for more information and examples.
226
227 .. versionadded:: 1.4.0
228
229 """
230 _write_toavro(table,
231 target=target,
232 mode='a+b',
233 schema=schema,
234 sample=sample,
235 **avro_args)
236
237 # endregion API
238
239 # region Implementation
240
241
242 class AvroView(Table):
243 '''Read rows from avro file with their types and logical types'''
244
245 def __init__(self, source, limit, skips, **avro_args):
246 self.source = source
247 self.limit = limit
248 self.skip = skips
249 self.avro_args = avro_args
250 self.avro_schema = None
251
252 def get_avro_schema(self):
253 '''gets the schema stored in avro file header'''
254 return self.avro_schema
255
256 def __iter__(self):
257 with self.source.open('rb') as source_file:
258 avro_reader = self._open_reader(source_file)
259 header = self._decode_schema(avro_reader)
260 yield header
261 for row in self._read_rows_from(avro_reader, header):
262 yield row
263
264 def _open_reader(self, source_file):
265 '''This could raise a error when the file is corrupt or is not avro'''
266 # delay the import of fastavro for not breaking when unused
267 import fastavro
268 avro_reader = fastavro.reader(source_file, **self.avro_args)
269 return avro_reader
270
271 def _decode_schema(self, avro_reader):
272 '''extract the header from schema stored in avro file header'''
273 self.avro_schema = avro_reader.writer_schema
274 if self.avro_schema is None:
275 return None, None
276 schema_fields = self.avro_schema['fields']
277 header = tuple(col['name'] for col in schema_fields)
278 return header
279
280 def _read_rows_from(self, avro_reader, header):
281 count = 0
282 maximum = self.limit if self.limit is not None else sys.maxsize
283 for i, record in enumerate(avro_reader):
284 if i < self.skip:
285 continue
286 if count >= maximum:
287 break
288 count += 1
289 row = self._map_row_from(header, record)
290 yield row
291
292 def _map_row_from(self, header, record):
293 '''
294 fastavro auto converts logical types defined in avro schema to
295 correspoding python types. E.g:
296 - avro type: long logicalType: timestamp-millis -> python datetime
297 - avro type: int logicalType: date -> python date
298 - avro type: bytes logicalType: decimal -> python Decimal
299 '''
300 if header is None or PY3:
301 r = tuple(record.values())
302 else:
303 # fastavro on python2 does not respect dict order
304 r = tuple(record.get(col) for col in header)
305 return r
306
307
308 def _write_toavro(table, target, mode, schema, sample,
309 codec='deflate', compression_level=None, **avro_args):
310 if table is None:
311 return
312 # build a schema when not defined by user
313 if not schema:
314 schema, table2 = _build_schema_from_values(table, sample)
315 else:
316 table2 = _fix_missing_headers(table, schema)
317 # fastavro expects a iterator of dicts
318 rows = dicts(table2) if PY3 else _ordered_dict_iterator(table2)
319
320 target2 = write_source_from_arg(target, mode=mode)
321 with target2.open(mode) as target_file:
322 # delay the import of fastavro for not breaking when unused
323 from fastavro import parse_schema
324 from fastavro.write import Writer
325
326 parsed_schema = parse_schema(schema)
327 writer = Writer(fo=target_file,
328 schema=parsed_schema,
329 codec=codec,
330 compression_level=compression_level,
331 **avro_args)
332 num = 1
333 for record in rows:
334 try:
335 writer.write(record)
336 num = num + 1
337 except ValueError as verr:
338 vmsg = _get_error_details(target, num, verr, record, schema)
339 _raise_error(ValueError, vmsg)
340 except TypeError as terr:
341 tmsg = _get_error_details(target, num, terr, record, schema)
342 _raise_error(TypeError, tmsg)
343 # finish writing
344 writer.flush()
345
346 # endregion Implementation
347
348 # region Helpers
349
350
351 def _build_schema_from_values(table, sample):
352 # table2: try not advance iterators
353 samples, table2 = iterpeek(table, sample + 1)
354 props = fieldnames(samples)
355 peek = skip(samples, 1)
356 schema_fields = _build_schema_fields_from_values(peek, props)
357 schema_source = _build_schema_with(schema_fields)
358 return schema_source, table2
359
360
361 def _build_schema_with(schema_fields):
362 schema = {
363 'type': 'record',
364 'name': 'output',
365 'namespace': 'avro',
366 'doc': 'generated by petl',
367 'fields': schema_fields,
368 }
369 return schema
370
371
372 def _build_schema_fields_from_values(peek, props):
373 # store the previous for calculate max precision and max scale
374 previous = OrderedDict()
375 # set a default when value is None in the first row but allow override after
376 fill_missing = True
377 fields = OrderedDict()
378 # iterate on sample rows for dealing with columns with None values
379 for row in peek:
380 _update_field_defs_from(props, row, fields, previous, fill_missing)
381 fill_missing = False
382
383 schema_fields = [item for item in fields.values()]
384 return schema_fields
385
386
387 def _update_field_defs_from(props, row, fields, previous, fill_missing):
388 for prop, val in izip_longest(props, row):
389 if prop is None:
390 break
391 dprev = previous.get(prop + '_prec')
392 fprev = previous.get(prop + '_prop')
393 fcurr = None
394 if isinstance(val, dict):
395 # get the fields from a recursive definition of record inside this field
396 tdef, dcurr, fcurr = _get_definition_from_record(prop, val, fprev, dprev, fill_missing)
397 else:
398 # get the field definition for building the schema
399 tdef, dcurr = _get_definition_from_type_of(prop, val, dprev)
400
401 if tdef is not None:
402 fields[prop] = {'name': prop, 'type': ['null', tdef]}
403 elif fill_missing:
404 fields[prop] = {'name': prop, 'type': ['null', 'string']}
405 if dcurr is not None:
406 previous[prop + '_prec'] = dcurr
407 if fcurr is not None:
408 previous[prop + '_prop'] = fcurr
409
410
411 def _get_definition_from_type_of(prop, val, prev):
412 # TODO: get type for enum, map and other python types
413 tdef = None
414 curr = None
415 if isinstance(val, datetime):
416 tdef = {'type': 'long', 'logicalType': 'timestamp-millis'}
417 elif isinstance(val, time):
418 tdef = {'type': 'int', 'logicalType': 'time-millis'}
419 elif isinstance(val, date):
420 tdef = {'type': 'int', 'logicalType': 'date'}
421 elif isinstance(val, Decimal):
422 curr, precision, scale = _get_precision_from_decimal(curr, val, prev)
423 tdef = {'type': 'bytes', 'logicalType': 'decimal',
424 'precision': precision, 'scale': scale, }
425 elif isinstance(val, bytes):
426 tdef = 'bytes'
427 elif isinstance(val, list):
428 tdef, curr = _get_definition_from_array(prop, val, prev)
429 elif isinstance(val, bool):
430 tdef = 'boolean'
431 elif isinstance(val, float):
432 tdef = 'double'
433 elif isinstance(val, int):
434 tdef = 'long'
435 elif val is not None:
436 tdef = 'string'
437 else:
438 return None, None
439 return tdef, curr
440
441
442 def _get_definition_from_array(prop, val, prev):
443 afield = None
444 for item in iter(val):
445 if item is None:
446 continue
447 field2, curr2 = _get_definition_from_type_of(prop, item, prev)
448 if field2 is not None:
449 afield = field2
450 if curr2 is not None:
451 prev = curr2
452
453 bfield = 'string' if afield is None else afield
454 tdef = {'type': 'array', 'items': bfield}
455 return tdef, prev
456
457
458 def _get_definition_from_record(prop, val, fprev, dprev, fill_missing):
459 if fprev is None:
460 fprev = OrderedDict()
461 if dprev is None:
462 dprev = OrderedDict()
463 props = list(val.keys())
464 row = list(val.values())
465
466 _update_field_defs_from(props, row, fprev, dprev, fill_missing)
467
468 schema_fields = [item for item in fprev.values()]
469 tdef = {
470 'type': 'record',
471 'name': prop + '_record',
472 'namespace': 'avro',
473 'fields': schema_fields,
474 }
475 return tdef, dprev, fprev
476
477
478 def _get_precision_from_decimal(curr, val, prev):
479 if val is None:
480 prec = scale = 0
481 else:
482 prec, scale, _, _ = precision_and_scale(val)
483 if prev is not None:
484 # get the greatests precision and scale of the sample
485 prec0, scale0 = prev.get('precision'), prev.get('scale')
486 prec, scale = max(prec, prec0), max(scale, scale0)
487 prec = max(prec, 8)
488 curr = {'precision': prec, 'scale': scale, }
489 return curr, prec, scale
490
491
492 def precision_and_scale(numeric_value):
493 sign, digits, exp = numeric_value.as_tuple()
494 number = 0
495 for digit in digits:
496 number = (number * 10) + digit
497 # delta = exp + scale
498 delta = 1
499 number = 10 ** delta * number
500 inumber = int(number)
501
502 bits_req = inumber.bit_length() + 1
503 bytes_req = (bits_req + 8) // 8
504 if sign:
505 inumber = - inumber
506 prec = int(math.ceil(math.log10(abs(inumber))))
507 scale = abs(exp)
508 return prec, scale, bytes_req, inumber
509
510
511 def _fix_missing_headers(table, schema):
512 '''add missing columns headers from schema'''
513 if schema is None or 'fields' not in schema:
514 return table
515 # table2: try not advance iterators
516 sample, table2 = iterpeek(table, 2)
517 cols = fieldnames(sample)
518 headers = _get_schema_header_names(schema)
519 if len(cols) >= len(headers):
520 return table2
521 table3 = setheader(table2, headers)
522 return table3
523
524
525 def _get_error_details(target, num, err, record, schema):
526 '''show last row when failed writing for throubleshooting'''
527 headers = _get_schema_header_names(schema)
528 if isinstance(record, dict):
529 table = [headers, list(record.values())]
530 else:
531 table = [headers, record]
532 example = wrap(table).look()
533 dest = " output: %s" % target if isinstance(target, string_types) else ''
534 printed = "failed writing on row #%d: %s\n%s\n schema: %s\n%s"
535 details = printed % (num, err, dest, schema, example)
536 return details
537
538
539 def _get_schema_header_names(schema):
540 fields = schema.get('fields')
541 if fields is None:
542 return []
543 header = [field.get('name') for field in fields]
544 return header
545
546
547 def _raise_error(ErrorType, new_message):
548 """Works like raise Excetion(msg) from prev_exp in python3."""
549 exinf = sys.exc_info()
550 tracebk = exinf[2]
551 try:
552 if PY3:
553 raise ErrorType(new_message).with_traceback(tracebk)
554 # Python2 compatibility workaround
555 exec('raise ErrorType, new_message, tracebk')
556 finally:
557 exinf = None
558 tracebk = None # noqa: F841
559
560
561 def _ordered_dict_iterator(table):
562 it = iter(table)
563 hdr = next(it)
564 flds = [text_type(f) for f in hdr]
565 for row in it:
566 items = list()
567 for i, f in enumerate(flds):
568 try:
569 v = row[i]
570 except IndexError:
571 v = None
572 items.append((f, v))
573 yield OrderedDict(items)
574
575
576 Table.toavro = toavro
577 Table.appendavro = appendavro
578
579 # endregion