001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.db.driver;
017
018import org.apache.http.impl.client.CloseableHttpClient;
019import ru.yandex.clickhouse.ClickHouseConnectionImpl;
020import ru.yandex.clickhouse.ClickhouseJdbcUrlParser;
021import ru.yandex.clickhouse.settings.ClickHouseProperties;
022
023import java.lang.reflect.Field;
024import java.net.URISyntaxException;
025import java.sql.PreparedStatement;
026import java.sql.SQLException;
027import java.util.Properties;
028import java.util.concurrent.TimeUnit;
029
030public class OfficialClickHouseConnection extends ClickHouseConnectionImpl {
031
032
033    private ClickHouseProperties properties;
034
035
036    public OfficialClickHouseConnection(String url) throws SQLException {
037        super(url);
038        try {
039            this.properties = ClickhouseJdbcUrlParser.parse(url,new Properties());
040        } catch (URISyntaxException e) {
041            throw new IllegalArgumentException(e);
042        }
043    }
044
045    public OfficialClickHouseConnection(String url, ClickHouseProperties properties) throws SQLException {
046        super(url, properties);
047        try {
048            this.properties = ClickhouseJdbcUrlParser.parse(url, properties.asProperties());
049        } catch (URISyntaxException e) {
050            throw new IllegalArgumentException(e);
051        }
052    }
053
054    @Override
055    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
056//      clickhouse 不支持 autoGeneratedKeys,但是 jfinal 调用了此方法会出错
057        return prepareStatement(sql);
058    }
059
060
061   public void cleanConnections() {
062       try {
063           Field httpClientField = ClickHouseConnectionImpl.class.getDeclaredField("httpclient");
064           httpClientField.setAccessible(true);
065           CloseableHttpClient httpclient = (CloseableHttpClient) httpClientField.get(this);
066           if (httpclient != null){
067               httpclient.getConnectionManager().closeExpiredConnections();
068               httpclient.getConnectionManager().closeIdleConnections(2 * properties.getSocketTimeout(), TimeUnit.MILLISECONDS);
069           }
070       } catch (NoSuchFieldException | IllegalAccessException e) {
071           e.printStackTrace();
072       }
073    }
074
075
076}