package org.seasar.framework.util;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

import org.seasar.framework.exception.SQLRuntimeException;

/**
 * @author higa
 *  
 */
public final class DatabaseMetaDataUtil {

	private DatabaseMetaDataUtil() {
	}

	public static String[] getPrimaryKeys(DatabaseMetaData dbMetaData,
			String tableName) {

		Set set = getPrimaryKeySet(dbMetaData, tableName);
		return (String[]) set.toArray(new String[set.size()]);
	}

	public static Set getPrimaryKeySet(DatabaseMetaData dbMetaData,
			String tableName) {

		tableName = convertIdentifier(dbMetaData, tableName);
		int index = tableName.indexOf('.');
		if (index >= 0) {
			tableName = tableName.substring(index + 1);
		}
		Set set = new CaseInsensitiveSet();
		try {
			ResultSet rs = dbMetaData.getPrimaryKeys(null, null, tableName);
			while (rs.next()) {
				set.add(rs.getString(4));
			}
			rs.close();
		} catch (SQLException ex) {
			throw new SQLRuntimeException(ex);
		}
		return set;
	}

	public static String[] getColumns(DatabaseMetaData dbMetaData,
			String tableName) {

		Set set = getColumnSet(dbMetaData, tableName);
		return (String[]) set.toArray(new String[set.size()]);
	}

	public static Set getColumnSet(DatabaseMetaData dbMetaData, String tableName) {
		tableName = convertIdentifier(dbMetaData, tableName);
		int index = tableName.indexOf('.');
		if (index >= 0) {
			tableName = tableName.substring(index + 1);
		}
		Set set = new CaseInsensitiveSet();
		try {
			ResultSet rs = dbMetaData.getColumns(null, null, tableName, null);
			while (rs.next()) {
				set.add(rs.getString(4));
			}
			rs.close();
		} catch (SQLException ex) {
			throw new SQLRuntimeException(ex);
		}
		return set;
	}

	public static String convertIdentifier(DatabaseMetaData dbMetaData,
			String identifier) {

		if (!supportsMixedCaseIdentifiers(dbMetaData)) {
			if (storesUpperCaseIdentifiers(dbMetaData)) {
				return identifier.toUpperCase();
			} else {
				return identifier.toLowerCase();
			}
		} else {
			return identifier;
		}
	}

	public static boolean supportsMixedCaseIdentifiers(
			DatabaseMetaData dbMetaData) {

		try {
			return dbMetaData.supportsMixedCaseIdentifiers();
		} catch (SQLException ex) {
			throw new SQLRuntimeException(ex);
		}
	}

	public static boolean storesUpperCaseIdentifiers(DatabaseMetaData dbMetaData) {
		try {
			return dbMetaData.storesUpperCaseIdentifiers();
		} catch (SQLException ex) {
			throw new SQLRuntimeException(ex);
		}
	}

	public static String getDatabaseProductName(DatabaseMetaData dbMetaData) {
		try {
			return dbMetaData.getDatabaseProductName();
		} catch (SQLException ex) {
			throw new SQLRuntimeException(ex);
		}
	}
}