Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
@@ -0,0 +1,97 @@
/*
* Licensed 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 io.trino.plugin.teradata;

import io.trino.matching.Capture;
import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.plugin.base.expression.ConnectorExpressionRule;
import io.trino.plugin.jdbc.QueryParameter;
import io.trino.plugin.jdbc.expression.ParameterizedExpression;
import io.trino.spi.expression.Call;
import io.trino.spi.expression.ConnectorExpression;
import io.trino.spi.expression.FunctionName;

import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import static io.trino.matching.Capture.newCapture;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.argument;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.argumentCount;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.call;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.expression;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.functionName;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;

public class RewriteSubstring
implements ConnectorExpressionRule<Call, ParameterizedExpression>
{
private static final Capture<ConnectorExpression> VALUE = newCapture();
private static final Capture<ConnectorExpression> START = newCapture();
private static final Capture<ConnectorExpression> LENGTH = newCapture();

Check failure on line 44 in plugin/trino-teradata/src/main/java/io/trino/plugin/teradata/RewriteSubstring.java

View workflow job for this annotation

GitHub Actions / error-prone-checks

The field 'LENGTH' is never read.

Check failure on line 44 in plugin/trino-teradata/src/main/java/io/trino/plugin/teradata/RewriteSubstring.java

View workflow job for this annotation

GitHub Actions / error-prone-checks

The field 'LENGTH' is never read.
Comment thread
sc250072 marked this conversation as resolved.
Outdated

public static final FunctionName SUBSTRING_FUNCTION_NAME = new FunctionName("substring");

@Override
public Pattern<Call> getPattern()
{
return call()
.with(functionName().equalTo(SUBSTRING_FUNCTION_NAME))
.with(argumentCount().matching(count -> count == 2 || count == 3))
.with(argument(0).matching(expression().capturedAs(VALUE)))
.with(argument(1).matching(expression().capturedAs(START)));
}

@Override
public Optional<ParameterizedExpression> rewrite(Call call, Captures captures, RewriteContext<ParameterizedExpression> context)
{
Optional<ParameterizedExpression> value = context.defaultRewrite(captures.get(VALUE));
Optional<ParameterizedExpression> start = context.defaultRewrite(captures.get(START));

if (value.isEmpty() || start.isEmpty()) {
return Optional.empty();
}

if (call.getArguments().size() == 3) {
// Optional<ParameterizedExpression> length = context.defaultRewrite(captures.get(LENGTH));
Comment thread
sc250072 marked this conversation as resolved.
Outdated
Optional<ParameterizedExpression> length = context.defaultRewrite(call.getArguments().get(2));
if (length.isEmpty()) {
return Optional.empty();
}

return Optional.of(new ParameterizedExpression(
format("SUBSTRING(%s FROM %s FOR %s)",
value.get().expression(),
start.get().expression(),
length.get().expression()),
combineParameters(value.get(), start.get(), length.get())));
}
else {
return Optional.of(new ParameterizedExpression(
format("SUBSTRING(%s FROM %s)",
value.get().expression(),
start.get().expression()),
combineParameters(value.get(), start.get())));
}
}

private List<QueryParameter> combineParameters(ParameterizedExpression... expressions)
{
return Stream.of(expressions)
.flatMap(expr -> expr.parameters().stream())
.collect(toList());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Licensed 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 io.trino.plugin.teradata;

import com.google.common.collect.ImmutableList;
import io.trino.matching.Capture;
import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.plugin.base.projection.ProjectFunctionRule;
import io.trino.plugin.jdbc.JdbcColumnHandle;
import io.trino.plugin.jdbc.JdbcExpression;
import io.trino.plugin.jdbc.JdbcTypeHandle;
import io.trino.plugin.jdbc.QueryParameter;
import io.trino.plugin.jdbc.expression.ParameterizedExpression;
import io.trino.spi.connector.ConnectorTableHandle;
import io.trino.spi.expression.Call;
import io.trino.spi.expression.ConnectorExpression;
import io.trino.spi.expression.FunctionName;
import io.trino.spi.expression.Variable;
import io.trino.spi.type.VarcharType;

import java.sql.JDBCType;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

import static io.trino.matching.Capture.newCapture;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.argument;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.argumentCount;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.call;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.expression;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.functionName;
import static io.trino.plugin.base.expression.ConnectorExpressionPatterns.type;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;

public class RewriteSubstringFunction
implements ProjectFunctionRule<JdbcExpression, ParameterizedExpression>
{
private static final Capture<ConnectorExpression> VALUE = newCapture();

private static final Pattern<Call> PATTERN = call()
.with(functionName().equalTo(new FunctionName("substring")))
.with(type().matching(type -> type instanceof VarcharType))
.with(argumentCount().matching(count -> count >= 2 && count <= 3))
.with(argument(0).matching(expression().capturedAs(VALUE).with(type().matching(type -> type instanceof VarcharType))));

@Override
public Pattern<? extends ConnectorExpression> getPattern()
{
return PATTERN;
}

@Override
public Optional<JdbcExpression> rewrite(ConnectorTableHandle handle, ConnectorExpression projectionExpression, Captures captures, RewriteContext<ParameterizedExpression> context)
{
Call call = (Call) projectionExpression;
ConnectorExpression valueExpression = captures.get(VALUE);

// Get JDBC type handle for the value expression
JdbcTypeHandle typeHandle = getTypeHandle(valueExpression, context);
if (typeHandle == null) {
return Optional.empty();
}

// Only rewrite for plain VARCHAR JDBC type named "varchar"
if (JDBCType.valueOf(typeHandle.jdbcType()) != JDBCType.VARCHAR ||
Comment thread
sc250072 marked this conversation as resolved.
!typeHandle.jdbcTypeName().map(name -> name.equalsIgnoreCase("varchar")).orElse(false)) {
return Optional.empty();
}

Optional<ParameterizedExpression> value = context.rewriteExpression(valueExpression);
if (value.isEmpty()) {
return Optional.empty();
}

String expression;
List<QueryParameter> parameters;
if (call.getArguments().size() == 2) {
// Two argument SUBSTRING(value, start)
Optional<ParameterizedExpression> start = context.rewriteExpression(call.getArguments().get(1));
if (start.isEmpty()) {
return Optional.empty();
}
expression = format("SUBSTRING(%s FROM %s)", value.get().expression(), start.get().expression());
parameters = combineParameters(value.get(), start.get());
}
else if (call.getArguments().size() == 3) {
// Three argument SUBSTRING(value, start, length)
Optional<ParameterizedExpression> start = context.rewriteExpression(call.getArguments().get(1));
Optional<ParameterizedExpression> length = context.rewriteExpression(call.getArguments().get(2));
if (start.isEmpty() || length.isEmpty()) {
return Optional.empty();
}
expression = format("SUBSTRING(%s FROM %s FOR %s)",
value.get().expression(),
start.get().expression(),
length.get().expression());
parameters = combineParameters(value.get(), start.get(), length.get());
}
else {
return Optional.empty();
}

return Optional.of(new JdbcExpression(expression, ImmutableList.copyOf(parameters), typeHandle));
}

private JdbcTypeHandle getTypeHandle(ConnectorExpression expression, RewriteContext<ParameterizedExpression> context)
{
if (expression instanceof Variable variable) {
return ((JdbcColumnHandle) context.getAssignment(variable.getName())).getJdbcTypeHandle();
}
// For non-variable expressions, we might need to derive the type handle differently
// This is a simplified approach - you might need more sophisticated type handling
return new JdbcTypeHandle(JDBCType.VARCHAR.getVendorTypeNumber(), Optional.of("varchar"), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
}

private List<QueryParameter> combineParameters(ParameterizedExpression... expressions)
{
return Stream.of(expressions)
.flatMap(expr -> expr.parameters().stream())
.collect(toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import io.trino.plugin.base.aggregation.AggregateFunctionRule;
import io.trino.plugin.base.expression.ConnectorExpressionRewriter;
import io.trino.plugin.base.mapping.IdentifierMapping;
import io.trino.plugin.base.projection.ProjectFunctionRewriter;
import io.trino.plugin.base.projection.ProjectFunctionRule;
import io.trino.plugin.jdbc.BaseJdbcClient;
import io.trino.plugin.jdbc.BaseJdbcConfig;
import io.trino.plugin.jdbc.CaseSensitivity;
Expand Down Expand Up @@ -80,8 +82,6 @@
import io.trino.spi.connector.JoinType;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.expression.ConnectorExpression;
import io.trino.spi.predicate.Domain;
import io.trino.spi.predicate.ValueSet;
import io.trino.spi.statistics.ColumnStatistics;
import io.trino.spi.statistics.Estimate;
import io.trino.spi.statistics.TableStatistics;
Expand Down Expand Up @@ -146,7 +146,6 @@
import static io.trino.plugin.jdbc.CaseSensitivity.CASE_SENSITIVE;
import static io.trino.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
import static io.trino.plugin.jdbc.JdbcJoinPushdownUtil.implementJoinCostAware;
import static io.trino.plugin.jdbc.JdbcMetadataSessionProperties.getDomainCompactionThreshold;
import static io.trino.plugin.jdbc.PredicatePushdownController.CASE_INSENSITIVE_CHARACTER_PUSHDOWN;
import static io.trino.plugin.jdbc.PredicatePushdownController.DISABLE_PUSHDOWN;
import static io.trino.plugin.jdbc.PredicatePushdownController.FULL_PUSHDOWN;
Expand Down Expand Up @@ -224,26 +223,7 @@ public class TeradataClient
* Predicate pushdown controller for Teradata string columns.
* Ensures correct pushdown behavior for case-sensitive and case-insensitive domains.
*/
private static final PredicatePushdownController TERADATA_STRING_PUSHDOWN = (session, domain) -> {
// 1. NULL-only filters are always safe
if (domain.isOnlyNull()) {
return FULL_PUSHDOWN.apply(session, domain);
}

Domain simplifiedDomain = domain.simplify(getDomainCompactionThreshold(session));
if (!simplifiedDomain.getValues().isDiscreteSet()) {
// Push down inequality predicate
ValueSet complement = simplifiedDomain.getValues().complement();
if (complement.isDiscreteSet()) {
return FULL_PUSHDOWN.apply(session, simplifiedDomain);
}
// Domain#simplify can turn a discrete set into a range predicate
// Push down of range predicate for varchar/char types could lead to incorrect results
// when the remote database is case-insensitive
return DISABLE_PUSHDOWN.apply(session, domain);
}
return FULL_PUSHDOWN.apply(session, simplifiedDomain);
};
private static final PredicatePushdownController TERADATA_STRING_PUSHDOWN = FULL_PUSHDOWN;
/**
* Maximum fallback number of distinct values (NDV) for statistics estimation.
*/
Expand Down Expand Up @@ -277,6 +257,8 @@ public class TeradataClient
*/
private AggregateFunctionRewriter<JdbcExpression, ?> aggregateFunctionRewriter;

private ProjectFunctionRewriter<JdbcExpression, ParameterizedExpression> projectFunctionRewriter;

/**
* Constructs a new TeradataClient instance.
*
Expand All @@ -296,6 +278,7 @@ public TeradataClient(BaseJdbcConfig config, TeradataConfig teradataConfig, Jdbc
this.statisticsEnabled = statisticsConfig.isEnabled();
buildExpressionRewriter();
buildAggregateRewriter();
buildProjectionFunctionRewriter();
}

/**
Expand Down Expand Up @@ -928,6 +911,15 @@ public void dropNotNullConstraint(ConnectorSession session, JdbcTableHandle hand
throw new TrinoException(NOT_SUPPORTED, "This connector does not support dropping a not null constraint");
}

private void buildProjectionFunctionRewriter()
{
this.projectFunctionRewriter = new ProjectFunctionRewriter<>(
connectorExpressionRewriter,
com.google.common.collect.ImmutableSet.<ProjectFunctionRule<JdbcExpression, ParameterizedExpression>>builder()
.add(new RewriteSubstringFunction())
.build());
}

/**
* Builds the expression rewriter for translating connector expressions
* into SQL fragments understood by Teradata.
Expand All @@ -940,10 +932,14 @@ private void buildExpressionRewriter()
.add(new RewriteIn())
.add(new RewriteLikeWithCaseSensitivity())
.add(new RewriteLikeEscapeWithCaseSensitivity())
.add(new RewriteSubstring())
.withTypeClass("integer_type", ImmutableSet.of("tinyint", "smallint", "integer", "bigint"))
.withTypeClass("numeric_type", ImmutableSet.of("tinyint", "smallint", "integer", "bigint", "decimal", "real", "double"))
.withTypeClass("string_type", ImmutableSet.of("varchar"))
.map("$equal(left: numeric_type, right: numeric_type)").to("left = right")
.map("$not_equal(left: numeric_type, right: numeric_type)").to("left <> right")
.map("$equal(left: string_type, right: string_type)").to("left = right")
.map("$not_equal(left: string_type, right: string_type)").to("left <> right")
.map("$less_than(left: numeric_type, right: numeric_type)").to("left < right")
.map("$less_than_or_equal(left: numeric_type, right: numeric_type)").to("left <= right")
.map("$greater_than(left: numeric_type, right: numeric_type)").to("left > right")
Expand Down Expand Up @@ -977,7 +973,7 @@ private void buildAggregateRewriter()
this.aggregateFunctionRewriter = new AggregateFunctionRewriter<>(
this.connectorExpressionRewriter,
ImmutableSet.<AggregateFunctionRule<JdbcExpression, ParameterizedExpression>>builder()
// Basic aggregates
// Basic aggregate
.add(new ImplementCountAll(bigintTypeHandle))
.add(new ImplementCount(bigintTypeHandle))
.add(new ImplementCountDistinct(bigintTypeHandle, false))
Expand Down Expand Up @@ -1019,6 +1015,17 @@ public Optional<ParameterizedExpression> convertPredicate(ConnectorSession sessi
return this.connectorExpressionRewriter.rewrite(session, expression, assignments);
}

@Override
public Optional<JdbcExpression> convertProjection(
ConnectorSession session,
JdbcTableHandle handle,
ConnectorExpression expression,
Map<String, ColumnHandle> assignments)
{
// Reuse the same connector expression rewriter used for predicates
return projectFunctionRewriter.rewrite(session, handle, expression, assignments);
}

@Override
public boolean supportsAggregationPushdown(ConnectorSession session, JdbcTableHandle table, List<AggregateFunction> aggregates, Map<String, ColumnHandle> assignments, List<List<ColumnHandle>> groupingSets)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ public static ConnectionFactory getConnectionFactory(BaseJdbcConfig config, Tera
case "JWT":
String token = teradataConfig.getOidcJwtToken();
if (token != null && !token.trim().isEmpty()) {
token = "token=" + token;
connectionProperties.put("LOGDATA", token);
}
break;
Expand Down
Loading
Loading