TheNeuralBit commented on a change in pull request #12780:
URL: https://github.com/apache/beam/pull/12780#discussion_r513699837



##########
File path: 
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/pubsub/RowToPubsubMessage.java
##########
@@ -57,14 +73,43 @@ public static RowToPubsubMessage 
withTimestampAttribute(boolean useTimestampAttr
             ? input.apply(WithTimestamps.of((row) -> 
row.getDateTime(TIMESTAMP_FIELD).toInstant()))
             : input;
 
-    return withTimestamp
-        .apply(DropFields.fields(TIMESTAMP_FIELD))
-        .apply(ToJson.of())
-        .apply(
-            MapElements.into(TypeDescriptor.of(PubsubMessage.class))
-                .via(
-                    (String json) ->
-                        new PubsubMessage(
-                            json.getBytes(StandardCharsets.ISO_8859_1), 
ImmutableMap.of())));
+    withTimestamp = withTimestamp.apply(DropFields.fields(TIMESTAMP_FIELD));
+    switch (payloadFormat) {
+      case JSON:
+        return withTimestamp
+            .apply("MapRowToJsonString", ToJson.of())
+            .apply("MapToJsonBytes", MapElements.via(new StringToBytes()))
+            .apply("MapToPubsubMessage", MapElements.via(new 
ToPubsubMessage()));
+      case AVRO:
+        return withTimestamp
+            .apply(
+                "MapRowToAvroBytes",
+                
MapElements.via(AvroUtils.getRowToAvroBytesFunction(payloadSchema)))
+            .apply("MapToPubsubMessage", MapElements.via(new 
ToPubsubMessage()));
+      default:
+        throw new IllegalArgumentException("Unsupported payload format: " + 
payloadFormat);
+    }
+  }
+
+  private static class StringToBytes extends SimpleFunction<String, byte[]> {
+    @Override
+    public byte[] apply(String s) {
+      return s.getBytes(ISO_8859_1);

Review comment:
       I'm not sure why I opted to get ISO_8859_1 encoded bytes here... Could 
you change this to use UTF_8?

##########
File path: 
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/pubsub/PubsubMessageToRow.java
##########
@@ -175,11 +213,21 @@ public void processElement(
 
     private final boolean useDlq;
 
+    private final PayloadFormat payloadFormat;
+
     private transient volatile @Nullable ObjectMapper objectMapper;
 
-    protected NestedSchemaPubsubMessageToRow(Schema messageSchema, boolean 
useDlq) {
+    private final SimpleFunction<byte[], Row> avroBytesToRowFn;
+
+    private final Schema payloadSchema;
+
+    protected NestedSchemaPubsubMessageToRow(
+        Schema messageSchema, boolean useDlq, PayloadFormat payloadFormat) {
       this.messageSchema = messageSchema;
       this.useDlq = useDlq;
+      this.payloadFormat = payloadFormat;
+      this.payloadSchema = 
messageSchema.getField(PAYLOAD_FIELD).getType().getRowSchema();
+      this.avroBytesToRowFn = 
AvroUtils.getAvroBytesToRowFunction(payloadSchema);

Review comment:
       Instead of eagerly generating the avroBytesToRowFn (even if we won't 
need it) and then branching on the payloadFormat for every element  in 
parsePayload, we should instead generate a parsePayload function when it's 
needed. This could work similarly to what the current version does 
with`objectMapper`, except we would create and store a `Function<PubsubMessage, 
Row>`. In the JSON case we'd generate the ObjectMapper and wrap that in a 
function, and in the Avro case we'd call getAvroBytesToRowFunction and wrap it.

##########
File path: 
website/www/site/content/en/documentation/dsls/sql/extensions/create-external-table.md
##########
@@ -251,6 +253,8 @@ TBLPROPERTIES '{"timestampAttributeKey": "key", 
"deadLetterQueue": "projects/[PR
     *   `deadLetterQueue`: The topic into which messages are written if the
         payload was not parsed. If not specified, an exception is thrown for
         parsing failures.
+    *   `format`: Optional. Allows you to specify the Pubsub payload format.
+        Possible values are {`json`, `avro`}. Defaults to `json`.

Review comment:
       :+1: thanks

##########
File path: 
sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/meta/provider/pubsub/PubsubAvroIT.java
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.sdk.extensions.sql.meta.provider.pubsub;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasProperty;
+
+import java.io.ByteArrayOutputStream;
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.generic.GenericRecordBuilder;
+import org.apache.beam.sdk.coders.AvroCoder;
+import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.schemas.utils.AvroUtils;
+import org.apache.beam.sdk.transforms.MapElements;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.sdk.values.TypeDescriptors;
+import org.hamcrest.Matcher;
+import org.joda.time.Instant;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Integration tests for querying Pubsub AVRO messages with SQL. */
+@RunWith(JUnit4.class)
+public class PubsubAvroIT extends PubsubTableProviderIT {
+  private static final Schema NAME_HEIGHT_KNOWS_JS_SCHEMA =
+      Schema.builder()
+          .addNullableField("name", Schema.FieldType.STRING)
+          .addNullableField("height", Schema.FieldType.INT32)
+          .addNullableField("knowsJavascript", Schema.FieldType.BOOLEAN)
+          .build();
+
+  private static final Schema NAME_HEIGHT_SCHEMA =
+      Schema.builder()
+          .addNullableField("name", Schema.FieldType.STRING)
+          .addNullableField("height", Schema.FieldType.INT32)
+          .build();
+
+  @Override
+  protected String getPayloadFormat() {
+    return "avro";
+  }
+
+  @Override
+  protected PCollection<String> applyRowsToStrings(PCollection<Row> rows) {
+    return rows.apply(
+        MapElements.into(TypeDescriptors.strings())
+            .via(
+                (Row row) ->
+                    new String(
+                        
AvroUtils.getRowToAvroBytesFunction(row.getSchema()).apply(row), UTF_8)));
+  }
+
+  @Override
+  protected PubsubMessage messageIdName(Instant timestamp, int id, String 
name) {
+    Row row = row(PAYLOAD_SCHEMA, id, name);
+    return message(timestamp, 
AvroUtils.getRowToAvroBytesFunction(PAYLOAD_SCHEMA).apply(row));
+  }
+
+  @Override
+  protected Matcher<PubsubMessage> matcherNames(String name) {
+    Schema schema = Schema.builder().addStringField("name").build();
+    Row row = row(schema, name);
+    return hasProperty("payload", 
equalTo(AvroUtils.getRowToAvroBytesFunction(schema).apply(row)));
+  }
+
+  @Override
+  protected Matcher<PubsubMessage> matcherNameHeight(String name, int height) {
+    Row row = row(NAME_HEIGHT_SCHEMA, name, height);
+    return hasProperty(
+        "payload", 
equalTo(AvroUtils.getRowToAvroBytesFunction(NAME_HEIGHT_SCHEMA).apply(row)));

Review comment:
       `messageIdName`, `matcherNames`, and `matcherNameHeight` should avoid 
using AvroUtils.getRowToAvroBytesFunction as well.

##########
File path: 
sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/meta/provider/pubsub/PubsubTableProviderIT.java
##########
@@ -0,0 +1,651 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.sdk.extensions.sql.meta.provider.pubsub;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.allOf;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasEntry;
+import static org.hamcrest.Matchers.hasProperty;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
+import org.apache.beam.sdk.extensions.sql.SqlTransform;
+import org.apache.beam.sdk.extensions.sql.impl.BeamSqlEnv;
+import org.apache.beam.sdk.extensions.sql.impl.JdbcConnection;
+import org.apache.beam.sdk.extensions.sql.impl.JdbcDriver;
+import org.apache.beam.sdk.extensions.sql.impl.rel.BeamSqlRelUtils;
+import 
org.apache.beam.sdk.extensions.sql.meta.provider.SchemaIOTableProviderWrapper;
+import org.apache.beam.sdk.extensions.sql.meta.provider.TableProvider;
+import org.apache.beam.sdk.extensions.sql.meta.store.InMemoryMetaStore;
+import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO;
+import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
+import org.apache.beam.sdk.io.gcp.pubsub.TestPubsub;
+import org.apache.beam.sdk.io.gcp.pubsub.TestPubsubSignal;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.schemas.SchemaCoder;
+import org.apache.beam.sdk.testing.TestPipeline;
+import org.apache.beam.sdk.transforms.Create;
+import org.apache.beam.sdk.util.common.ReflectHelpers;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.Row;
+import 
org.apache.beam.vendor.calcite.v1_20_0.com.google.common.collect.ImmutableList;
+import 
org.apache.beam.vendor.calcite.v1_20_0.com.google.common.collect.ImmutableMap;
+import 
org.apache.beam.vendor.calcite.v1_20_0.com.google.common.collect.ImmutableSet;
+import 
org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.jdbc.CalciteConnection;
+import org.hamcrest.Matcher;
+import org.joda.time.Duration;
+import org.joda.time.Instant;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public abstract class PubsubTableProviderIT implements Serializable {
+
+  protected static final Schema PAYLOAD_SCHEMA =
+      Schema.builder()
+          .addNullableField("id", Schema.FieldType.INT32)
+          .addNullableField("name", Schema.FieldType.STRING)
+          .build();
+
+  @Rule public transient TestPubsub eventsTopic = TestPubsub.create();
+  @Rule public transient TestPubsub filteredEventsTopic = TestPubsub.create();
+  @Rule public transient TestPubsub dlqTopic = TestPubsub.create();
+  @Rule public transient TestPubsubSignal resultSignal = 
TestPubsubSignal.create();
+  @Rule public transient TestPipeline pipeline = TestPipeline.create();
+  @Rule public transient TestPipeline filterPipeline = TestPipeline.create();
+  private final SchemaIOTableProviderWrapper tableProvider = new 
PubsubTableProvider();
+  private final String payloadFormatParam =
+      getPayloadFormat() == null ? "" : String.format("\"format\" : \"%s\", ", 
getPayloadFormat());
+
+  /**
+   * HACK: we need an objectmapper to turn pipelineoptions back into a map. We 
need to use
+   * ReflectHelpers to get the extra PipelineOptions.
+   */
+  protected static final ObjectMapper MAPPER =
+      new ObjectMapper()
+          
.registerModules(ObjectMapper.findModules(ReflectHelpers.findClassLoader()));
+
+  @Test
+  public void testSQLSelectsPayloadContent() throws Exception {
+    String createTableString =
+        String.format(
+            "CREATE EXTERNAL TABLE message (\n"
+                + "event_timestamp TIMESTAMP, \n"
+                + "attributes MAP<VARCHAR, VARCHAR>, \n"
+                + "payload ROW< \n"
+                + "             id INTEGER, \n"
+                + "             name VARCHAR \n"
+                + "           > \n"
+                + ") \n"
+                + "TYPE '%s' \n"
+                + "LOCATION '%s' \n"
+                + "TBLPROPERTIES '{ "
+                + "%s"
+                + "\"timestampAttributeKey\" : \"ts\" }'",
+            tableProvider.getTableType(), eventsTopic.topicPath(), 
payloadFormatParam);
+
+    String queryString = "SELECT message.payload.id, message.payload.name from 
message";
+
+    // Prepare messages to send later
+    List<PubsubMessage> messages =
+        ImmutableList.of(
+            messageIdName(ts(1), 3, "foo"),
+            messageIdName(ts(2), 5, "bar"),
+            messageIdName(ts(3), 7, "baz"));
+
+    // Initialize SQL environment and create the pubsub table
+    BeamSqlEnv sqlEnv = BeamSqlEnv.inMemory(new PubsubTableProvider());
+    sqlEnv.executeDdl(createTableString);
+
+    // Apply the PTransform to query the pubsub topic
+    PCollection<Row> queryOutput = query(sqlEnv, pipeline, queryString);
+
+    // Observe the query results and send success signal after seeing the 
expected messages
+    queryOutput.apply(
+        "waitForSuccess",
+        resultSignal.signalSuccessWhen(
+            SchemaCoder.of(PAYLOAD_SCHEMA),
+            observedRows ->
+                observedRows.equals(
+                    ImmutableSet.of(
+                        row(PAYLOAD_SCHEMA, 3, "foo"),
+                        row(PAYLOAD_SCHEMA, 5, "bar"),
+                        row(PAYLOAD_SCHEMA, 7, "baz")))));
+
+    // Start the pipeline
+    pipeline.run();
+
+    // Block until a subscription for this topic exists
+    eventsTopic.assertSubscriptionEventuallyCreated(
+        pipeline.getOptions().as(GcpOptions.class).getProject(), 
Duration.standardMinutes(5));
+
+    // Start publishing the messages when main pipeline is started and 
signaling topic is ready
+    eventsTopic.publish(messages);
+
+    // Poll the signaling topic for success message
+    resultSignal.waitForSuccess(Duration.standardMinutes(5));
+  }
+
+  @Test
+  public void testUsesDlq() throws Exception {
+    String createTableString =
+        String.format(
+            "CREATE EXTERNAL TABLE message (\n"
+                + "event_timestamp TIMESTAMP, \n"
+                + "attributes MAP<VARCHAR, VARCHAR>, \n"
+                + "payload ROW< \n"
+                + "             id INTEGER, \n"
+                + "             name VARCHAR \n"
+                + "           > \n"
+                + ") \n"
+                + "TYPE '%s' \n"
+                + "LOCATION '%s' \n"
+                + "TBLPROPERTIES "
+                + "    '{ "
+                + "       %s"
+                + "       \"timestampAttributeKey\" : \"ts\", "
+                + "       \"deadLetterQueue\" : \"%s\""
+                + "     }'",
+            tableProvider.getTableType(),
+            eventsTopic.topicPath(),
+            payloadFormatParam,
+            dlqTopic.topicPath());
+
+    String queryString = "SELECT message.payload.id, message.payload.name from 
message";
+
+    // Prepare messages to send later
+    List<PubsubMessage> messages =
+        ImmutableList.of(
+            messageIdName(ts(1), 3, "foo"),
+            messageIdName(ts(2), 5, "bar"),
+            messageIdName(ts(3), 7, "baz"),
+            messagePayload(ts(4), "{ - }"), // invalid message, will go to DLQ
+            messagePayload(ts(5), "{ + }")); // invalid message, will go to DLQ
+
+    // Initialize SQL environment and create the pubsub table
+    BeamSqlEnv sqlEnv = BeamSqlEnv.inMemory(new PubsubTableProvider());
+    sqlEnv.executeDdl(createTableString);
+
+    // Apply the PTransform to query the pubsub topic
+    PCollection<Row> queryOutput = query(sqlEnv, pipeline, queryString);
+
+    // Observe the query results and send success signal after seeing the 
expected messages
+    queryOutput.apply(
+        "waitForSuccess",
+        resultSignal.signalSuccessWhen(
+            SchemaCoder.of(PAYLOAD_SCHEMA),
+            observedRows ->
+                observedRows.equals(
+                    ImmutableSet.of(
+                        row(PAYLOAD_SCHEMA, 3, "foo"),
+                        row(PAYLOAD_SCHEMA, 5, "bar"),
+                        row(PAYLOAD_SCHEMA, 7, "baz")))));
+
+    // Start the pipeline
+    pipeline.run();
+
+    // Block until a subscription for this topic exists
+    eventsTopic.assertSubscriptionEventuallyCreated(
+        pipeline.getOptions().as(GcpOptions.class).getProject(), 
Duration.standardMinutes(5));
+
+    // Start publishing the messages when main pipeline is started and 
signaling topics are ready
+    eventsTopic.publish(messages);
+
+    // Poll the signaling topic for success message
+    resultSignal.waitForSuccess(Duration.standardMinutes(4));
+    dlqTopic
+        .assertThatTopicEventuallyReceives(
+            matcherPayload(ts(4), "{ - }"), matcherPayload(ts(5), "{ + }"))
+        .waitForUpTo(Duration.standardSeconds(20));
+  }
+
+  @Test
+  public void testSQLLimit() throws Exception {
+    String createTableString =
+        String.format(
+            "CREATE EXTERNAL TABLE message (\n"
+                + "event_timestamp TIMESTAMP, \n"
+                + "attributes MAP<VARCHAR, VARCHAR>, \n"
+                + "payload ROW< \n"
+                + "             id INTEGER, \n"
+                + "             name VARCHAR \n"
+                + "           > \n"
+                + ") \n"
+                + "TYPE '%s' \n"
+                + "LOCATION '%s' \n"
+                + "TBLPROPERTIES "
+                + "    '{ "
+                + "       %s"
+                + "       \"timestampAttributeKey\" : \"ts\", "
+                + "       \"deadLetterQueue\" : \"%s\""
+                + "     }'",
+            tableProvider.getTableType(),
+            eventsTopic.topicPath(),
+            payloadFormatParam,
+            dlqTopic.topicPath());
+
+    List<PubsubMessage> messages =
+        ImmutableList.of(
+            messageIdName(ts(1), 3, "foo"),
+            messageIdName(ts(2), 5, "bar"),
+            messageIdName(ts(3), 7, "baz"),
+            messageIdName(ts(4), 9, "ba2"),
+            messageIdName(ts(5), 10, "ba3"),
+            messageIdName(ts(6), 13, "ba4"),
+            messageIdName(ts(7), 15, "ba5"));
+
+    // We need the default options on the schema to include the project passed 
in for the
+    // integration test
+    CalciteConnection connection = connect(pipeline.getOptions(), new 
PubsubTableProvider());
+
+    Statement statement = connection.createStatement();
+    statement.execute(createTableString);
+
+    // Because Pubsub only allow new subscription receives message after the 
subscription is
+    // created, eventsTopic.publish(messages) can only be called after 
statement.executeQuery.
+    // However, because statement.executeQuery is a blocking call, it has to 
be put into a
+    // seperate thread to execute.
+    ExecutorService pool = Executors.newFixedThreadPool(1);
+    Future<List<String>> queryResult =
+        pool.submit(
+            (Callable)
+                () -> {
+                  ResultSet resultSet =
+                      statement.executeQuery("SELECT message.payload.id FROM 
message LIMIT 3");
+                  ImmutableList.Builder<String> result = 
ImmutableList.builder();
+                  while (resultSet.next()) {
+                    result.add(resultSet.getString(1));
+                  }
+                  return result.build();
+                });
+
+    eventsTopic.assertSubscriptionEventuallyCreated(
+        pipeline.getOptions().as(GcpOptions.class).getProject(), 
Duration.standardMinutes(5));
+    eventsTopic.publish(messages);
+    assertThat(queryResult.get(2, TimeUnit.MINUTES).size(), equalTo(3));
+    pool.shutdown();
+  }
+
+  @Test
+  public void testWritesRowsToPubsub() throws Exception {
+    Schema personSchema =
+        Schema.builder()
+            .addStringField("name")
+            .addInt32Field("height")
+            .addBooleanField("knowsJavascript")
+            .build();
+    PCollection<Row> rows =
+        pipeline
+            .apply(
+                Create.of(
+                    row(personSchema, "person1", 80, true),
+                    row(personSchema, "person2", 70, false),
+                    row(personSchema, "person3", 60, true),
+                    row(personSchema, "person4", 50, false),
+                    row(personSchema, "person5", 40, true)))
+            .setRowSchema(personSchema)
+            .apply(
+                SqlTransform.query(
+                    "SELECT name FROM PCOLLECTION AS person WHERE 
person.knowsJavascript"));
+    // Convert rows to proper format and write to pubsub
+    PCollection<String> rowsStrings = applyRowsToStrings(rows);
+    
rowsStrings.apply(PubsubIO.writeStrings().to(eventsTopic.topicPath().getPath()));
+
+    pipeline.run().waitUntilFinish(Duration.standardMinutes(5));
+
+    eventsTopic
+        .assertThatTopicEventuallyReceives(
+            matcherNames("person1"), matcherNames("person3"), 
matcherNames("person5"))
+        .waitForUpTo(Duration.standardSeconds(20));
+  }

Review comment:
       I think it may be better to just get rid of this test. I added it as a 
stepping stone when I was adding support for writing JSON to PubSub (see 
https://github.com/apache/beam/pull/9880). But it's just adding unnecessary 
complexity to keep it around now, the write path is thoroughly tested 
end-to-end in the tests below this one.
   
   If we get rid of this you won't need `applyRowsToStrings`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to