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

Optimized MERGE query for dynamic partition overwrite in Time partitioned table #1227

Merged
merged 1 commit into from
May 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -643,17 +643,33 @@ static String getQueryForTimePartitionedTable(
TimePartitioning timePartitioning) {
TimePartitioning.Type partitionType = timePartitioning.getType();
String partitionField = timePartitioning.getField();
String extractedPartitioned = "timestamp_trunc(`%s`.`%s`, %s)";
String extractedPartitionedSource =
String.format(extractedPartitioned, "source", partitionField, partitionType.toString());
String.format("timestamp_trunc(`%s`, %s)", partitionField, partitionType.toString());
String extractedPartitionedTarget =
String.format(extractedPartitioned, "target", partitionField, partitionType.toString());
return getMergeQueryForPartitionedTable(
String.format(
"timestamp_trunc(`%s`.`%s`, %s)", "target", partitionField, partitionType.toString());
FieldList allFields = destinationDefinition.getSchema().getFields();
String commaSeparatedFields =
allFields.stream().map(Field::getName).collect(Collectors.joining("`,`", "`", "`"));

String queryFormat =
"DECLARE partitions_to_delete DEFAULT "
+ "(SELECT ARRAY_AGG(DISTINCT(%s) IGNORE NULLS) FROM `%s`); \n"
+ "MERGE `%s` AS target\n"
+ "USING `%s` AS source\n"
+ "ON FALSE\n"
+ "WHEN NOT MATCHED BY SOURCE AND %s IN UNNEST(partitions_to_delete) THEN DELETE\n"
+ "WHEN NOT MATCHED BY TARGET THEN\n"
+ "INSERT(%s) VALUES(%s)";
return String.format(
queryFormat,
extractedPartitionedSource,
temporaryTableName,
destinationTableName,
temporaryTableName,
destinationDefinition,
extractedPartitionedSource,
extractedPartitionedTarget);
extractedPartitionedTarget,
commaSeparatedFields,
commaSeparatedFields);
}

static String getQueryForRangePartitionedTable(
Expand Down
Loading