You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by st...@apache.org on 2021/06/08 10:03:51 UTC
[impala] branch master updated (bb30621 -> 0c89a9c)
This is an automated email from the ASF dual-hosted git repository.
stigahuang pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git.
from bb30621 IMPALA-7501: Slim down partition metadata in LocalCatalog mode
new ce21fe7 IMPALA-10689: Implement ds_cpc_union_f() function.
new 0c89a9c IMPALA-10728: Check access privileges inside masking expressions
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
be/src/exprs/datasketches-common.cc | 13 +++
be/src/exprs/datasketches-common.h | 8 ++
be/src/exprs/datasketches-functions-ir.cc | 18 +++++
be/src/exprs/datasketches-functions.h | 7 ++
common/function-registry/impala_functions.py | 2 +
.../apache/impala/analysis/AnalysisContext.java | 51 ++++++------
.../authorization/AuthorizationStmtTest.java | 62 +++++++++++++++
.../authorization/ranger/RangerAuditLogTest.java | 26 +++---
.../org/apache/impala/common/FrontendTestBase.java | 4 +-
.../queries/QueryTest/datasketches-cpc.test | 93 +++++++++++++++++++++-
10 files changed, 247 insertions(+), 37 deletions(-)
[impala] 02/02: IMPALA-10728: Check access privileges inside
masking expressions
Posted by st...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
stigahuang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
commit 0c89a9cf0f2b642ca214e4fa68eeea9bc32ef3af
Author: stiga-huang <hu...@gmail.com>
AuthorDate: Mon Jun 7 15:59:25 2021 +0800
IMPALA-10728: Check access privileges inside masking expressions
Row-filtering/column-masking policies may introduce new expressions or
tables to the original query, e.g. a column-masking policy can reference
other columns that are not used by the original query, a row-filtering
policy can filter rows based on a subquery on other tables.
Previously, we intend to not checking accesses on these expressions and
tables. One reason is that they are hidden and users are not aware of
them. The other reason is the expressions are considered to be evaluated
by the admin (who creates these policies and has access to all
resources). The same for masking policies, i.e. if the hidden tables
have masking policies, those policies are not applied recursively. This
also avoids infinitely recursively masking.
Hive has the same behavior on masking policies. However, Hive does check
access privileges inside the masking expressions. To avoid breaking
users who may have already depended on this, we adjust our behavior to
check access privileges inside the masking expressions as well. Due to
this, audits will also be generated on accessing the additional columns.
Implementation:
Before this patch, we only collect privilege requests when analyzing the
original query. When masking expressions are applied and query rewrite
rules are applied, we re-analyze the AST without collecting privilege
requests. This patch adjusts the behavior to also collect them in the
re-analyzing pass after masking expressions are applied.
Tests
- Add FE tests.
- Adjust existing FE audit test to verify the additional audits.
- Run CORE tests.
Change-Id: I772fa2f5d189b1272e8419ed1fb5b34d373d3601
Reviewed-on: http://gerrit.cloudera.org:8080/17550
Reviewed-by: Aman Sinha <am...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
.../apache/impala/analysis/AnalysisContext.java | 51 +++++++++---------
.../authorization/AuthorizationStmtTest.java | 62 ++++++++++++++++++++++
.../authorization/ranger/RangerAuditLogTest.java | 26 +++++----
.../org/apache/impala/common/FrontendTestBase.java | 4 +-
4 files changed, 107 insertions(+), 36 deletions(-)
diff --git a/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java b/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
index 48bed79..de55559 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
@@ -501,37 +501,39 @@ public class AnalysisContext {
Lists.newArrayList(analysisResult_.stmt_.getColLabels());
// Apply column/row masking, expr, setop, and subquery rewrites.
- boolean reAnalyze = false;
+ boolean shouldReAnalyze = false;
if (authzFactory_.getAuthorizationConfig().isEnabled()) {
- reAnalyze = analysisResult_.stmt_.resolveTableMask(analysisResult_.analyzer_);
+ shouldReAnalyze = analysisResult_.stmt_.resolveTableMask(analysisResult_.analyzer_);
// If any catalog table/view is replaced by table masking views, we need to
// resolve them. Also re-analyze the SlotRefs to reference the output exprs of
// the table masking views.
- if (reAnalyze) {
- reAnalyzeWithoutPrivChecks(stmtTableCache, authzCtx, origResultTypes,
- origColLabels);
+ if (shouldReAnalyze) {
+ // To be consistent with Hive, privilege requests introduced by the masking views
+ // should also be collected (IMPALA-10728).
+ reAnalyze(stmtTableCache, authzCtx, origResultTypes, origColLabels,
+ /*collectPrivileges*/ true);
}
- reAnalyze = false;
+ shouldReAnalyze = false;
}
ExprRewriter rewriter = analysisResult_.analyzer_.getExprRewriter();
if (analysisResult_.requiresExprRewrite()) {
rewriter.reset();
analysisResult_.stmt_.rewriteExprs(rewriter);
- reAnalyze = rewriter.changed();
+ shouldReAnalyze = rewriter.changed();
}
if (analysisResult_.requiresSubqueryRewrite()) {
new StmtRewriter.SubqueryRewriter().rewrite(analysisResult_);
- reAnalyze = true;
+ shouldReAnalyze = true;
}
if (analysisResult_.requiresSetOperationRewrite()) {
new StmtRewriter().rewrite(analysisResult_);
- reAnalyze = true;
+ shouldReAnalyze = true;
}
if (analysisResult_.requiresAcidComplexScanRewrite()) {
new StmtRewriter.AcidRewriter().rewrite(analysisResult_);
- reAnalyze = true;
+ shouldReAnalyze = true;
}
- if (!reAnalyze) return;
+ if (!shouldReAnalyze) return;
// For SetOperationStmt we must replace the query statement with the rewritten version
// before re-analysis.
@@ -544,13 +546,14 @@ public class AnalysisContext {
}
}
- reAnalyzeWithoutPrivChecks(stmtTableCache, authzCtx, origResultTypes, origColLabels);
+ reAnalyze(stmtTableCache, authzCtx, origResultTypes, origColLabels,
+ /*collectPrivileges*/ false);
Preconditions.checkState(!analysisResult_.requiresSubqueryRewrite());
}
- private void reAnalyzeWithoutPrivChecks(StmtTableCache stmtTableCache,
- AuthorizationContext authzCtx, List<Type> origResultTypes,
- List<String> origColLabels) throws AnalysisException {
+ private void reAnalyze(StmtTableCache stmtTableCache, AuthorizationContext authzCtx,
+ List<Type> origResultTypes, List<String> origColLabels, boolean collectPrivileges)
+ throws AnalysisException {
boolean isExplain = analysisResult_.isExplainStmt();
// Some expressions, such as function calls with constant arguments, can get
// folded into literals. Since literals do not require privilege requests, we
@@ -561,17 +564,20 @@ public class AnalysisContext {
// Re-analyze the stmt with a new analyzer.
analysisResult_.analyzer_ = createAnalyzer(stmtTableCache, authzCtx);
- // We restore the privileges collected in the first pass below. So, no point in
- // collecting them again.
- analysisResult_.analyzer_.setEnablePrivChecks(false);
+ // Restore privilege requests found during the previous pass
+ for (PrivilegeRequest req : origPrivReqs) {
+ analysisResult_.analyzer_.registerPrivReq(req);
+ }
+ // Only collect privilege requests in need.
+ analysisResult_.analyzer_.setEnablePrivChecks(collectPrivileges);
analysisResult_.stmt_.reset();
try {
analysisResult_.stmt_.analyze(analysisResult_.analyzer_);
- analysisResult_.analyzer_.setEnablePrivChecks(true); // restore
+ analysisResult_.analyzer_.setEnablePrivChecks(true); // Always restore
} catch (AnalysisException e) {
LOG.error(String.format("Error analyzing the rewritten query.\n" +
"Original SQL: %s\nRewritten SQL: %s", analysisResult_.stmt_.toSql(),
- analysisResult_.stmt_.toSql(REWRITTEN)));
+ analysisResult_.stmt_.toSql(REWRITTEN)), e);
throw e;
}
// Restore the original result types and column labels.
@@ -580,11 +586,6 @@ public class AnalysisContext {
if (LOG.isTraceEnabled()) {
LOG.trace("Rewritten SQL: " + analysisResult_.stmt_.toSql(REWRITTEN));
}
-
- // Restore privilege requests found during the first pass
- for (PrivilegeRequest req : origPrivReqs) {
- analysisResult_.analyzer_.registerPrivReq(req);
- }
if (isExplain) analysisResult_.stmt_.setIsExplain();
}
diff --git a/fe/src/test/java/org/apache/impala/authorization/AuthorizationStmtTest.java b/fe/src/test/java/org/apache/impala/authorization/AuthorizationStmtTest.java
index ce2b6be..9b1f31d 100644
--- a/fe/src/test/java/org/apache/impala/authorization/AuthorizationStmtTest.java
+++ b/fe/src/test/java/org/apache/impala/authorization/AuthorizationStmtTest.java
@@ -3212,6 +3212,68 @@ public class AuthorizationStmtTest extends AuthorizationTestBase {
}
/**
+ * Validates access privileges are checked inside column-masking/row-filtering
+ * expressions (IMPALA-10728).
+ */
+ @Test
+ public void testPrivInMaskingExprs() throws Exception {
+ // Create a row-filter that contains a subquery on another table. Verify that accesses
+ // inside the subquery are also checked.
+ try {
+ createRowFilteringPolicy("alltypes_subquery_filter", "functional", "alltypes",
+ user_.getShortName(), "id in (select id from functional.alltypestiny)");
+ String[] queries = {
+ "select * from functional.alltypes",
+ "select id from functional.alltypes",
+ "select int_col from functional.alltypes"
+ };
+ for (String q : queries) {
+ authorize(q)
+ .ok(onTable("functional", "alltypes", TPrivilegeLevel.SELECT),
+ onTable("functional", "alltypestiny", TPrivilegeLevel.SELECT))
+ .ok(onTable("functional", "alltypes", TPrivilegeLevel.SELECT),
+ onColumn("functional", "alltypestiny", "id", TPrivilegeLevel.SELECT))
+ // Can't read the table if missing SELECT privilege on column "id" of table
+ // "functional.alltypestiny".
+ .error(selectError("functional.alltypestiny"),
+ onTable("functional", "alltypes", TPrivilegeLevel.SELECT))
+ .error(selectError("functional.alltypestiny"),
+ onTable("functional", "alltypes", TPrivilegeLevel.SELECT),
+ onColumn("functional", "alltypestiny", "int_col",
+ TPrivilegeLevel.SELECT));
+ }
+ } finally {
+ deleteRangerPolicy("alltypes_subquery_filter");
+ }
+ // Create a column-masking policy that masks a column using another column. Verify
+ // that accesses on both columns are checked. Create a column-masking policy that
+ // masks a column to NULL. Verify that access on the column are still checked.
+ try {
+ createColumnMaskingPolicy("alltypes_replace_id", "functional", "alltypes", "id",
+ user_.getShortName(), "CUSTOM", "int_col");
+ createColumnMaskingPolicy("alltypes_nullify_str", "functional", "alltypes",
+ "string_col", user_.getShortName(), "MASK_NULL", /*maskExpr*/null);
+ authorize("select id from functional.alltypes")
+ .ok(onTable("functional", "alltypes", TPrivilegeLevel.SELECT))
+ .ok(onColumn("functional", "alltypes", "id", TPrivilegeLevel.SELECT),
+ onColumn("functional", "alltypes", "int_col", TPrivilegeLevel.SELECT))
+ .error(selectError("functional.alltypes"),
+ onColumn("functional", "alltypes", "id", TPrivilegeLevel.SELECT))
+ .error(selectError("functional.alltypes"),
+ onColumn("functional", "alltypes", "int_col", TPrivilegeLevel.SELECT));
+ // Although string_col is masked as NULL, we still require access privilege on it.
+ authorize("select bool_col, string_col from functional.alltypes")
+ .ok(onColumn("functional", "alltypes", "bool_col", TPrivilegeLevel.SELECT),
+ onColumn("functional", "alltypes", "string_col", TPrivilegeLevel.SELECT))
+ .error(selectError("functional.alltypes"),
+ onColumn("functional", "alltypes", "bool_col", TPrivilegeLevel.SELECT));
+ } finally {
+ deleteRangerPolicy("alltypes_replace_id");
+ deleteRangerPolicy("alltypes_nullify_str");
+ }
+ }
+
+ /**
* Validates Ranger's object ownership privileges. Note that we no longer have to add a
* policy to the Ranger server to explicitly grant a user the access privileges of the
* resources if the user is the owner of the resources.
diff --git a/fe/src/test/java/org/apache/impala/authorization/ranger/RangerAuditLogTest.java b/fe/src/test/java/org/apache/impala/authorization/ranger/RangerAuditLogTest.java
index e2d8065..2e75393 100644
--- a/fe/src/test/java/org/apache/impala/authorization/ranger/RangerAuditLogTest.java
+++ b/fe/src/test/java/org/apache/impala/authorization/ranger/RangerAuditLogTest.java
@@ -581,43 +581,49 @@ public class RangerAuditLogTest extends AuthorizationTestBase {
assertNotEquals("Illegal policy id", -1, policyIds[i]);
}
- // Verify row filter audits. Note that columns used in the row filter won't create
+ // Verify row filter audits. Note that columns used in the row filter also creates
// column access audits.
authzOk(events -> {
- assertEquals(3, events.size());
+ assertEquals(4, events.size());
assertEquals("select bool_col from functional.alltypestiny",
events.get(0).getRequestData());
assertEventEquals("@table", "select", "functional/alltypestiny", 1,
events.get(0));
assertEventEquals("@column", "select", "functional/alltypestiny/bool_col", 1,
events.get(1));
- assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ assertEventEquals("@column", "select", "functional/alltypestiny/id", 1,
events.get(2));
- assertEquals(events.get(2).getPolicyId(), policyIds[0]);
+ assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ events.get(3));
+ assertEquals(events.get(3).getPolicyId(), policyIds[0]);
}, "select bool_col from functional.alltypestiny",
onTable("functional", "alltypestiny", TPrivilegeLevel.SELECT));
authzOk(events -> {
- assertEquals(2, events.size());
+ assertEquals(3, events.size());
assertEquals("select 1 from functional.alltypestiny",
events.get(0).getRequestData());
assertEventEquals("@table", "select", "functional/alltypestiny", 1,
events.get(0));
- assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ assertEventEquals("@column", "select", "functional/alltypestiny/id", 1,
events.get(1));
- assertEquals(events.get(1).getPolicyId(), policyIds[0]);
+ assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ events.get(2));
+ assertEquals(events.get(2).getPolicyId(), policyIds[0]);
}, "select 1 from functional.alltypestiny",
onTable("functional", "alltypestiny", TPrivilegeLevel.SELECT));
authzOk(events -> {
- assertEquals(2, events.size());
+ assertEquals(3, events.size());
assertEquals("select count(*) from functional.alltypestiny",
events.get(0).getRequestData());
assertEventEquals("@table", "select", "functional/alltypestiny", 1,
events.get(0));
- assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ assertEventEquals("@column", "select", "functional/alltypestiny/id", 1,
events.get(1));
- assertEquals(events.get(1).getPolicyId(), policyIds[0]);
+ assertEventEquals("@table", "row_filter", "functional/alltypestiny", 1,
+ events.get(2));
+ assertEquals(events.get(2).getPolicyId(), policyIds[0]);
}, "select count(*) from functional.alltypestiny",
onTable("functional", "alltypestiny", TPrivilegeLevel.SELECT));
diff --git a/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java b/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
index d32baea..bdf0815 100644
--- a/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
+++ b/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
@@ -61,6 +61,7 @@ import org.apache.impala.thrift.TAccessEvent;
import org.apache.impala.thrift.TQueryOptions;
import org.apache.impala.thrift.TSessionState;
import org.apache.impala.util.EventSequence;
+import org.apache.impala.util.TSessionStateUtil;
import org.junit.Assert;
import com.google.common.base.Preconditions;
@@ -315,8 +316,9 @@ public class FrontendTestBase extends AbstractFrontendTest {
try (FrontendProfile.Scope scope = FrontendProfile.createNewWithScope()) {
ctx.getQueryCtx().getClient_request().setStmt(stmt);
StatementBase parsedStmt = Parser.parse(stmt, ctx.getQueryOptions());
+ User user = new User(TSessionStateUtil.getEffectiveUser(ctx.getQueryCtx().session));
StmtMetadataLoader mdLoader =
- new StmtMetadataLoader(fe, ctx.getQueryCtx().session.database, null);
+ new StmtMetadataLoader(fe, ctx.getQueryCtx().session.database, null, user);
StmtTableCache stmtTableCache = mdLoader.loadTables(parsedStmt);
return ctx.analyzeAndAuthorize(parsedStmt, stmtTableCache, fe.getAuthzChecker());
}
[impala] 01/02: IMPALA-10689: Implement ds_cpc_union_f() function.
Posted by st...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
stigahuang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
commit ce21fe74b806757a1c9e52c614db95a76283c78c
Author: Fucun Chu <ch...@hotmail.com>
AuthorDate: Wed May 12 16:15:38 2021 +0800
IMPALA-10689: Implement ds_cpc_union_f() function.
This function receives two strings that are serialized Apache
DataSketches CPC sketches. Union two sketches and returns the
resulting sketch of union.
Example:
select ds_cpc_estimate(ds_cpc_union_f(sketch1, sketch2))
from sketch_tbl;
+---------------------------------------------------+
| ds_cpc_estimate(ds_cpc_union_f(sketch1, sketch2)) |
+---------------------------------------------------+
| 15 |
+---------------------------------------------------+
Change-Id: Ib5c616316bf2bf2ff437678e9a44a15339920150
Reviewed-on: http://gerrit.cloudera.org:8080/17440
Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
be/src/exprs/datasketches-common.cc | 13 +++
be/src/exprs/datasketches-common.h | 8 ++
be/src/exprs/datasketches-functions-ir.cc | 18 +++++
be/src/exprs/datasketches-functions.h | 7 ++
common/function-registry/impala_functions.py | 2 +
.../queries/QueryTest/datasketches-cpc.test | 93 +++++++++++++++++++++-
6 files changed, 140 insertions(+), 1 deletion(-)
diff --git a/be/src/exprs/datasketches-common.cc b/be/src/exprs/datasketches-common.cc
index cfb5a68..c3e0b3b 100644
--- a/be/src/exprs/datasketches-common.cc
+++ b/be/src/exprs/datasketches-common.cc
@@ -84,6 +84,19 @@ StringVal StringStreamToStringVal(FunctionContext* ctx, const stringstream& str_
return dst;
}
+bool update_sketch_to_cpc_union(FunctionContext* ctx,
+ const StringVal& serialized_sketch, datasketches::cpc_union& union_sketch) {
+ if (!serialized_sketch.is_null && serialized_sketch.len > 0) {
+ datasketches::cpc_sketch sketch(DS_CPC_SKETCH_CONFIG);
+ if (!DeserializeDsSketch(serialized_sketch, &sketch)) {
+ LogSketchDeserializationError(ctx);
+ return false;
+ }
+ union_sketch.update(sketch);
+ }
+ return true;
+}
+
bool update_sketch_to_theta_union(FunctionContext* ctx,
const StringVal& serialized_sketch, datasketches::theta_union& sketch) {
if (!serialized_sketch.is_null && serialized_sketch.len > 0) {
diff --git a/be/src/exprs/datasketches-common.h b/be/src/exprs/datasketches-common.h
index 7187399..0cf5273 100644
--- a/be/src/exprs/datasketches-common.h
+++ b/be/src/exprs/datasketches-common.h
@@ -22,6 +22,7 @@
#include "common/status.h"
#include "thirdparty/datasketches/hll.hpp"
+#include "thirdparty/datasketches/cpc_union.hpp"
#include "thirdparty/datasketches/theta_union.hpp"
#include "thirdparty/datasketches/theta_intersection.hpp"
#include "udf/udf.h"
@@ -65,6 +66,13 @@ bool DeserializeDsSketch(const StringVal& serialized_sketch, T* sketch)
StringVal StringStreamToStringVal(FunctionContext* ctx,
const std::stringstream& str_stream);
+/// Helper function that receives a serialized DataSketches CPC sketch in
+/// 'serialized_sketch', deserializes it and update the deserialized sketch to 'sketch'.
+/// Returns false if the deserialization fails (the error log will be written),
+/// true otherwise.
+bool update_sketch_to_cpc_union(FunctionContext* ctx, const StringVal& serialized_sketch,
+ datasketches::cpc_union& sketch);
+
/// Helper function that receives a serialized DataSketches Theta sketch in
/// 'serialized_sketch', deserializes it and update the deserialized sketch to 'sketch'.
/// Returns false if the deserialization fails (the error log will be written),
diff --git a/be/src/exprs/datasketches-functions-ir.cc b/be/src/exprs/datasketches-functions-ir.cc
index f741edc..4315fa3 100644
--- a/be/src/exprs/datasketches-functions-ir.cc
+++ b/be/src/exprs/datasketches-functions-ir.cc
@@ -21,6 +21,7 @@
#include "gutil/strings/substitute.h"
#include "thirdparty/datasketches/hll.hpp"
#include "thirdparty/datasketches/cpc_sketch.hpp"
+#include "thirdparty/datasketches/cpc_union.hpp"
#include "thirdparty/datasketches/theta_sketch.hpp"
#include "thirdparty/datasketches/theta_union.hpp"
#include "thirdparty/datasketches/theta_intersection.hpp"
@@ -134,6 +135,23 @@ StringVal DataSketchesFunctions::DsCpcStringify(
return dst;
}
+StringVal DataSketchesFunctions::DsCpcUnionF(FunctionContext* ctx,
+ const StringVal& first_serialized_sketch, const StringVal& second_serialized_sketch) {
+ datasketches::cpc_union union_sketch;
+ // Update two sketches to cpc_union
+ if (!update_sketch_to_cpc_union(ctx, first_serialized_sketch, union_sketch)) {
+ return StringVal::null();
+ }
+ if (!update_sketch_to_cpc_union(ctx, second_serialized_sketch, union_sketch)) {
+ return StringVal::null();
+ }
+ // Result
+ datasketches::cpc_sketch sketch = union_sketch.get_result();
+ std::stringstream serialized_input;
+ sketch.serialize(serialized_input);
+ return StringStreamToStringVal(ctx, serialized_input);
+}
+
BigIntVal DataSketchesFunctions::DsThetaEstimate(
FunctionContext* ctx, const StringVal& serialized_sketch) {
if (serialized_sketch.is_null || serialized_sketch.len == 0) return 0;
diff --git a/be/src/exprs/datasketches-functions.h b/be/src/exprs/datasketches-functions.h
index 2477189..3f44793 100644
--- a/be/src/exprs/datasketches-functions.h
+++ b/be/src/exprs/datasketches-functions.h
@@ -76,6 +76,13 @@ public:
static StringVal DsCpcStringify(
FunctionContext* ctx, const StringVal& serialized_sketch);
+ /// 'first_serialized_sketch' and 'second_serialized_sketch' are both expected as
+ /// serialized Apache DataSketches CPC sketches. If they are not, then the query
+ /// fails. Union two sketches and returns the resulting sketch of union.
+ static StringVal DsCpcUnionF(FunctionContext* ctx,
+ const StringVal& first_serialized_sketch,
+ const StringVal& second_serialized_sketch);
+
/// 'serialized_sketch' is expected as a serialized Apache DataSketches Theta sketch.
/// If it is not, then the query fails. Otherwise, returns the count(distinct) estimate
/// from the sketch.
diff --git a/common/function-registry/impala_functions.py b/common/function-registry/impala_functions.py
index 7c36995..a6b4914 100644
--- a/common/function-registry/impala_functions.py
+++ b/common/function-registry/impala_functions.py
@@ -1011,6 +1011,8 @@ visible_functions = [
'_ZN6impala21DataSketchesFunctions13DsCpcEstimateEPN10impala_udf15FunctionContextERKNS1_9StringValE'],
[['ds_cpc_stringify'], 'STRING', ['STRING'],
'_ZN6impala21DataSketchesFunctions14DsCpcStringifyEPN10impala_udf15FunctionContextERKNS1_9StringValE'],
+ [['ds_cpc_union_f'], 'STRING', ['STRING', 'STRING'],
+ '_ZN6impala21DataSketchesFunctions11DsCpcUnionFEPN10impala_udf15FunctionContextERKNS1_9StringValES6_'],
[['ds_theta_estimate'], 'BIGINT', ['STRING'],
'_ZN6impala21DataSketchesFunctions15DsThetaEstimateEPN10impala_udf15FunctionContextERKNS1_9StringValE'],
[['ds_theta_exclude'], 'STRING', ['STRING', 'STRING'],
diff --git a/testdata/workloads/functional-query/queries/QueryTest/datasketches-cpc.test b/testdata/workloads/functional-query/queries/QueryTest/datasketches-cpc.test
index 4c1ce48..1ee5d53 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/datasketches-cpc.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/datasketches-cpc.test
@@ -282,4 +282,95 @@ select ds_cpc_stringify(ds_cpc_sketch(float_col)) from functional_parquet.alltyp
row_regex: .*### CPC sketch summary:.*lg_k.*seed hash.*C.*flavor.*### End sketch summary.*
---- TYPES
STRING
-====
\ No newline at end of file
+====
+---- QUERY
+# Checks that unioning a valid sketch with a null value result the valid sketch being returned.
+select
+ ds_cpc_estimate(ds_cpc_union_f(date_sketch, null)),
+ ds_cpc_estimate(ds_cpc_union_f(null, float_sketch))
+from cpc_sketch_store;
+---- TYPES
+BIGINT,BIGINT
+---- RESULTS
+3,10
+3,10
+3,10
+3,10
+====
+---- QUERY
+# Check that ds_cpc_union_f() returns an empty sketch for an empty sketch.
+select ds_cpc_estimate(ds_cpc_union_f(ds_cpc_sketch(cast(f2 as float)), null))
+from functional_parquet.emptytable;
+---- TYPES
+BIGINT
+---- RESULTS
+0
+====
+---- QUERY
+# Checks that ds_cpc_union_f() returns an empty sketch for NULL inputs.
+select ds_cpc_estimate(ds_cpc_union_f(null_str, some_nulls)) from functional_parquet.nullrows
+where id='b';
+---- TYPES
+BIGINT
+---- RESULTS
+0
+====
+---- QUERY
+# ds_cpc_union_f() returns an error if it receives an invalid serialized sketch.
+select ds_cpc_union_f(null, date_string_col) from functional_parquet.alltypestiny
+where id=1;
+---- CATCH
+UDF ERROR: Unable to deserialize sketch.
+====
+---- QUERY
+# ds_cpc_union_f() returns an error if it receives an invalid serialized sketch.
+select ds_cpc_union_f(date_string_col, null) from functional_parquet.alltypestiny
+where id=1;
+---- CATCH
+UDF ERROR: Unable to deserialize sketch.
+====
+---- QUERY
+# Get the same sketches from Impala and Hive and put them into the same table (different
+# column prefix). When we get the estimates from the unions of these sketches the expectation
+# is to get the same results as if these sketches were used separately to get the estimates.
+# However, for string types (STRING, CHAR, VARCHAR) we see the numbers doubling up because
+# of the difference between how Impala and Hive uses these types. Like IMPALA-9939.
+create table cpc_sketches_impala_hive2 (
+i_ti string,i_i string,i_bi string,i_f string,i_d string,i_s string,i_c string,i_v string,
+i_nc string,
+h_ti string,h_i string,h_bi string,h_f string,h_d string,h_s string,h_c string,h_v string,
+h_nc string) stored as parquet;
+insert overwrite cpc_sketches_impala_hive2 select
+i.ti i_ti, i.i i_i, i.bi i_bi, i.f i_f, i.d i_d, i.s i_s, i.c i_c, i.v i_v,i.nc i_nc,
+h.ti h_ti, h.i h_i, h.bi h_bi, h.f h_f, h.d h_d, h.s h_s, h.c h_c, h.v h_v,h.nc h_nc
+from cpc_sketches_from_impala i, cpc_sketches_from_hive h;
+select
+ ds_cpc_estimate(ds_cpc_union_f(i_ti, h_ti)) as ti,
+ ds_cpc_estimate(ds_cpc_union_f(i_i, h_i)) as i,
+ ds_cpc_estimate(ds_cpc_union_f(i_bi, h_bi)) as bi,
+ ds_cpc_estimate(ds_cpc_union_f(i_f, h_f)) as f,
+ ds_cpc_estimate(ds_cpc_union_f(i_d, h_d)) as d,
+ ds_cpc_estimate(ds_cpc_union_f(i_s, h_s)) as s,
+ ds_cpc_estimate(ds_cpc_union_f(i_c, h_c)) as c,
+ ds_cpc_estimate(ds_cpc_union_f(i_v, h_v)) as v,
+ ds_cpc_estimate(ds_cpc_union_f(i_nc, h_nc)) as nc
+from cpc_sketches_impala_hive2;
+---- TYPES
+BIGINT,BIGINT,BIGINT,BIGINT,BIGINT,BIGINT,BIGINT,BIGINT,BIGINT
+---- RESULTS
+5,7,6,6,7,8,8,6,0
+====
+---- QUERY
+# Union two sketches from different columns of sketch_intermediate.
+create table sketch_input (id1 int, id2 int);
+insert into table sketch_input values
+ (1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 12), (7, 14), (8, 16), (9, 18), (10, 20);
+create table sketch_intermediate (sketch1 string, sketch2 string) stored as parquet;
+insert overwrite sketch_intermediate
+ select ds_cpc_sketch(id1), ds_cpc_sketch(id2) from sketch_input;
+select ds_cpc_estimate(ds_cpc_union_f(sketch1, sketch2)) from sketch_intermediate;
+---- TYPES
+BIGINT
+---- RESULTS
+15
+====