View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.infra.database.h2.metadata.data.loader;
19  
20  import org.apache.shardingsphere.infra.database.core.metadata.data.loader.DialectMetaDataLoader;
21  import org.apache.shardingsphere.infra.database.core.metadata.data.loader.MetaDataLoaderMaterial;
22  import org.apache.shardingsphere.infra.database.core.metadata.data.model.ColumnMetaData;
23  import org.apache.shardingsphere.infra.database.core.metadata.data.model.IndexMetaData;
24  import org.apache.shardingsphere.infra.database.core.metadata.data.model.SchemaMetaData;
25  import org.apache.shardingsphere.infra.database.core.metadata.data.model.TableMetaData;
26  import org.apache.shardingsphere.infra.database.core.metadata.database.datatype.DataTypeRegistry;
27  
28  import java.sql.Connection;
29  import java.sql.PreparedStatement;
30  import java.sql.ResultSet;
31  import java.sql.SQLException;
32  import java.sql.Types;
33  import java.util.Collection;
34  import java.util.Collections;
35  import java.util.HashMap;
36  import java.util.LinkedList;
37  import java.util.Map;
38  import java.util.Map.Entry;
39  import java.util.stream.Collectors;
40  
41  /**
42   * Meta data loader for H2.
43   */
44  public final class H2MetaDataLoader implements DialectMetaDataLoader {
45      
46      private static final String TABLE_META_DATA_NO_ORDER = "SELECT TABLE_CATALOG, TABLE_NAME, COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COALESCE(IS_VISIBLE, FALSE) IS_VISIBLE, IS_NULLABLE"
47              + " FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG=? AND TABLE_SCHEMA=?";
48      
49      private static final String ORDER_BY_ORDINAL_POSITION = " ORDER BY ORDINAL_POSITION";
50      
51      private static final String TABLE_META_DATA_SQL = TABLE_META_DATA_NO_ORDER + ORDER_BY_ORDINAL_POSITION;
52      
53      private static final String TABLE_META_DATA_SQL_IN_TABLES = TABLE_META_DATA_NO_ORDER + " AND UPPER(TABLE_NAME) IN (%s)" + ORDER_BY_ORDINAL_POSITION;
54      
55      private static final String INDEX_META_DATA_SQL = "SELECT TABLE_CATALOG, TABLE_NAME, INDEX_NAME, INDEX_TYPE_NAME FROM INFORMATION_SCHEMA.INDEXES"
56              + " WHERE TABLE_CATALOG=? AND TABLE_SCHEMA=? AND UPPER(TABLE_NAME) IN (%s)";
57      
58      private static final String PRIMARY_KEY_META_DATA_SQL = "SELECT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA.INDEXES WHERE TABLE_CATALOG=? AND TABLE_SCHEMA=?"
59              + " AND INDEX_TYPE_NAME = 'PRIMARY KEY'";
60      
61      private static final String PRIMARY_KEY_META_DATA_SQL_IN_TABLES = PRIMARY_KEY_META_DATA_SQL + " AND UPPER(TABLE_NAME) IN (%s)";
62      
63      private static final String GENERATED_INFO_SQL = "SELECT C.TABLE_NAME TABLE_NAME, C.COLUMN_NAME COLUMN_NAME, COALESCE(I.IS_GENERATED, FALSE) IS_GENERATED FROM INFORMATION_SCHEMA.COLUMNS C"
64              + " RIGHT JOIN INFORMATION_SCHEMA.INDEXES I ON C.TABLE_NAME=I.TABLE_NAME WHERE C.TABLE_CATALOG=? AND C.TABLE_SCHEMA=?";
65      
66      private static final String GENERATED_INFO_SQL_IN_TABLES = GENERATED_INFO_SQL + " AND UPPER(C.TABLE_NAME) IN (%s)";
67      
68      @Override
69      public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException {
70          Collection<TableMetaData> tableMetaDataList = new LinkedList<>();
71          try (Connection connection = material.getDataSource().getConnection()) {
72              Map<String, Collection<ColumnMetaData>> columnMetaDataMap = loadColumnMetaDataMap(connection, material.getActualTableNames());
73              Map<String, Collection<IndexMetaData>> indexMetaDataMap = columnMetaDataMap.isEmpty() ? Collections.emptyMap() : loadIndexMetaData(connection, columnMetaDataMap.keySet());
74              for (Entry<String, Collection<ColumnMetaData>> entry : columnMetaDataMap.entrySet()) {
75                  Collection<IndexMetaData> indexMetaDataList = indexMetaDataMap.getOrDefault(entry.getKey(), Collections.emptyList());
76                  tableMetaDataList.add(new TableMetaData(entry.getKey(), entry.getValue(), indexMetaDataList, Collections.emptyList()));
77              }
78          }
79          return Collections.singleton(new SchemaMetaData(material.getDefaultSchemaName(), tableMetaDataList));
80      }
81      
82      private Map<String, Collection<ColumnMetaData>> loadColumnMetaDataMap(final Connection connection, final Collection<String> tables) throws SQLException {
83          Map<String, Collection<ColumnMetaData>> result = new HashMap<>();
84          try (PreparedStatement preparedStatement = connection.prepareStatement(getTableMetaDataSQL(tables))) {
85              Map<String, Collection<String>> tablePrimaryKeys = loadTablePrimaryKeys(connection, tables);
86              Map<String, Map<String, Boolean>> tableGenerated = loadTableGenerated(connection, tables);
87              preparedStatement.setString(1, connection.getCatalog());
88              preparedStatement.setString(2, "PUBLIC");
89              try (ResultSet resultSet = preparedStatement.executeQuery()) {
90                  while (resultSet.next()) {
91                      String tableName = resultSet.getString("TABLE_NAME");
92                      ColumnMetaData columnMetaData =
93                              loadColumnMetaData(resultSet, tablePrimaryKeys.getOrDefault(tableName, Collections.emptyList()), tableGenerated.getOrDefault(tableName, new HashMap<>()));
94                      if (!result.containsKey(tableName)) {
95                          result.put(tableName, new LinkedList<>());
96                      }
97                      result.get(tableName).add(columnMetaData);
98                  }
99              }
100         }
101         return result;
102     }
103     
104     private ColumnMetaData loadColumnMetaData(final ResultSet resultSet, final Collection<String> primaryKeys, final Map<String, Boolean> tableGenerated) throws SQLException {
105         String columnName = resultSet.getString("COLUMN_NAME");
106         String dataType = resultSet.getString("DATA_TYPE");
107         boolean primaryKey = primaryKeys.contains(columnName);
108         boolean generated = tableGenerated.getOrDefault(columnName, Boolean.FALSE);
109         boolean isVisible = resultSet.getBoolean("IS_VISIBLE");
110         boolean isNullable = "YES".equals(resultSet.getString("IS_NULLABLE"));
111         return new ColumnMetaData(columnName, DataTypeRegistry.getDataType(getDatabaseType(), dataType).orElse(Types.OTHER), primaryKey, generated, false, isVisible, false, isNullable);
112     }
113     
114     private String getTableMetaDataSQL(final Collection<String> tables) {
115         return tables.isEmpty() ? TABLE_META_DATA_SQL
116                 : String.format(TABLE_META_DATA_SQL_IN_TABLES, tables.stream().map(each -> String.format("'%s'", each).toUpperCase()).collect(Collectors.joining(",")));
117     }
118     
119     private Map<String, Collection<IndexMetaData>> loadIndexMetaData(final Connection connection, final Collection<String> tableNames) throws SQLException {
120         Map<String, Collection<IndexMetaData>> result = new HashMap<>();
121         try (PreparedStatement preparedStatement = connection.prepareStatement(getIndexMetaDataSQL(tableNames))) {
122             preparedStatement.setString(1, connection.getCatalog());
123             preparedStatement.setString(2, "PUBLIC");
124             try (ResultSet resultSet = preparedStatement.executeQuery()) {
125                 while (resultSet.next()) {
126                     String indexName = resultSet.getString("INDEX_NAME");
127                     String tableName = resultSet.getString("TABLE_NAME");
128                     boolean uniqueIndex = "UNIQUE INDEX".equals(resultSet.getString("INDEX_TYPE_NAME"));
129                     if (!result.containsKey(tableName)) {
130                         result.put(tableName, new LinkedList<>());
131                     }
132                     IndexMetaData indexMetaData = new IndexMetaData(indexName);
133                     indexMetaData.setUnique(uniqueIndex);
134                     result.get(tableName).add(indexMetaData);
135                     
136                 }
137             }
138         }
139         return result;
140     }
141     
142     private String getIndexMetaDataSQL(final Collection<String> tableNames) {
143         return String.format(INDEX_META_DATA_SQL, tableNames.stream().map(each -> String.format("'%s'", each).toUpperCase()).collect(Collectors.joining(",")));
144     }
145     
146     private String getPrimaryKeyMetaDataSQL(final Collection<String> tables) {
147         return tables.isEmpty() ? PRIMARY_KEY_META_DATA_SQL
148                 : String.format(PRIMARY_KEY_META_DATA_SQL_IN_TABLES, tables.stream().map(each -> String.format("'%s'", each).toUpperCase()).collect(Collectors.joining(",")));
149     }
150     
151     private Map<String, Collection<String>> loadTablePrimaryKeys(final Connection connection, final Collection<String> tableNames) throws SQLException {
152         Map<String, Collection<String>> result = new HashMap<>();
153         try (PreparedStatement preparedStatement = connection.prepareStatement(getPrimaryKeyMetaDataSQL(tableNames))) {
154             preparedStatement.setString(1, connection.getCatalog());
155             preparedStatement.setString(2, "PUBLIC");
156             try (ResultSet resultSet = preparedStatement.executeQuery()) {
157                 while (resultSet.next()) {
158                     String indexName = resultSet.getString("INDEX_NAME");
159                     String tableName = resultSet.getString("TABLE_NAME");
160                     result.computeIfAbsent(tableName, key -> new LinkedList<>()).add(indexName);
161                 }
162             }
163         }
164         return result;
165     }
166     
167     private String getGeneratedInfoSQL(final Collection<String> tables) {
168         return tables.isEmpty() ? GENERATED_INFO_SQL
169                 : String.format(GENERATED_INFO_SQL_IN_TABLES, tables.stream().map(each -> String.format("'%s'", each).toUpperCase()).collect(Collectors.joining(",")));
170     }
171     
172     private Map<String, Map<String, Boolean>> loadTableGenerated(final Connection connection, final Collection<String> tableNames) throws SQLException {
173         Map<String, Map<String, Boolean>> result = new HashMap<>();
174         try (PreparedStatement preparedStatement = connection.prepareStatement(getGeneratedInfoSQL(tableNames))) {
175             preparedStatement.setString(1, connection.getCatalog());
176             preparedStatement.setString(2, "PUBLIC");
177             try (ResultSet resultSet = preparedStatement.executeQuery()) {
178                 while (resultSet.next()) {
179                     String columnName = resultSet.getString("COLUMN_NAME");
180                     String tableName = resultSet.getString("TABLE_NAME");
181                     boolean generated = resultSet.getBoolean("IS_GENERATED");
182                     result.computeIfAbsent(tableName, key -> new HashMap<>()).put(columnName, generated);
183                 }
184             }
185         }
186         return result;
187     }
188     
189     @Override
190     public String getDatabaseType() {
191         return "H2";
192     }
193 }