/*
 * blanco Framework
 * Copyright (C) 2004-2006 IGA Tosiki
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.db.expander.query.iterator;

import java.util.List;

import blanco.cg.BlancoCgObjectFactory;
import blanco.cg.valueobject.BlancoCgClass;
import blanco.cg.valueobject.BlancoCgMethod;
import blanco.cg.valueobject.BlancoCgSourceFile;
import blanco.db.common.expander.BlancoDbAbstractMethod;
import blanco.db.common.valueobject.BlancoDbSetting;
import blanco.db.common.valueobject.BlancoDbSqlInfoStructure;
import blanco.db.util.BlancoDbCgUtilDotNet;

/**
 * 個別のメソッドを展開するためのクラス。
 */
public class ExecuteQueryMethodDotNet extends BlancoDbAbstractMethod {
    public ExecuteQueryMethodDotNet(final BlancoDbSetting argDbSetting,
            final BlancoDbSqlInfoStructure argSqlInfo,
            final BlancoCgObjectFactory argCgFactory,
            final BlancoCgSourceFile argCgSourceFile,
            final BlancoCgClass argCgClass) {
        super(argDbSetting, argSqlInfo, argCgFactory, argCgSourceFile,
                argCgClass);
    }

    public void expand() {
        final BlancoCgMethod cgMethod = fCgFactory.createMethod("ExecuteQuery",
                null);
        fCgClass.getMethodList().add(cgMethod);

        // BlancoDbCgUtilDotNet.addExceptionToMethodDeadlockTimeoutException(
        // fCgFactory, cgMethod, fDbSetting);
        BlancoDbCgUtilDotNet.addExceptionToMethodSqlException(fCgFactory,
                cgMethod);

        cgMethod.getLangDoc().getDescriptionList().add("検索型クエリを実行します。");

        final List<String> listLine = cgMethod.getLineList();

        if (fDbSetting.getLogging()) {
            BlancoDbCgUtilDotNet.addBeginLogToMethod(cgMethod);
        }

        // statementが未確保であるばあい、強制的にprepareStatementを呼び出します。
        listLine.add("if (fStatement == null) {");
        listLine.add("PrepareStatement();");
        listLine.add("}");

        // resultSetがあいた状態であれば、先にcloseを行います。
        listLine.add("if (fResultSet != null) {");
        listLine.add("fResultSet.Close();");
        listLine.add("fResultSet = null;");
        listLine.add("}");

        listLine.add("try {");
        listLine
                .add("fResultSet = fStatement.ExecuteReader(CommandBehavior.SequentialAccess);");
        listLine.add("} catch (SqlException ex) {");
        listLine.add("throw BlancoDbUtil.ConvertToBlancoException(ex);");
        listLine.add("}");
    }
}