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

package com.postgres.replic.tools;

import java.sql.*;

public class PsqlMasterAdd extends MasterAdd {

    public static final String APP_NAME = ToolKitConst.MASTER_ADD_TABLE;

    public PsqlMasterAdd()  {
    }

    public static void main (String[] args ) throws Exception {
        MasterAdd masterAdd = new PsqlMasterAdd();
        masterAdd.run(args);
    }

    public  String getAppName() {
        return APP_NAME;
    }

    public void run(String[] args) {
        if (!init(args)) {
            System.exit(1);
        }

        System.out.println("debug=" + debug);
        System.out.println("host=" + host);
        System.out.println("port=" + port);
        System.out.println("user=" + user);
        System.out.println("pass=" + pass);
        System.out.println("db=" + db);
        System.out.println("schema=" + schema);
        System.out.println("trigger=" + trigger);

        masterAdd (trigger);

    }

    public PsqlMasterAdd(String table, String column)
    throws Exception {
        super(table, column);
    }

    public ResultSet getTableColumnAttrRS() throws SQLException {
        if (debug) System.out.println("PsqlMasterAdd::getTableColumnAttrRS: BEGIN");

        Statement stmt = getConnection().createStatement();

        String sql = "select pgc.oid, pga.attnum from pg_class pgc" +
        ", pg_attribute pga where pgc.relname = '" + table + "'" +
        " and pgc.oid = pga.attrelid" +
        " and pga.attname = '" + column + "'";

        if (debug) System.out.println("PsqlMasterAdd::getTableColumnAttrRS: sql=" + sql);

        return stmt.executeQuery(sql);
    }

    public boolean createTrigger(String trigger, String table, String columnNum)
    throws SQLException {
        Statement stmt = getConnection().createStatement();
        String sql = "create trigger " + trigger + " after" +
        " insert or update or delete on " + table +
        " for each row execute procedure" +
        " _rserv_log_('" + columnNum + "')";

        if (debug) System.out.println("PsqlMasterAdd::createTrigger: sql=" + sql);

        return stmt.execute(sql);
    }

    public int insertInto_RSERV_TABLES_(int tableId, String columnName)
    throws SQLException {

        Statement stmt = getConnection().createStatement();
        String sql = "insert into _RSERV_TABLES_ (tname, cname, reloid, key)"
        + " values ('"
        + table + "', '"
        + column + "', "
        + tableId + ", "
        + columnName + ")" ;

        if (debug) System.out.println("PsqlMasterAdd::insertInto_RSERV_TABLES_: sql=" + sql);

        return stmt.executeUpdate(sql);
    }

}
