herringbone 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1148482072b7346372f0ce7d404c237359dbda86443c0b12dd8200937f6336cc
4
- data.tar.gz: 9c1abff1ff39a715b0cb32f9bb9385d3642cdf6a0f2f5f6c45e741f25832ca21
3
+ metadata.gz: b6e9b4e12f2b83688e6ea7be2752dd389cd1a338489834160efb0df5f796916e
4
+ data.tar.gz: c69303ac028259092e2f22c0f5d635f0e428ae1950c1b4b42d4a6379fd6a5a87
5
5
  SHA512:
6
- metadata.gz: 84e2d8192f4a0e9e15430cf8df20d1dd070028dc3561973d639ca887ff82c8673e7864063419a63b05649526ccf6dd0f2a6eb9d291067fd5c674a2ba76ec9771
7
- data.tar.gz: 532f1deff266b6f4867f47c6e80b200cfa9bcdb1a5d45442ef8e40b5f25247087fa2a85975822c3f572c6a64575ae6b4f87bbd72a13df1143db2a0c82fde856b
6
+ metadata.gz: 00a7d9246cb73211dcd5c46a5b0dab15b20b0fe1dc0026a2f02dcf3a9e13a11c91b8632bf1891fdd2f5a8deccf42f1c46918ee26ed9bf881208338f731cd12b6
7
+ data.tar.gz: 91edc03478f1d9aa24f4d40527b8d2ac8cbed53047e3870e2b17d52ba252bb29a354035f5f072105adf0122bcf93e24c424747552423f9f7ba345fedb98b4219
data/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  A pure-Ruby reader and writer for [Apache Parquet](https://parquet.apache.org/) files.
4
4
 
5
- - No native extensions, no Thrift gem: the Thrift compact protocol, all encodings and the
6
- Snappy and LZ4 codecs are implemented in Ruby
5
+ - No Thrift gem and no native extensions of its own: the Thrift compact protocol, all encodings
6
+ and the Snappy and LZ4 codecs are implemented in Ruby (ZSTD and Brotli use optional gems)
7
7
  - Full nesting support (structs, lists, maps, any depth) via Dremel record shredding/assembly
8
8
  - Reads files from parquet-mr, Arrow, Spark, Impala, DuckDB, Rust writers etc.
9
9
  - Ruby 3.0+
@@ -12,32 +12,70 @@ A pure-Ruby reader and writer for [Apache Parquet](https://parquet.apache.org/)
12
12
 
13
13
  ```ruby
14
14
  gem "herringbone"
15
+ gem "zstd-ruby" # optional: ZSTD (faster writes and smaller files than the default Snappy)
16
+ gem "brotli" # optional: Brotli
17
+ gem "xxhash" # optional: faster bloom filters
15
18
  ```
16
19
 
17
- Snappy and LZ4 are implemented in Ruby, GZIP uses `zlib`, and ZSTD and Brotli come from the
18
- `zstd-ruby` and `brotli` gems (runtime dependencies, along with `bigdecimal`).
20
+ The only dependency is `bigdecimal`. Snappy, LZ4 and GZIP always work. `Herringbone.codecs` lists
21
+ the codecs this process can use, e.g. `[:none, :snappy, :gzip, :lz4, :lz4_hadoop, :zstd]`. Using
22
+ a missing one raises `Herringbone::MissingCodecError` naming the gem to add: a writer raises it
23
+ before writing anything, a reader when it reaches the first such page (the schema and metadata
24
+ are still readable). LZO is not supported.
19
25
 
20
26
  ## Reading
21
27
 
28
+ Herringbone never opens files by path: readers take a random-access IO (a `File` opened with
29
+ `"rb"`, `StringIO`, `Tempfile`...), which stays open and belongs to the caller.
30
+
22
31
  ```ruby
23
32
  require "herringbone"
24
33
 
25
- Herringbone::Reader.open("data.parquet") do |reader|
26
- reader.schema # => #<Herringbone::Schema ...>
34
+ File.open("data.parquet", "rb") do |file|
35
+ reader = Herringbone::Reader.new(file)
36
+ reader.schema
27
37
  reader.num_rows
28
38
 
29
- reader.each_row do |row| # Hash with String keys, nested values as Hash/Array
30
- p row
31
- end
32
-
33
- reader.each_row(columns: ["id", "name"]) { |row| ... } # projection
34
- reader.column("name") # => all values of one top-level field
35
- reader.read_row_group(0) # => { "id" => [...], "name" => [...] }
39
+ reader.each_row { |row| p row } # Hashes with String keys, nested values as Hash/Array
40
+ reader.each_batch(1000) { |rows| ... } # Arrays of up to 1000 rows
41
+ reader.each_batch(10_000, as: :columns) { |batch| batch["amount"].sum } # { "id" => [...], ... }
42
+ reader.read # all rows at once; read(as: :columns) for column Arrays
36
43
  end
44
+ ```
45
+
46
+ Reads stream: pages are read and decoded one at a time per column and rows are assembled in
47
+ batches, so memory depends on the batch and page sizes rather than on the row group size (1M
48
+ rows in a single row group peak at about 60–160 MB RSS growth instead of 660 MB). Column-order
49
+ batches (`as: :columns`) skip building a Hash per row and are 25–30% faster.
37
50
 
38
- Herringbone.read("data.parquet") # => Array of row Hashes
51
+ `Reader.new` takes `keys: :symbol` for Symbol keys (in rows and in structs; map keys stay as
52
+ stored) and `time_zone:` to return timestamps in a zone instead of UTC: a UTC offset (`"+02:00"`,
53
+ or seconds), `"UTC"`, a `TZInfo::Timezone`, or anything responding to `#at` such as `Time.zone`
54
+ in Rails (which yields `ActiveSupport::TimeWithZone`). Zone names like `"Europe/Amsterdam"` work
55
+ when ActiveSupport or TZInfo is loaded. Timestamps stored with `isAdjustedToUTC=false` are
56
+ wall-clock values and stay as they are.
57
+
58
+ ### Selecting rows
59
+
60
+ `each_row`, `each_batch` and `read` take `columns:`, `where:`, `from:` and `limit:`:
61
+
62
+ ```ruby
63
+ reader.read(columns: %w[id name]) # projection
64
+ reader.read(where: { user_id: 42 })
65
+ reader.read(where: { status: %w[paid shipped], created_at: 1.week.ago.. }) # IN, Ranges
66
+ reader.read(where: { "address.city" => "Amsterdam", deleted_at: nil }) # struct members, IS NULL
67
+ reader.read(where: { amount: ->(v) { v && v > 100 } }) # any callable
68
+ reader.read(from: 1_000_000, limit: 100) # rows 1,000,000..1,000,099
39
69
  ```
40
70
 
71
+ All conditions must hold; filtered columns need not be among `columns:`, and any column not inside
72
+ a list or map can be filtered on. Row groups are skipped using min/max statistics, null counts and
73
+ bloom filters, pages using the page index (written by Herringbone, parquet-mr, Arrow and others),
74
+ and `from:` jumps to its row through the offset index; every row read is then checked, so results
75
+ are exact. On a 1M-row file with 20k-row pages, looking up one `id` takes 0.1 s instead of 6.3 s.
76
+ Filters help most on columns the data is sorted or clustered by. `reader.scan_plan(where: ...)`
77
+ shows which row groups and row ranges a read would touch, without reading them.
78
+
41
79
  ## Writing
42
80
 
43
81
  ```ruby
@@ -56,38 +94,33 @@ schema = Herringbone::Schema.define do
56
94
  timestamp :created_at
57
95
  end
58
96
 
59
- Herringbone::Writer.open("out.parquet", schema) do |w|
60
- w << { "id" => 1, "name" => "Anna", "status" => "paid", "tags" => ["a", "b"],
61
- "scores" => { "x" => 1.5 }, "address" => { "city" => "Amsterdam" },
62
- "price" => BigDecimal("9.99"), "payload" => { "any" => ["json"] }, "created_at" => Time.now }
63
- w << { id: 2, status: :pending } # Symbol keys and values work; missing keys are nulls
64
- w << [3, "Bo", nil, nil, nil, nil, nil, nil, nil, nil] # Arrays in schema order
65
- w << order # anything with #attributes (ActiveRecord) or #to_h (Struct, Data)
97
+ File.open("out.parquet", "wb") do |file|
98
+ Herringbone::Writer.open(file, schema) do |w|
99
+ w << { "id" => 1, "name" => "Anna", "status" => "paid", "tags" => ["a", "b"],
100
+ "scores" => { "x" => 1.5 }, "address" => { "city" => "Amsterdam" },
101
+ "price" => BigDecimal("9.99"), "payload" => { "any" => ["json"] }, "created_at" => Time.now }
102
+ w << { id: 2, status: :pending } # Symbol keys and values work; missing keys are nulls
103
+ w << [3, "Bo", nil, nil, nil, nil, nil, nil, nil, nil] # Arrays in schema order
104
+ w << order # anything with #attributes (ActiveRecord) or #to_h (Struct, Data)
105
+ end
66
106
  end
67
-
68
- # Or with an inferred schema, optionally overriding some columns
69
- Herringbone.write("out.parquet", rows, schema: Herringbone::Schema.infer(rows, types: { payload: :json }))
70
107
  ```
71
108
 
72
- Schemas can also be given as a Hash, anywhere a schema is accepted:
109
+ `Herringbone.write(io, rows)` writes an Enumerable of rows in one go, inferring the schema from the
110
+ first 1000 rows unless `schema:` is given; fields declared in a block replace inferred ones:
111
+ `Herringbone.write(io, rows, schema: Herringbone::Schema.infer(rows) { json :payload })`.
73
112
 
74
- ```ruby
75
- Herringbone::Schema.define(
76
- id: { type: :int64, null: false },
77
- name: :string,
78
- tags: [:string], # list of strings
79
- address: { city: :string, zip: :string }, # struct
80
- price: { type: :decimal, precision: 12, scale: 2 },
81
- scores: { type: :map, key: :string, value: :double }
82
- )
83
- Herringbone::Writer.open("out.parquet", { id: :int64, name: :string }) { |w| w << [1, "x"] }
84
- ```
113
+ The writer writes to any IO that responds to `#write` (a `File`, `StringIO`, `Tempfile`, socket or
114
+ pipe), sequentially, and never seeks, rewinds or closes it. If the `Writer.open` block raises (or
115
+ `#abort` is called), no footer is written and what was written so far is left for you to discard.
116
+ To replace a file only once it is complete, write to a temporary file and rename it.
85
117
 
86
- Column types in the DSL: `boolean int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double
87
- float16 string binary json bson enum uuid date int96 time timestamp decimal fixed`, plus
88
- `struct`, `list` and `map`. Fields are nullable unless `null: false` is given.
89
- List elements are nullable unless `element_null: false`; map values unless `value_null: false`.
90
- Nested lists: `list :matrix do list :element, :double end`.
118
+ Column types: `boolean int8 int16 int32 int64 uint8 uint16 uint32 uint64 float double float16
119
+ string binary json bson enum uuid date int96 time timestamp decimal fixed`, plus `struct`, `list`
120
+ and `map`; `column :name, :int32` declares one by name. Fields are nullable unless `null: false`
121
+ is given; list elements unless `element_null: false`, map values unless `value_null: false`.
122
+ Nested lists: `list :matrix do list :element, :double end`. `time` and `timestamp` take `unit:`
123
+ (`:millis`, `:micros`, `:nanos`) and `utc:`.
91
124
 
92
125
  `enum` is a string column. `values:` restricts what may be written, and also takes a Rails-style
93
126
  Hash (`values: Order.statuses`), in which case both labels and stored integers are accepted and
@@ -111,41 +144,53 @@ Columns accept the values Ruby and Rails code usually has at hand:
111
144
  Values that don't fit raise `Herringbone::EncodeError` naming the row number and column path; the
112
145
  failed row is discarded and the writer can carry on.
113
146
 
114
- When given a path, the writer writes to a temporary file next to it and renames it into place on
115
- close. If the block raises (or `#abort` is called), the temporary file is removed and any
116
- existing file at the path is left untouched. An IO (`File`, `StringIO`, a socket...) can be
117
- given instead of a path.
118
-
119
147
  Writer options:
120
148
 
121
149
  | option | default | |
122
150
  |---|---|---|
123
- | `compression` | `:zstd` | `:none`, `:snappy`, `:gzip`, `:lz4` (LZ4_RAW), `:lz4_hadoop`, `:zstd`, `:brotli` |
124
- | `row_group_bytes` | 16MB | flush a row group once the buffered values take about this much memory; bounds memory use. Low-cardinality string columns are dictionary-encoded as rows arrive and other strings are packed into byte buffers, so a 15-column table exported in 16MB groups peaks around 290 MB RSS (420 MB with 64MB groups) |
125
- | `row_group_size` | none | also flush after this many rows |
126
- | `page_size` | 1MB | approximate data page size |
151
+ | `compression` | `:snappy` | `:none`, `:snappy`, `:gzip`, `:lz4` (LZ4_RAW), `:lz4_hadoop`, `:zstd`, `:brotli` |
152
+ | `row_group_bytes` | 16MB | flush a row group once the buffered values take about this much memory, which bounds memory use (a 15-column table peaks around 290 MB RSS) |
153
+ | `row_group_rows` | none | also flush after this many rows |
154
+ | `page_bytes` | 1MB | approximate data page size |
155
+ | `page_rows` | `20_000` | at most this many rows per data page |
127
156
  | `data_page_version` | `1` | `1` or `2` |
128
157
  | `dictionary` | `true` | `false`, or an Array of column paths to dictionary-encode |
129
158
  | `encodings` | `{}` | e.g. `{ "id" => :delta_binary_packed, "x" => :byte_stream_split }` |
130
- | `statistics` | `true` | write min/max/null_count |
131
- | `metadata` | `{}` | footer key/value metadata |
159
+ | `metadata` | `{}` | footer key/value metadata, read back with `reader.metadata` |
160
+ | `bloom_filters` | none | `true`, an Array of column paths, or `{ "path" => { ndv:, fpp:, max_bytes: } }` |
132
161
 
133
- ## Exporting ActiveRecord models
162
+ ### Statistics, page indexes and bloom filters
134
163
 
135
- `Herringbone::Schema.from_active_record` builds a schema from a model's columns, so that
136
- `record.attributes` can be written as-is. Rails is not a dependency: it only calls
137
- `columns`, `primary_key` and `defined_enums` on the model.
164
+ Every column chunk gets min/max/null-count statistics and the Parquet page index (per-page min/max
165
+ and row offsets), which Herringbone, DuckDB, Spark, Trino, Arrow and DataFusion use to skip pages.
166
+ With 20,000 rows per page, `WHERE id BETWEEN ...` on a sorted column reads a handful of pages
167
+ instead of the whole row group, so sort rows by the columns you filter on.
168
+
169
+ Min/max cannot rule out a value inside a row group's range, the usual case for unsorted IDs,
170
+ emails or UUIDs; a bloom filter can. They are off by default. `bloom_filters: ["user_id", "email"]`
171
+ (or `true` for every non-boolean column) writes Parquet's split block bloom filters, sized from
172
+ each row group's distinct values at a false positive probability of 1% (`fpp:`, up to `max_bytes:`,
173
+ default 1MB) unless `ndv:` gives the number of distinct values. Nested leaves are named by their
174
+ dotted path (`"tags.list.element"`). Hashing is pure Ruby unless the `xxhash` gem is installed:
175
+ a million rows take about 1.2 s longer to write with a filter on an INT64 column and 2.8 s longer
176
+ with one on a ~22-byte string column, and about 0.5 s longer with `xxhash`.
177
+
178
+ ## ActiveRecord
179
+
180
+ `Herringbone.write` also takes a model or relation, which it reads with `find_each`, using a schema
181
+ built from the model's columns. It returns the number of rows written:
138
182
 
139
183
  ```ruby
140
- schema = Herringbone::Schema.from_active_record(Order)
141
- Herringbone::Writer.open("orders.parquet", schema) do |w|
142
- Order.find_each { |order| w << order.attributes }
184
+ File.open("orders.parquet", "wb") do |file|
185
+ Herringbone.write(file, Order.where(created_at: 1.year.ago..), compression: :zstd)
143
186
  end
187
+ schema = Herringbone::Schema.from_active_record(Order, only: %w[id status total])
188
+ Herringbone.write(io, Order, schema: schema)
144
189
  ```
145
190
 
146
- Options: `only:` and `except:` take attribute names; `enums: :enum` writes enum attributes with
147
- the Parquet ENUM annotation instead of as plain strings (the default, `enums: :string`). Enum
148
- attributes are written as their labels, and the writer rejects values outside the enum.
191
+ `from_active_record` takes `only:`, `except:` and `parquet_enum: true`. Rails is not a dependency:
192
+ it only calls `columns`, `primary_key` and `defined_enums` on the model. Enum attributes are
193
+ written as their labels, and the writer rejects values outside the enum.
149
194
 
150
195
  | Column | Parquet |
151
196
  |---|---|
@@ -161,8 +206,8 @@ attributes are written as their labels, and the writer rejects values outside th
161
206
  | `string`, `text`, `citext`, anything else | `string` |
162
207
  | Postgres array columns | `list` of the element type |
163
208
 
164
- Columns declared `NOT NULL` (and primary keys) are required, all others nullable.
165
- Column order follows `Model.columns`.
209
+ Columns declared `NOT NULL` (and primary keys) are required, all others nullable. Column order
210
+ follows `Model.columns`.
166
211
 
167
212
  ## Type mapping
168
213
 
@@ -180,23 +225,50 @@ Column order follows `Model.columns`.
180
225
  | UUID | `String` like `"0f1e2d3c-..."` |
181
226
  | struct / list / map | `Hash` / `Array` / `Hash` |
182
227
 
183
- ## Supported format features
228
+ ## Inspecting files
184
229
 
185
- - Encodings (read and write): PLAIN, PLAIN_DICTIONARY/RLE_DICTIONARY, RLE, DELTA_BINARY_PACKED,
186
- DELTA_LENGTH_BYTE_ARRAY, DELTA_BYTE_ARRAY, BYTE_STREAM_SPLIT; legacy BIT_PACKED levels (read)
187
- - Data page v1 and v2, dictionary pages, page CRCs (written)
188
- - Legacy list and map layouts per the Parquet backward-compatibility rules
189
- - Not supported: encryption, column chunks in external files, bloom filters and page indexes
190
- (ignored when reading, not written)
230
+ > The inspector and its HTML view are modelled on
231
+ > **[Parquet X-ray](https://huggingface.co/spaces/cfahlgren1/parquet-xray) by cfahlgren1** —
232
+ > the design and the idea are theirs. Go check it out.
233
+
234
+ `Herringbone::Inspector` examines a file using only its footer, page headers, page indexes and
235
+ bloom filter headers. Nothing is decompressed, so it is fast on big files and works for ZSTD and
236
+ Brotli files without the codec gems.
237
+
238
+ ```ruby
239
+ File.open("data.parquet", "rb") do |file|
240
+ inspector = Herringbone::Inspector.new(file)
241
+ inspector.summary # size, rows, row groups, codecs, page index / bloom filter presence...
242
+ inspector.row_groups[0].column("name").pages # page headers; also statistics, column_index...
243
+ puts inspector.report # the schema, every column chunk, key/value metadata (Arrow schema decoded)
244
+ inspector.to_h # all of it, JSON-serializable
245
+ inspector.to_html # one self-contained HTML page with a to-scale byte map of the file
246
+ end
247
+ ```
248
+
249
+ `inspector.verify_checksums` reads every page body (still without decompressing) to check the page
250
+ CRCs; the results then appear in `summary`, `report`, `to_h` and `to_html`.
191
251
 
192
252
  ## Command line
193
253
 
194
254
  ```
195
- bin/herringbone schema FILE
196
- bin/herringbone meta FILE
197
- bin/herringbone cat FILE [N]
255
+ bin/herringbone cat FILE [N] # rows as JSON lines
256
+ bin/herringbone inspect FILE [--pages] # text report (--pages lists every page header)
257
+ bin/herringbone inspect FILE --json # everything as JSON
258
+ bin/herringbone inspect FILE --html > out.html # the HTML page
198
259
  ```
199
260
 
261
+ Add `--verify-checksums` to any `inspect` form to check page CRCs.
262
+
263
+ ## Supported format features
264
+
265
+ - Encodings (read and write): PLAIN, PLAIN_DICTIONARY/RLE_DICTIONARY, RLE, DELTA_BINARY_PACKED,
266
+ DELTA_LENGTH_BYTE_ARRAY, DELTA_BYTE_ARRAY, BYTE_STREAM_SPLIT; legacy BIT_PACKED levels (read)
267
+ - Data page v1 and v2, dictionary pages, page CRCs (written)
268
+ - Page indexes and split block bloom filters (read and written)
269
+ - Legacy list and map layouts per the Parquet backward-compatibility rules
270
+ - Not supported: encryption, column chunks in external files
271
+
200
272
  ## Development
201
273
 
202
274
  ```
data/bin/herringbone CHANGED
@@ -2,9 +2,12 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  # Usage:
5
- # herringbone schema FILE print the schema
6
- # herringbone meta FILE print row groups, codecs and encodings
7
- # herringbone cat FILE [N] print rows as JSON lines (optionally only the first N)
5
+ # herringbone cat FILE [N] print rows as JSON lines (optionally only the first N)
6
+ # herringbone inspect FILE [--pages] print the schema, row groups, column chunks (and every page header)
7
+ # herringbone inspect FILE --json print all of it as JSON
8
+ # herringbone inspect FILE --html print a self-contained HTML page showing the file's layout
9
+ # add --verify-checksums to any inspect form to read page bodies and check their CRCs
10
+ # `inspect` reads only the footer, page headers and page indexes: no values are decompressed.
8
11
  $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
9
12
  require "herringbone"
10
13
  require "json"
@@ -22,33 +25,42 @@ def jsonable(v)
22
25
  end
23
26
  end
24
27
 
25
- command, path, limit = ARGV
26
- unless %w[schema meta cat].include?(command) && path
27
- warn "usage: herringbone (schema|meta|cat) FILE [N]"
28
+ USAGE = "usage: herringbone cat FILE [N]\n" \
29
+ " herringbone inspect FILE [--pages | --json | --html] [--verify-checksums]"
30
+
31
+ command, *rest = ARGV
32
+ flags, args = rest.partition { |a| a.start_with?("--") }
33
+ path, limit = args
34
+ valid = case command
35
+ when "cat" then flags.empty? && path && (limit.nil? || limit.match?(/\A\d+\z/))
36
+ when "inspect"
37
+ formats = flags & %w[--pages --json --html]
38
+ path && limit.nil? && (flags - %w[--pages --json --html --verify-checksums]).empty? && formats.size <= 1
39
+ end
40
+ unless valid
41
+ warn USAGE
28
42
  exit 1
29
43
  end
30
44
 
31
- Herringbone::Reader.open(path) do |r|
32
- case command
33
- when "schema"
34
- puts r.schema.inspect
35
- when "meta"
36
- puts "rows: #{r.num_rows}, row groups: #{r.num_row_groups}, created by: #{r.created_by}"
37
- r.key_value_metadata.each { |k, v| puts " #{k} = #{v.to_s[0, 80]}" }
38
- r.row_groups.each_with_index do |rg, i|
39
- puts "row group #{i}: #{rg.num_rows} rows"
40
- rg.columns.each do |cc|
41
- m = cc.meta_data
42
- encodings = m.encodings.map { |e| Herringbone::Format::Encoding::NAMES[e] }.join(",")
43
- puts " #{m.path_in_schema.join(".")}: #{Herringbone::Format::Codec::NAMES[m.codec]} #{encodings} " \
44
- "#{m.total_compressed_size}/#{m.total_uncompressed_size} bytes"
45
+ # Parquet and file errors are reported in one line, without a backtrace
46
+ begin
47
+ File.open(path, "rb") do |io|
48
+ if command == "cat"
49
+ n = limit&.to_i
50
+ Herringbone::Reader.new(io).each_row(limit: n) { |row| puts JSON.generate(jsonable(row)) }
51
+ else
52
+ inspector = Herringbone::Inspector.new(io)
53
+ inspector.verify_checksums if flags.include?("--verify-checksums")
54
+ if flags.include?("--json")
55
+ puts JSON.pretty_generate(inspector.to_h)
56
+ elsif flags.include?("--html")
57
+ $stdout.write(inspector.to_html)
58
+ else
59
+ puts inspector.report(pages: flags.include?("--pages"))
45
60
  end
46
61
  end
47
- when "cat"
48
- n = limit&.to_i
49
- r.each_row.with_index do |row, i|
50
- break if n && i >= n
51
- puts JSON.generate(jsonable(row))
52
- end
53
62
  end
63
+ rescue Herringbone::Error, SystemCallError => e
64
+ warn "herringbone: #{e.message}"
65
+ exit 1
54
66
  end
@@ -5,22 +5,18 @@ module Herringbone
5
5
  # Builds a schema from an ActiveRecord model, so that the Hashes returned by
6
6
  # +record.attributes+ can be written directly:
7
7
  #
8
- # schema = Herringbone::Schema.from_active_record(Order)
9
- # Herringbone::Writer.open("orders.parquet", schema) do |w|
10
- # Order.find_each { |order| w << order.attributes }
11
- # end
8
+ # schema = Herringbone::Schema.from_active_record(Order, except: %w[notes])
9
+ # File.open("orders.parquet", "wb") { |f| Herringbone.write(f, Order, schema: schema) }
12
10
  #
13
11
  # ActiveRecord is not required: this only uses what a model class exposes
14
12
  # (+columns+, +primary_key+ and, when present, +defined_enums+).
15
13
  #
16
- # only: attribute names to include (Strings or Symbols)
17
- # except: attribute names to leave out
18
- # enums: :string (default) writes enum attributes as STRING columns, :enum uses the
19
- # Parquet ENUM annotation (which pyarrow/pandas read as binary). Either way the
20
- # enum labels are written, and the writer rejects values outside the enum mapping
21
- # (stored values such as 0/1 are accepted and written as their labels).
22
- def self.from_active_record(model, only: nil, except: nil, enums: :string)
23
- raise ArgumentError, "enums: must be :string or :enum" unless %i[string enum].include?(enums)
14
+ # only: attribute names to include (Strings or Symbols)
15
+ # except: attribute names to leave out
16
+ # parquet_enum: Rails enum attributes are string columns holding the labels (the writer
17
+ # rejects values outside the enum; stored values such as 0/1 are written as
18
+ # their labels). true adds the Parquet ENUM annotation, see Builder#enum.
19
+ def self.from_active_record(model, only: nil, except: nil, parquet_enum: false)
24
20
  only = only && Array(only).map(&:to_s)
25
21
  except = Array(except).map(&:to_s)
26
22
  defined_enums = model.respond_to?(:defined_enums) ? model.defined_enums.to_h { |k, v| [k.to_s, v] } : {}
@@ -34,7 +30,7 @@ module Herringbone
34
30
  primary = primary_keys.include?(name)
35
31
  nullable = column.null != false && !primary
36
32
  if (mapping = defined_enums[name])
37
- builder.enum(name, values: mapping.to_h, parquet_enum: enums == :enum, null: nullable)
33
+ builder.enum(name, values: mapping.to_h, parquet_enum: parquet_enum, null: nullable)
38
34
  else
39
35
  ActiveRecordMapping.add_column(builder, column, nullable, primary)
40
36
  end
@@ -129,3 +125,4 @@ module Herringbone
129
125
  end
130
126
  end
131
127
  end
128
+