/*
 * $Source: /usr/local/cvsroot/erserver/erserver/java/src/com/postgres/replic/tools/desc/MasterAddTable.java,v $
 * $Author: asullivan $ $Revision: 1.1.1.1 $ $Date: 2003/08/26 19:02:26 $
 *
 */

package com.postgres.replic.tools.desc;

import com.postgres.replic.tools.*;
import java.sql.*;


public class MasterAddTable extends AddTable {

    private static final String SYS_TABLE = "_RSERV_TABLES_";

    public MasterAddTable(
    Connection conn,
    String table,
    String column) throws Exception {
        super(conn, table, column);

    }

    /* res[0] will contain oid
       res[1] - AttNum
    */

    public void addTable() throws Exception {

        try {
            getConnection().setAutoCommit(false);
            String [] res = getAttNum(table, column);
            String oid = res [0];
            String attNum = res [1];

            createTrigger(table, attNum);
            insertRserv(SYS_TABLE, table, column, oid, attNum);
            if (!TEST ) {
                getConnection().commit();
            } else {
                getConnection().rollback();
            }
        } catch (Exception e) {
            try { getConnection().rollback(); } catch (Exception ex) { };
            try { getConnection().setAutoCommit(true); }
            catch (Exception ex) { };
            throw new Exception ("MasterAddTable::insertRserv" + e.toString());
        } finally {

        }
    }

    public String getTriggerName(String table) {
        return ToolKitConst.GLOBAL_PREFIX + getFiller(table) + ToolKitConst.V_TRIGGER_SUFFIX;
    }

    private void createTrigger(String table, String attNum) {

        Statement stmt = null;
        ResultSet rs = null;

        try {

            stmt = getConnection().createStatement();

            String sql = "create trigger " + getTriggerName(table) + " after" +
            " insert or update or delete on " + table +
            " for each row execute procedure" +
            " _rserv_log_('" + attNum + "')";

            if (getDebug()) System.out.println("MasterAddTable::getAttNum: sql = " + sql);
            stmt.executeUpdate(sql);

            //getConnection().commit();
        } catch (Exception e) {
            System.out.println("MasterAddTable::getAttNum" + e.toString());
            try { getConnection().rollback(); } catch (Exception ex) { };
        } finally {
            if (stmt != null) {
                try { stmt.close(); } catch (Exception e) { };
            }
            if (rs != null) {
                try { rs.close(); } catch (Exception e) { };
            }
        }
    }

}
