Skip to content

Commit

Permalink
Add methods for transforming rows into Ruby objects
Browse files Browse the repository at this point in the history
  • Loading branch information
kmcq committed Sep 11, 2023
1 parent 986d89c commit 59438f7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/trino/client/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ def self.faraday_client(options)
Trino::Client.faraday_client(options)
end

def self.transform_row(column_value_parsers, row)
row_object = {}

row.each_with_index do |element, i|
column = column_value_parsers[i]
value = column.value(element)

row_object[column.name] = value
end

row_object
end

def initialize(api)
@api = api
end
Expand Down Expand Up @@ -87,6 +100,20 @@ def columns
return @api.current_results.columns
end

def column_value_parsers
@column_value_parsers ||= columns.map {|column|
ColumnValueParser.new(column)
}
end

def transform_rows
rows.map(&:transform_row)
end

def transform_row(row)
self.class.transform_row(column_value_parsers, row)
end

def rows
rows = []
each_row_chunk {|chunk|
Expand Down
35 changes: 35 additions & 0 deletions spec/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,41 @@
expect(rehashed[1].values[4]).to eq ['some horse', 0]
end

it 'transforms rows into Ruby objects' do
rows = [
['dog', 1, 'Lassie', ['kibble', 'peanut butter'], ['spaniel', 2]],
['horse', 5, 'Mr. Ed', ['hay', 'sugar cubes'], ['some horse', 0]],
['t-rex', 37, 'Doug', ['rodents', 'small dinos'], ['dino', 0]]
]
client.stub(:run).and_return([columns, rows])

columns, rows = client.run('fake query')
column_value_parsers = columns.map { |column| Trino::Client::ColumnValueParser.new(column) }
transformed_rows = rows.map { |row| Trino::Client::Query.transform_row(column_value_parsers, row) }

expect(transformed_rows[0]).to eq({
"animal" => "dog",
"score" => 1,
"name" => "Lassie",
"foods" => ["kibble", "peanut butter"],
"traits" => {
"breed" => "spaniel",
"num_spots" => 2,
},
})

expect(transformed_rows[1]).to eq({
"animal" => "horse",
"score" => 5,
"name" => "Mr. Ed",
"foods" => ["hay", "sugar cubes"],
"traits" => {
"breed" => "some horse",
"num_spots" => 0,
},
})
end

it 'empty results' do
rows = []
client.stub(:run).and_return([columns, rows])
Expand Down

0 comments on commit 59438f7

Please sign in to comment.