/*
 * 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.sqlserver;

import org.testcontainers.containers.MSSQLServerContainer;
import org.testcontainers.utility.DockerImageName;

import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

import static io.trino.testing.containers.TestContainers.startOrReuse;
import static java.lang.String.format;

public final class TestingSqlServer
        implements AutoCloseable
{
    private static final DockerImageName DOCKER_IMAGE_NAME = DockerImageName.parse("microsoft/mssql-server-linux:2017-CU13")
            .asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-CU12");
    private final MSSQLServerContainer<?> container;
    private final String databaseName;
    private Closeable cleanup = () -> {};

    public TestingSqlServer()
    {
        container = new MSSQLServerContainer<>(DOCKER_IMAGE_NAME);
        container.addEnv("ACCEPT_EULA", "yes");
        this.databaseName = "database_" + UUID.randomUUID().toString().replace("-", "");
    }

    public String getDatabaseName()
    {
        return databaseName;
    }

    public void execute(String sql)
    {
        try (Connection connection = container.createConnection("");
                Statement statement = connection.createStatement()) {
            statement.execute(sql);
        }
        catch (Exception e) {
            throw new RuntimeException("Failed to execute statement: " + sql, e);
        }
    }

    public Connection createConnection()
            throws SQLException
    {
        return container.createConnection("");
    }

    public void start()
    {
        cleanup = startOrReuse(container);
        setUpDatabase();
    }

    public String getUsername()
    {
        return container.getUsername();
    }

    public String getPassword()
    {
        return container.getPassword();
    }

    public String getJdbcUrl()
    {
        return container.getJdbcUrl();
    }

    private void setUpDatabase()
    {
        execute("CREATE DATABASE " + databaseName);

        // Enable snapshot isolation by default to reduce flakiness on CI
        execute(format("ALTER DATABASE %s SET ALLOW_SNAPSHOT_ISOLATION ON", databaseName));
        execute(format("ALTER DATABASE %s SET READ_COMMITTED_SNAPSHOT ON", databaseName));

        container.withUrlParam("database", this.databaseName);
    }

    @Override
    public void close()
    {
        try {
            cleanup.close();
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

@@ -591,16 +591,121 @@
 erver;%0A%0A
+import io.airlift.log.Logger;%0Aimport net.jodah.failsafe.Failsafe;%0Aimport net.jodah.failsafe.RetryPolicy;%0A
 import o
@@ -999,19 +999,121 @@
 ava.
-util.UUID;%0A
+time.temporal.ChronoUnit;%0Aimport java.util.UUID;%0A%0Aimport static com.google.common.base.Throwables.getCausalChain;
 %0Aimp
@@ -1291,16 +1291,725 @@
 eable%0A%7B%0A
+    private static final Logger log = Logger.get(TestingSqlServer.class);%0A%0A    private static final RetryPolicy%3C?%3E QUERY_RETRY_POLICY = new RetryPolicy%3C%3E()%0A            .withBackoff(1, 5, ChronoUnit.SECONDS)%0A            .withMaxRetries(5)%0A            .handleIf(throwable -%3E getCausalChain(throwable).stream()%0A                            .filter(SQLException.class::isInstance)%0A                            .anyMatch(exception -%3E exception.getMessage().contains(%22Rerun the transaction.%22)))%0A            .onRetry(event -%3E log.warn(%0A                    %22Query failed on attempt %25s, will retry. Exception: %25s%22,%0A                    event.getAttemptCount(),%0A                    event.getLastFailure().getMessage()));%0A%0A
     priv
@@ -3681,32 +3681,93 @@
 ss on CI%0A       
+ Failsafe.with(QUERY_RETRY_POLICY)%0A                .run(() -%3E
  execute(format(
@@ -3833,16 +3833,17 @@
 seName))
+)
 ;%0A      
@@ -3835,32 +3835,93 @@
 Name)));%0A       
+ Failsafe.with(QUERY_RETRY_POLICY)%0A                .run(() -%3E
  execute(format(
@@ -3986,16 +3986,17 @@
 seName))
+)
 ;%0A%0A     

Fix flaky TestingSqlServer setup