|
| 1 | +# Copyright 2020 The SQLFlow Authors. All rights reserved. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +from google.protobuf import text_format, wrappers_pb2 |
| 15 | +from runtime.dbapi.connection import ResultSet |
| 16 | +from runtime.dbapi.table_writer import sqlflow_pb2 |
| 17 | + |
| 18 | + |
| 19 | +class ProtobufWriter: |
| 20 | + def __init__(self, result_set): |
| 21 | + assert isinstance(result_set, ResultSet) |
| 22 | + column_info = result_set.column_info() |
| 23 | + self.all_responses = [] |
| 24 | + head = sqlflow_pb2.Head() |
| 25 | + for field_name, _ in column_info: |
| 26 | + head.column_names.append(field_name) |
| 27 | + self.all_responses.append(sqlflow_pb2.Response(head=head)) |
| 28 | + for row in result_set: |
| 29 | + pb_row = sqlflow_pb2.Row() |
| 30 | + for col in row: |
| 31 | + any_msg = self.pod_to_pb_any(col) |
| 32 | + any = pb_row.data.add() |
| 33 | + any.Pack(any_msg) |
| 34 | + self.all_responses.append(sqlflow_pb2.Response(row=pb_row)) |
| 35 | + |
| 36 | + @staticmethod |
| 37 | + def pod_to_pb_any(value): |
| 38 | + if isinstance(value, bool): |
| 39 | + v = wrappers_pb2.BoolValue(value=value) |
| 40 | + elif isinstance(value, int): |
| 41 | + v = wrappers_pb2.Int32Value(value=value) |
| 42 | + elif isinstance(value, float): |
| 43 | + v = wrappers_pb2.FloatValue(value=value) |
| 44 | + elif isinstance(value, str): |
| 45 | + v = wrappers_pb2.StringValue(value=value) |
| 46 | + else: |
| 47 | + raise ValueError("not supported cell data type: %s" % type(value)) |
| 48 | + return v |
| 49 | + |
| 50 | + def dump_strings(self): |
| 51 | + lines = [] |
| 52 | + for resp in self.all_responses: |
| 53 | + lines.append(text_format.MessageToString(resp, as_one_line=True)) |
| 54 | + return lines |
0 commit comments