/*
 * 著作権: Copyright (c) 2007－2008 ZIGEN
 * ライセンス：Eclipse Public License - v 1.0
 * 原文：http://www.eclipse.org/legal/epl-v10.html
 */

package zigen.plugin.db.ext.s2jdbc.entity;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import zigen.plugin.db.DbPlugin;
import zigen.plugin.db.core.IDBConfig;
import zigen.plugin.db.core.ResultSetUtil;
import zigen.plugin.db.core.StatementUtil;
import zigen.plugin.db.core.Transaction;
import zigen.plugin.db.ext.s2jdbc.entity.rule.AbstractSqlFactory;
import zigen.plugin.db.ext.s2jdbc.entity.rule.ISqlFactory;

public class OneToManySearcher {

    public static List<String> execute(IDBConfig config, String schema, String columnName) throws Exception {
        try {
            Connection con = Transaction.getInstance(config).getConnection();
            return execute(con, schema, columnName);

        } catch (Exception e) {
            throw e;
        }
    }

    public static List<String> execute(Connection con, String schema, String columnName) throws Exception {
        ResultSet rs = null;
        Statement st = null;
        List<String> result = null;
        try {
            st = con.createStatement();

            ISqlFactory factory = AbstractSqlFactory.getFactory(con.getMetaData());

            String sql = factory.createOneToManySql(schema, columnName);

            result = new ArrayList<String>();

            if (sql == null) {
                return result;
            }

            rs = st.executeQuery(sql);

            if (rs.next()) {
                result.add(rs.getString(1));
            }

        } catch (Exception e) {
            DbPlugin.log(e);
            throw e;
        } finally {
            ResultSetUtil.close(rs);
            StatementUtil.close(st);
        }

        return result;
    }

}
