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

import org.testcontainers.containers.ClickHouseContainer;

import java.io.Closeable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import static java.lang.String.format;
import static org.testcontainers.containers.ClickHouseContainer.HTTP_PORT;
import static org.testcontainers.utility.MountableFile.forClasspathResource;

public class TestingClickHouseServer
        implements Closeable
{
    private static final String CLICKHOUSE_IMAGE = "yandex/clickhouse-server:20.8";
    private final ClickHouseContainer dockerContainer;

    public TestingClickHouseServer()
    {
        // Use 2nd stable version
        dockerContainer = (ClickHouseContainer) new ClickHouseContainer(CLICKHOUSE_IMAGE)
                .withCopyFileToContainer(forClasspathResource("custom.xml"), "/etc/clickhouse-server/config.d/custom.xml")
                .withStartupAttempts(10);

        dockerContainer.start();
    }

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

    public String getJdbcUrl()
    {
        return format("jdbc:clickhouse://%s:%s/", dockerContainer.getContainerIpAddress(),
                dockerContainer.getMappedPort(HTTP_PORT));
    }

    @Override
    public void close()
    {
        dockerContainer.stop();
    }
}

@@ -649,16 +649,67 @@
 ntainer;
+%0Aimport org.testcontainers.utility.DockerImageName;
 %0A%0Aimport
@@ -1100,22 +1100,31 @@
 c final 
-String
+DockerImageName
  CLICKHO
@@ -1135,16 +1135,38 @@
 IMAGE = 
+DockerImageName.parse(
 %22yandex/
@@ -1182,17 +1182,132 @@
 e-server
-:
+%22);%0A    public static final String LATEST_VERSION = %2221.11.10.1%22;%0A    public static final String DEFAULT_VERSION = %22
 20.8%22;%0A 
@@ -1416,33 +1416,87 @@
     
-// Use 2nd stable
+this(DEFAULT_VERSION);%0A    %7D%0A%0A    public TestingClickHouseServer(String
  version
 %0A   
@@ -1491,16 +1491,23 @@
  version
+)%0A    %7B
 %0A       
@@ -1587,16 +1587,33 @@
 SE_IMAGE
+.withTag(version)
 )%0A      

Allow specifying CilckHouse docker image version