/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.shardingsphere.infra.metadata.schema.builder.loader.dialect;

import org.apache.shardingsphere.infra.metadata.schema.builder.loader.DataTypeLoader;
import org.apache.shardingsphere.infra.metadata.schema.builder.spi.DialectTableMetaDataLoader;
import org.apache.shardingsphere.infra.metadata.schema.model.ColumnMetaData;
import org.apache.shardingsphere.infra.metadata.schema.model.TableMetaData;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Table meta data loader for MySQL.
 */
public final class MySQLTableMetaDataLoader implements DialectTableMetaDataLoader {
    
    private static final String TABLE_META_DATA_SQL
            = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_KEY, EXTRA, COLLATION_NAME FROM information_schema.columns WHERE TABLE_SCHEMA=? AND TABLE_NAME NOT IN (%s)";
    
    @Override
    public Map<String, TableMetaData> load(final DataSource dataSource, final Collection<String> existedTables) throws SQLException {
        Map<String, TableMetaData> result = new LinkedHashMap<>();
        loadColumnMetaData(dataSource, existedTables, result);
        // TODO load index
        return result;
    }
    
    private void loadColumnMetaData(final DataSource dataSource, final Collection<String> existedTables, final Map<String, TableMetaData> tableMetaDataMap) throws SQLException {
        String sql = String.format(TABLE_META_DATA_SQL, existedTables.stream().map(each -> String.format("'%s'", each)).collect(Collectors.joining(",")));
        try (
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sql)
        ) {
            Map<String, Integer> dataTypes = DataTypeLoader.load(connection.getMetaData());
            preparedStatement.setString(1, connection.getCatalog());
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    String tableName = resultSet.getString("TABLE_NAME");
                    ColumnMetaData columnMetaData = loadColumnMetaData(dataTypes, resultSet);
                    if (!tableMetaDataMap.containsKey(tableName)) {
                        tableMetaDataMap.put(tableName, new TableMetaData());
                    }
                    tableMetaDataMap.get(tableName).getColumns().put(columnMetaData.getName(), columnMetaData);
                }
            }
        }
    }
    
    private ColumnMetaData loadColumnMetaData(final Map<String, Integer> dataTypeMap, final ResultSet resultSet) throws SQLException {
        String columnName = resultSet.getString("COLUMN_NAME");
        String dataType = resultSet.getString("DATA_TYPE");
        boolean primaryKey = "PRI".equals(resultSet.getString("COLUMN_KEY"));
        boolean generated = "auto_increment".equals(resultSet.getString("EXTRA"));
        boolean caseSensitive = null != resultSet.getString("COLLATION_NAME") && resultSet.getString("COLLATION_NAME").endsWith("_ci");
        return new ColumnMetaData(columnName, dataTypeMap.get(dataType), primaryKey, generated, caseSensitive);
    }
    
    @Override
    public String getDatabaseType() {
        return "MySQL";
    }
}

@@ -1647,16 +1647,22 @@
  String 
+BASIC_
 TABLE_ME
@@ -1672,28 +1672,16 @@
 DATA_SQL
-%0A           
  = %22SELE
@@ -1805,16 +1805,127 @@
 SCHEMA=?
+%22;%0A    %0A    private static final String TABLE_META_DATA_SQL_WITH_EXISTED_TABLES = BASIC_TABLE_META_DATA_SQL + %22
  AND TAB
@@ -2472,163 +2472,8 @@
 n %7B%0A
-        String sql = String.format(TABLE_META_DATA_SQL, existedTables.stream().map(each -%3E String.format(%22'%25s'%22, each)).collect(Collectors.joining(%22,%22)));%0A
     
@@ -2636,21 +2636,43 @@
 ent(
-sql)%0A        
+getTableMetaDataSQL(existedTables))
 ) %7B%0A
@@ -4126,24 +4126,355 @@
 %0A    %7D%0A    %0A
+    private String getTableMetaDataSQL(final Collection%3CString%3E existedTables) %7B%0A        return existedTables.isEmpty() ? BASIC_TABLE_META_DATA_SQL%0A                : String.format(TABLE_META_DATA_SQL_WITH_EXISTED_TABLES, existedTables.stream().map(each -%3E String.format(%22'%25s'%22, each)).collect(Collectors.joining(%22,%22)));%0A    %7D%0A    %0A
     @Overrid

Fix error if existedTables is empty (#9641)