package com.ctrip.xpipe.service.datasource;

import com.ctrip.datasource.configure.DalDataSourceFactory;
import com.ctrip.platform.dal.dao.datasource.ClusterDynamicDataSource;
import com.ctrip.platform.dal.dao.datasource.ForceSwitchableDataSourceAdapter;
import com.ctrip.xpipe.service.fireman.ForceSwitchableDataSourceHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.dal.jdbc.datasource.DataSource;
import org.unidal.dal.jdbc.datasource.DataSourceDescriptor;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author lishanglin
 * date 2021/4/13
 */
public class CtripDynamicDataSource implements DataSource {

    private static final Logger logger = LoggerFactory.getLogger(CtripDynamicDataSource.class);

    private ClusterDynamicDataSource dataSource;

    private DataSourceDescriptor descriptor;

    private DalDataSourceFactory factory;

    private DataSourceConfig config = new DataSourceConfig();

    private void init() throws Exception {
        factory = new DalDataSourceFactory();
        dataSource = (ClusterDynamicDataSource) factory.getOrCreateDataSource(config.getClusterName());
        ForceSwitchableDataSourceHolder.getInstance().setDataSource(new ForceSwitchableDataSourceAdapter(dataSource));
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public DataSourceDescriptor getDescriptor() {
        return descriptor;
    }

    @Override
    public void initialize(DataSourceDescriptor descriptor) {
        this.descriptor = descriptor;
        try {
            init();
        } catch (Throwable e) {
            logger.error("[initialize]", e);
        }
    }

}

@@ -94,24 +94,155 @@
 rceFactory;%0A
+import com.ctrip.platform.dal.dao.configure.FirstAidKit;%0Aimport com.ctrip.platform.dal.dao.configure.SerializableDataSourceConfig;%0A
 import com.c
@@ -617,16 +617,80 @@
 criptor;
+%0Aimport org.unidal.dal.jdbc.datasource.JdbcDataSourceDescriptor;
 %0A%0Aimport
@@ -1653,24 +1653,322 @@
 criptor() %7B%0A
+        FirstAidKit firstAidKit = dataSource.getFirstAidKit();%0A        if (firstAidKit instanceof SerializableDataSourceConfig) %7B%0A            ((JdbcDataSourceDescriptor)descriptor)%0A                    .setProperty(%22url%22, ((SerializableDataSourceConfig) firstAidKit).getConnectionUrl());%0A        %7D%0A%0A
         retu

fix unidal log for 'SQL.Database'