8000 [Quarkus 4] Adapt SQL Server conflict translation to Hibernate 8 by Pepo48 · Pull Request #55430 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
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.
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,27 +17,23 @@

package org.keycloak.connections.jpa.dialect;

import org.hibernate.LockMode;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.sql.ast.SQLServerSqlAstTranslator;
import org.hibernate.dialect.sql.ast.internal.SQLServerSqlAstTranslator;
import org.hibernate.dialect.sql.ast.spi.SqlAstTranslationRequest;
import org.hibernate.dialect.sql.ast.spi.SqlAstTranslatorFactory;
import org.hibernate.dialect.sql.ast.spi.StandardSqlAstTranslatorFactory;
import org.hibernate.dialect.sql.ast.spi.TableReferenceAliasContext;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.sql.ast.SqlAstTranslator;
import org.hibernate.sql.ast.SqlAstTranslatorFactory;
import org.hibernate.sql.ast.spi.StandardSqlAstTranslatorFactory;
import org.hibernate.sql.ast.tree.Statement;
import org.hibernate.sql.ast.tree.from.NamedTableReference;
import org.hibernate.sql.ast.tree.insert.InsertSelectStatement;
import org.hibernate.sql.ast.spi.Statement;
import org.hibernate.sql.ast.spi.translation.Clause;
import org.hibernate.sql.ast.spi.translation.SqlAstTranslator;
import org.hibernate.sql.exec.spi.JdbcOperation;

/**
* Fixes Hibernate's SQL Server dialect to correctly handle HQL {@code insert ... on conflict ... do nothing}
* by emitting a MERGE statement instead of a plain INSERT that silently drops the conflict clause.
* Preserves concurrent-insert safety for Hibernate's MERGE-based conflict handling on SQL Server.
* <p>
* The MERGE target gets a {@code HOLDLOCK} hint for all conflict clauses. Without it, two concurrent upserts of the
* same new key can both take the "not matched" branch, and one fails with a unique constraint violation.
* <p>
* See <a href="https://hibernate.atlassian.net/browse/HHH-20826">HHH-20826</a> for the upstream tracker.
*/
public class KeycloakSQLServerDialect extends SQLServerDialect {

Expand All @@ -49,39 +45,23 @@ public KeycloakSQLServerDialect(DialectResolutionInfo info) {
super(info);
}

// Remove this override once Keycloak upgrades to a Hibernate version that fixes HHH-21039.
// https://hibernate.atlassian.net/browse/HHH-21039
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {
@Override
protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator(
SessionFactoryImplementor sessionFactory, Statement statement) {
return new SQLServerSqlAstTranslator<>(sessionFactory, statement) {
private boolean renderingMergeTarget;

@Override
protected void visitInsertStatementOnly(InsertSelectStatement statement) {
if (statement.getConflictClause() != null
&& !statement.getConflictClause().getConstraintColumnNames().isEmpty()) {
renderingMergeTarget = true;
visitInsertStatementEmulateMerge(statement);
appendSql(';');
} else {
super.visitInsertStatementOnly(statement);
}
}

protected <S extends Statement, T extends JdbcOperation> SqlAstTranslator<T> createTranslator(
SqlAstTranslationRequest<S, T> request) {
return new SQLServerSqlAstTranslator<>(request) {
@Override
protected boolean renderNamedTableReference(NamedTableReference tableReference, LockMode lockMode) {
if (renderingMergeTarget) {
renderingMergeTarget = false;
protected void renderTableReferenceAlias(String alias, TableReferenceAliasContext context) {
if (context == TableReferenceAliasContext.INSERT_TARGET
&& getCurrentClauseStack().getCurrent() == Clause.MERGE) {
// In a MERGE the table hint goes between the table name and the alias
appendSql(tableReference.getTableExpression());
registerAffectedTable(tableReference);
appendSql(" with (holdlock)");
renderTableReferenceIdentificationVariable(tableReference);
return true;
}
return super.renderNamedTableReference(tableReference, lockMode);
super.renderTableReferenceAlias(alias, context);
}
};
}
Expand Down
510D
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package org.keycloak.connections.jpa.dialect;

import java.util.Locale;
import java.util.UUID;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

/**
* Checks SQL generation without executing SQL Server statements on the H2 bootstrap connection.
*/
public class KeycloakSQLServerDialectTest {

private static final String INSERT = "insert into SqlServerConflictTestEntity (id, payload) values (1, 'first')";
private StandardServiceRegistry registry;
private SessionFactory sessionFactory;

@Before
public void createSessionFactory() {
registry = new StandardServiceRegistryBuilder()
.applySetting("hibernate.connection.driver_class", "org.h2.Driver")
.applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID())
.applySetting("hibernate.dialect", KeycloakSQLServerDialect.class.getName())
.applySetting("hibernate.boot.allow_jdbc_metadata_access", false)
.applySetting("hibernate.hbm2ddl.auto", "none")
.applySetting("hibernate.session_factory.statement_inspector", (StatementInspector) sql -> {
throw new CapturedSql(sql);
})
.build();
sessionFactory = new MetadataSources(registry).addAnnotatedClass(ConflictEntity.class)
.buildMetadata().buildSessionFactory();
}

@After
public void closeSessionFactory() {
if (sessionFactory != null) {
sessionFactory.close();
}
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}

@Test
public void doNothingLocksMergeTarget() {
assertLockedMerge(sql(INSERT + " on conflict (id) do nothing"));
}

@Test
public void doUpdateLocksMergeTarget() {
String sql = sql(INSERT + " on conflict (id) do update set payload = excluded.payload");
assertLockedMerge(sql);
assertTrue(sql.contains("when matched then update"));
}

@Test
public void plainInsertSelectDoesNotLockSource() {
String sql = sql("insert into SqlServerConflictTestEntity (id, payload)"
+ " select e.id + 1, e.payload from SqlServerConflictTestEntity e");
assertTrue(sql.startsWith("insert into "));
assertFalse(sql.contains("holdlock"));
}

private String sql(String hql) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
try {
return assertThrows(CapturedSql.class, () -> session.createMutationQuery(hql).executeUpdate()).sql;
} finally {
session.getTransaction().rollback();
}
}
}

private void assertLockedMerge(String sql) {
assertTrue(sql, sql.matches("(?s)^merge into \\S+ with \\(holdlock\\) \\S+ using .*;$"));
assertEquals(sql, 1, sql.split("holdlock", -1).length - 1);
assertEquals(sql, 1, sql.chars().filter(c -> c == ';').count());
}

private static class CapturedSql extends RuntimeException {
private final String sql;

private CapturedSql(String sql) {
this.sql = sql.toLowerCase(Locale.ROOT);
}
}

@Entity(name = "SqlServerConflictTestEntity")
public static class ConflictEntity {
@Id
private int id;

private String payload;
}
}
Loading
0