001
014
015 package com.liferay.portal.kernel.dao.db;
016
017 import com.liferay.portal.kernel.util.ArrayUtil;
018 import com.liferay.portal.kernel.util.StringBundler;
019 import com.liferay.portal.kernel.util.StringPool;
020 import com.liferay.portal.kernel.util.StringUtil;
021
022
026 public class IndexMetadataFactoryUtil {
027
028 public static IndexMetadata createIndexMetadata(
029 boolean unique, String tableName, String... columnNames) {
030
031 String specification = _getSpecification(tableName, columnNames);
032
033 String indexName = _getIndexName(specification);
034
035 StringBundler sb = new StringBundler(5);
036
037 if (!unique) {
038 sb.append("create ");
039 }
040 else {
041 sb.append("create unique ");
042 }
043
044 sb.append("index ");
045 sb.append(indexName);
046 sb.append(" on ");
047 sb.append(specification);
048
049 String createSQL = sb.toString();
050
051 sb.setIndex(0);
052
053 sb.append("drop index ");
054 sb.append(indexName);
055 sb.append(" on ");
056 sb.append(tableName);
057
058 String dropSQL = sb.toString();
059
060 return new IndexMetadata(
061 indexName, tableName, unique, specification, createSQL, dropSQL);
062 }
063
064 private static String _getIndexName(String specification) {
065 String specificationHash = StringUtil.toHexString(
066 specification.hashCode());
067
068 specificationHash = StringUtil.toUpperCase(specificationHash);
069
070 return _INDEX_NAME_PREFIX.concat(specificationHash);
071 }
072
073 private static String _getSpecification(
074 String tableName, String[] columnNames) {
075
076 StringBundler sb = new StringBundler(6);
077
078 sb.append(tableName);
079 sb.append(StringPool.SPACE);
080 sb.append(StringPool.OPEN_PARENTHESIS);
081
082 if (ArrayUtil.isNotEmpty(columnNames)) {
083 sb.append(
084 StringUtil.merge(columnNames, StringPool.COMMA_AND_SPACE));
085 }
086
087 sb.append(StringPool.CLOSE_PARENTHESIS);
088 sb.append(StringPool.SEMICOLON);
089
090 return sb.toString();
091 }
092
093 private static final String _INDEX_NAME_PREFIX = "IX_";
094
095 }