Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spark,snowflake: support query option via SQL parser #2563

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,41 @@
public class SqlUtils {
public static <D extends OpenLineage.Dataset> List<D> getDatasets(
DatasetFactory<D> datasetFactory, String sql, String dialect, String namespace) {
Optional<SqlMeta> sqlMeta = OpenLineageSql.parse(Collections.singletonList(sql), dialect);
if (sqlMeta.isPresent()) {
return getDatasets(datasetFactory, sqlMeta.get(), namespace);
}
return Collections.emptyList();
return getDatasets(datasetFactory, sql, dialect, namespace, null, null);
}

public static <D extends OpenLineage.Dataset> List<D> getDatasets(
DatasetFactory<D> datasetFactory, SqlMeta meta, String namespace) {
return meta.inTables().stream()
DatasetFactory<D> datasetFactory,
String sql,
String dialect,
String namespace,
String defaultDatabase,
String defaultSchema) {
Optional<SqlMeta> sqlMeta = OpenLineageSql.parse(Collections.singletonList(sql), dialect);
return sqlMeta
.map(
dbtm -> {
return datasetFactory.getDataset(
new DatasetIdentifier(dbtm.qualifiedName(), namespace),
new OpenLineage.DatasetFacetsBuilder());
})
.collect(Collectors.toList());
meta ->
meta.inTables().stream()
.map(
dbtm -> {
return datasetFactory.getDataset(
new DatasetIdentifier(
getName(defaultDatabase, defaultSchema, dbtm.qualifiedName()),
namespace),
new OpenLineage.DatasetFacetsBuilder());
})
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
}

private static String getName(String defaultDatabase, String defaultSchema, String parsedName) {
// database and schema from parser have priority over default ones
String[] parts = parsedName.split("\\.");
if (parts.length == 2) {
return String.format("%s.%s.%s", defaultDatabase, parts[0], parts[1]);
} else if (parts.length == 1) {
return String.format("%s.%s.%s", defaultDatabase, defaultSchema, parts[0]);
}
return parsedName;
}
}
1 change: 1 addition & 0 deletions integration/spark/vendor/snowflake/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ ext {

dependencies {
implementation(project(path: ":shared", configuration: activeRuntimeElementsConfiguration))
implementation("io.openlineage:openlineage-sql-java:${project.version}")

compileOnly("org.apache.spark:spark-sql_${scala}:${spark}")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
package io.openlineage.spark.agent.vendor.snowflake.lifecycle;

import io.openlineage.client.OpenLineage;
import io.openlineage.spark.agent.util.SqlUtils;
import io.openlineage.spark.api.DatasetFactory;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
Expand All @@ -17,13 +20,17 @@ public class SnowflakeDataset {

private static final Logger logger = LoggerFactory.getLogger(SnowflakeDataset.class);

public static <D extends OpenLineage.Dataset> D getDataset(
public static <D extends OpenLineage.Dataset> List<D> getDatasets(
DatasetFactory<D> factory,
String sfFullURL,
String sfDatabase,
String sfSchema,
Optional<String> dbtable,
Optional<String> query,
StructType schema) {

final String namespace =
pawel-big-lebowski marked this conversation as resolved.
Show resolved Hide resolved
String.format("%s%s", SNOWFLAKE_PREFIX, sfFullURL.replace("https://", ""));
final String tableName;
// https://docs.snowflake.com/en/user-guide/spark-connector-use#moving-data-from-snowflake-to-spark
// > Specify one of the following options for the table data to be read:
Expand All @@ -35,20 +42,15 @@ public static <D extends OpenLineage.Dataset> D getDataset(
// An improvement could be put the query string in the `DatasetFacets`
if (dbtable.isPresent()) {
tableName = dbtable.get();
String name = String.format("%s.%s.%s", sfDatabase, sfSchema, tableName);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it make sense to add method in io.openlineage.client.utils.JdbcUtils instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JDBCUtils deal with parsing JDBC URIs - this is not related to those I believe and is Snowflake specific.

return Collections.singletonList(factory.getDataset(name, namespace, schema));
} else if (query.isPresent()) {
return SqlUtils.getDatasets(
factory, query.get(), "snowflake", namespace, sfDatabase, sfSchema);
} else {
// TODO Implement same logic as the
// `io.openlineage.spark.agent.lifecycle.plan.handlers.JdbcRelationHandler`
// to extract the table name from the query string
// Optional<SqlMeta> sqlMeta = OpenLineageSql.parse(Collections.singletonList(query),
// "snowflake");
// the OpenLineageSql support the dialect:
// [snowflake](https://github.com/OpenLineage/OpenLineage/blob/99fed92fe2a8c63f24accbd8b632b15b72cce7c0/integration/sql/README.md#supported-dialects)
tableName = "COMPLEX";
logger.warn("Unable to discover Snowflake table property");
logger.warn(
"Unable to discover Snowflake table property - neither \"dbtable\" nor \"query\" option present");
}

String name = String.format("%s.%s.%s", sfDatabase, sfSchema, tableName);
String namespace = String.format("%s%s", SNOWFLAKE_PREFIX, sfFullURL.replace("https://", ""));
return factory.getDataset(name, namespace, schema);
return Collections.emptyList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import static io.openlineage.spark.agent.vendor.snowflake.Constants.SNOWFLAKE_CLASS_NAME;

import io.openlineage.client.OpenLineage;
import io.openlineage.spark.agent.util.ScalaConversionUtils;
import io.openlineage.spark.agent.vendor.snowflake.lifecycle.plan.SnowflakeSaveIntoDataSourceCommandDatasetBuilder;
import io.openlineage.spark.api.DatasetFactory;
import io.openlineage.spark.api.OpenLineageContext;
import io.openlineage.spark.api.QueryPlanVisitor;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -65,9 +65,9 @@ public List<D> apply(LogicalPlan x) {
String sfFullURL = params.sfFullURL();
Optional<String> dbtable =
Optional.<TableName>ofNullable(params.table().getOrElse(null)).map(TableName::toString);
Optional<String> query = ScalaConversionUtils.asJavaOptional(params.query());

return Collections.singletonList(
SnowflakeDataset.getDataset(
factory, sfFullURL, sfDatabase, sfSchema, dbtable, relation.schema()));
return SnowflakeDataset.getDatasets(
factory, sfFullURL, sfDatabase, sfSchema, dbtable, query, relation.schema());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,20 @@ public List<OpenLineage.OutputDataset> apply(SaveIntoDataSourceCommand command)

Map<String, String> options = ScalaConversionUtils.<String, String>fromMap(command.options());
Optional<String> dbtable = Optional.ofNullable(options.get("dbtable"));
Optional<String> query = Optional.ofNullable(options.get("query"));
String sfSchema = options.get("sfschema");
String sfUrl = options.get("sfurl");
String sfDatabase = options.get("sfdatabase");

return Collections.singletonList(
// Similar to Kafka, Snowflake also has some special handling. So we use the method
// below for extracting the dataset from Snowflake write operations.
SnowflakeDataset.getDataset(
outputDataset(), sfUrl, sfDatabase, sfSchema, dbtable, getSchema(command)
// command.schema() doesn't seem to contain the schema when tested with Azure
// Snowflake,
// so we use the helper to extract it from the logical plan.
));
return
// Similar to Kafka, Snowflake also has some special handling. So we use the method
// below for extracting the dataset from Snowflake write operations.
SnowflakeDataset.getDatasets(
outputDataset(), sfUrl, sfDatabase, sfSchema, dbtable, query, getSchema(command)
// command.schema() doesn't seem to contain the schema when tested with Azure
// Snowflake,
// so we use the helper to extract it from the logical plan.
);
} else {
return Collections.emptyList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,58 @@ public void setUp() {
(new StructType(
new StructField[] {new StructField("name", StringType$.MODULE$, false, null)})));

when(relation.params().sfFullURL())
.thenReturn("https://microsoft_partner.east-us-2.azure.snowflakecomputing.com");
}

@Test
void testApplyDbTable() {
TableName tableName = mock(TableName.class, RETURNS_DEEP_STUBS);
when(tableName.toString()).thenReturn("table");

Option<TableName> table = Option.apply(tableName);

when(relation.params().table()).thenReturn(table);

when(relation.params().sfFullURL())
.thenReturn("https://microsoft_partner.east-us-2.azure.snowflakecomputing.com");
OpenLineageContext openLineageContext =
OpenLineageContext.builder()
.sparkSession(session)
.sparkContext(session.sparkContext())
.openLineage(new OpenLineage(Versions.OPEN_LINEAGE_PRODUCER_URI))
.customEnvironmentVariables(Collections.singletonList("TEST_VAR"))
.vendors(Vendors.getVendors())
.build();

SnowflakeRelationVisitor visitor =
new SnowflakeRelationVisitor<>(openLineageContext, DatasetFactory.output(context));

LogicalRelation lr =
new LogicalRelation(
relation,
ScalaConversionUtils.fromList(
Collections.singletonList(
new AttributeReference(
FIELD_NAME,
StringType$.MODULE$,
false,
null,
ExprId.apply(1L),
ScalaConversionUtils.<String>asScalaSeqEmpty()))),
Option.empty(),
false);

List<OpenLineage.Dataset> datasets = visitor.apply(lr);

OpenLineage.Dataset ds = datasets.get(0);

assertEquals(
"snowflake://microsoft_partner.east-us-2.azure.snowflakecomputing.com", ds.getNamespace());

assertEquals("snowflake_db.snowflake_schema.table", ds.getName());
}

@Test
void testApplyDbTable() {
void testApplyQuery() {
when(relation.params().query()).thenReturn(Option.apply("select * from some_table"));

OpenLineageContext openLineageContext =
OpenLineageContext.builder()
Expand Down Expand Up @@ -103,6 +142,6 @@ void testApplyDbTable() {
assertEquals(
"snowflake://microsoft_partner.east-us-2.azure.snowflakecomputing.com", ds.getNamespace());

assertEquals("snowflake_db.snowflake_schema.table", ds.getName());
assertEquals("snowflake_db.snowflake_schema.some_table", ds.getName());
}
}