Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

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 @@ -17,20 +17,22 @@

import com.google.cloud.teleport.v2.spanner.migrations.connection.IConnectionHelper;
import com.google.cloud.teleport.v2.spanner.migrations.exceptions.ConnectionException;
import com.google.cloud.teleport.v2.templates.dbutils.dml.PreparedStatementValue;
import com.google.cloud.teleport.v2.templates.models.DMLGeneratorResponse;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Types;
import java.util.List;

public class JdbcDao implements IDao {
private String sqlUrl;
private String sqlUser;

private final String sqlUrl;
private final String sqlUser;
private final IConnectionHelper connectionHelper;

private static final Logger LOG = LoggerFactory.getLogger(JdbcDao.class);

public JdbcDao(String sqlUrl, String sqlUser, IConnectionHelper connectionHelper) {
this.sqlUrl = sqlUrl;
this.sqlUser = sqlUser;
Expand All @@ -41,49 +43,93 @@ public JdbcDao(String sqlUrl, String sqlUser, IConnectionHelper connectionHelper
public void write(
DMLGeneratorResponse dmlGeneratorResponse, TransactionalCheck transactionalCheck)
throws Exception {
Connection connObj = null;
Statement statement = null;

String dmlStatement = dmlGeneratorResponse.getDmlStatement();

try {
connObj = (Connection) connectionHelper.getConnection(this.sqlUrl + "/" + this.sqlUser);
// Try-with-resources ensures the pooled connection is always returned even if statement.close()
// throws on a broken socket or after a failed transactional check.
try (Connection connObj =
(Connection) connectionHelper.getConnection(this.sqlUrl + "/" + this.sqlUser)) {
if (connObj == null) {
throw new ConnectionException("Connection is null");
}
connObj.setAutoCommit(false);
java.util.List<Object> params = dmlGeneratorResponse.getPreparedStatementParameters();
if (params != null && !params.isEmpty()) {
java.sql.PreparedStatement pstmt = connObj.prepareStatement(dmlStatement);
statement = pstmt;
int paramIdx = 1;
for (Object param : params) {
if (param instanceof byte[]) {
byte[] bytes = (byte[]) param;
pstmt.setBlob(paramIdx++, new java.io.ByteArrayInputStream(bytes), bytes.length);
} else {
pstmt.setObject(paramIdx++, param);
try {
List<Object> params = dmlGeneratorResponse.getPreparedStatementParameters();
if (params != null && !params.isEmpty()) {
try (PreparedStatement pstmt = connObj.prepareStatement(dmlStatement)) {
int paramIdx = 1;
for (Object param : params) {
bindParameter(pstmt, paramIdx++, param);
}
pstmt.executeUpdate();
}
} else {
// Raw Statement fallback retained for un-migrated dialects (Oracle, SQL Server).
try (Statement statement = connObj.createStatement()) {
statement.executeUpdate(dmlStatement);
}
}
pstmt.executeUpdate();
} else {
statement = connObj.createStatement();
statement.executeUpdate(dmlStatement);
}

if (transactionalCheck != null) {
transactionalCheck.check();
if (transactionalCheck != null) {
transactionalCheck.check();
}
connObj.commit();
} catch (Throwable t) {
// Explicitly roll back before returning the connection to the pool so drivers that do not
// auto-rollback on close (or non-HikariCP helpers) never commit partial writes.
try {
connObj.rollback();
} catch (Throwable rollbackEx) {
t.addSuppressed(rollbackEx);
}
throw t;
}
connObj.commit();

} finally {
}
}

if (statement != null) {
statement.close();
}
if (connObj != null) {
connObj.close();
/**
* Binds a prepared statement parameter. Handles typed {@link PreparedStatementValue} entries
* uniformly across JDBC dialects, falling back to legacy raw parameter binding for un-migrated
* dialects.
*/
protected void bindParameter(PreparedStatement pstmt, int paramIdx, Object param)
throws SQLException {
if (param instanceof PreparedStatementValue) {
PreparedStatementValue bindValue = (PreparedStatementValue) param;
Object value = bindValue.getValue();
if (value == null) {
pstmt.setNull(paramIdx, bindValue.getSqlType());
} else if (bindValue.getSqlType() == Types.OTHER) {
// Must precede the String check: untyped strings (e.g. PostgreSQL jsonb/uuid/date/time)
// carry a String payload with Types.OTHER so the driver sends OID UNSPECIFIED.
pstmt.setObject(paramIdx, value, Types.OTHER);
} else if (value instanceof byte[]) {
pstmt.setBytes(paramIdx, (byte[]) value);
} else if (value instanceof String) {
pstmt.setString(paramIdx, (String) value);
} else if (value instanceof Boolean) {
pstmt.setBoolean(paramIdx, (Boolean) value);
} else if (value instanceof BigDecimal) {
pstmt.setBigDecimal(paramIdx, (BigDecimal) value);
} else if (value instanceof Long) {
pstmt.setLong(paramIdx, (Long) value);
} else if (value instanceof Float) {
pstmt.setFloat(paramIdx, (Float) value);
} else if (value instanceof Double) {
pstmt.setDouble(paramIdx, (Double) value);
} else {
// Defensive fallback for any future PreparedStatementValue payload types.
pstmt.setObject(paramIdx, value, bindValue.getSqlType());
}
return;
}

// Legacy raw parameter binding retained for un-migrated dialects (e.g. Oracle LOB params).
if (param instanceof byte[]) {
byte[] bytes = (byte[]) param;
pstmt.setBlob(paramIdx, new ByteArrayInputStream(bytes), bytes.length);
} else {
pstmt.setObject(paramIdx, param);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (C) 2026 Google LLC
*
* 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 com.google.cloud.teleport.v2.templates.dbutils.dml;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;

/**
* The SQL fragment used for a single column value in a parameterized DML statement, together with
* the values to be bound to the {@code ?} placeholders in that fragment (in order).
*
* <p>The SQL fragment is always generated by the template (for example {@code ?}, {@code
* ?::timestamptz}, or {@code CONVERT_TZ(?, '+00:00', ?)}) and never contains user or record data.
*/
public final class ColumnBinding {

public static final String PLACEHOLDER = "?";

private final String placeholderSql;
private final ImmutableList<PreparedStatementValue> params;

private ColumnBinding(String placeholderSql, List<PreparedStatementValue> params) {
Preconditions.checkNotNull(placeholderSql, "placeholderSql must not be null");
Preconditions.checkNotNull(params, "params must not be null");
long placeholderCount = placeholderSql.chars().filter(c -> c == '?').count();
Preconditions.checkArgument(
placeholderCount == params.size(),
"Placeholder count %s does not match parameter count %s for SQL fragment: %s",
placeholderCount,
params.size(),
placeholderSql);
this.placeholderSql = placeholderSql;
this.params = ImmutableList.copyOf(params);
}

/** A binding with a single {@code ?} placeholder. */
public static ColumnBinding of(PreparedStatementValue value) {
return new ColumnBinding(PLACEHOLDER, ImmutableList.of(value));
}

/**
* A binding with a template-generated SQL fragment containing one {@code ?} per parameter.
*
* <p>The placeholder count check assumes {@code placeholderSql} does not contain literal {@code
* ?} characters inside SQL string literals or dialect-specific operators.
*/
public static ColumnBinding of(String placeholderSql, List<PreparedStatementValue> params) {
return new ColumnBinding(placeholderSql, params);
}

public String getPlaceholderSql() {
return placeholderSql;
}

public ImmutableList<PreparedStatementValue> getParams() {
return params;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ColumnBinding)) {
return false;
}
ColumnBinding that = (ColumnBinding) o;
return placeholderSql.equals(that.placeholderSql) && params.equals(that.params);
}

@Override
public int hashCode() {
return Objects.hash(placeholderSql, params);
}

@Override
public String toString() {
return "ColumnBinding{placeholderSql=" + placeholderSql + ", params=" + params + "}";
}
}
Loading
Loading