/*
 * Copyright (C) 2005 NTT DATA Corporation
 * 
 */
package org.postgresforest.vm;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import org.postgresforest.Driver;
import org.postgresforest.jdbc3.AbstractJdbc3Connection;
import org.postgresforest.jdbc3.Jdbc3Connection;
import org.postgresforest.vm.gsc.GscData;

public class NoPartitionReWriter extends ReWriter {

	/**
	 * @param gsc
	 */
	public NoPartitionReWriter(GscData gsc) {
		super(gsc);
	}

	/* (非 Javadoc)
	 * @see org.postgresforest.vm.ReWriter#setSrcSql(java.lang.String)
	 */
	public void rewrite(Parser parser) throws SQLException {

		clearSrcSql();

		m_paser = parser;
		m_srcSql = m_paser.getSrcSql();


		//QueryInfo作成
		if (m_paser.getType() == Parser.SELECT) {
				makeSelectQuery(m_paser);
		}else{
				makeOtherQuery();
		}
		
		//Ver2.0 ログ追加
		if (Driver.logInfo){
			//抽出更新カラム名
			QueryInfo qi;
			for( int i = 0; i < m_info.size(); i++ ){
				qi = (QueryInfo)m_info.get(i);
				
				AbstractJdbc3Connection con = (AbstractJdbc3Connection)qi.getConnection();

				m_logUtil.info("ReWriter Result: Connection URL = " + con.getURL());
				//パーティションNo.
				m_logUtil.info("ReWriter Result: Partition No = " + qi.getPartNo());
				//リライトしたSQL
				m_logUtil.info("ReWriter Result: The rewritten SQL = " + qi.getSql());
				//抽出テーブル名
				String[] tables = qi.getTables();
				String allname = "";
				try {
					for (int j = 0; j < tables.length; j++){
						allname = allname + tables[j] + ",";
					}
				} catch (Exception e) {
				}
				m_logUtil.info("ReWriter Result: Extraction Table Name = " + allname);
			}
		}

	}

	/* (非 Javadoc)
	 * @see org.postgresforest.vm.ReWriter#makeSelectQuery(org.postgresql.vm.Parser)
	 */
	protected void makeSelectQuery(Parser ps) throws SQLException {

		//Ver1.1 FOR UPDATEの追加			
		if(ps.isForUpdate()){
			makeOtherQuery();
		}else{

			if(Driver.forestTestLog)
				System.out.println( "The query type was specified to be dispersion.");

			if (Driver.logInfo)
				m_logUtil.info("The query type was specified to be dispersion.");
		
			//クエリタイプのセット
			m_queyType = TYPE_DISPERSION;

			//テーブルがパーティションではないか、VIEWで処理
			Connection con = m_gsc.getDistServer();

			//QueryInfoの作成
			QueryInfo qf = new QueryInfo();
			qf.setConnection(con);
			qf.setSql(m_srcSql);

			m_info.add(qf);

		}
	
	}

    /* (非 Javadoc)
     * @see org.postgresforest.vm.ReWriter#clearSrcSql()
     */
    protected void clearSrcSql() {

		m_srcSql = null;

		if(m_info == null){
			m_info = new ArrayList();
		}else{
		    m_info.clear();
		}


		m_queyType = TYPE_NONE;

    
    
    }
}
