package org.jcon.df.request;

import org.jcon.util.GenLib;
import java.sql.Statement;

/**
 * A request to add a table to a database. Only one
 * table name should be supplied.
 *
 * @author Jack Harich
 */
public class AddTable extends DataRequest {

//---------- Abstract Implementation ---------------------
public boolean isMutator() {
    return true;
}
// prepare() not used since multiple sql
public Object perform() {
    Translator translator = requestServices.getTranslator();
    Statement statement = requestServices.getStatement();
    String sql = "#NotSet#";
    //----- Create table
    try {
        sql = translator.buildCreateTableStm(this);
        //print(".perform() - create SQL = " + sql);
        statement.executeUpdate(sql);

    } catch(Exception ex) {
        GenLib.exception("AddTable.perform()",
            "Cannot create table using SQL = " + sql, ex);
        // Exception could be due to variety of causes
        this.setFailureText("Exception, table may alread be in database\n or columns may have an error.");
        this.setFailureSQL(sql);
        this.setFailureException(ex);
        return this;
    }
    //----- Create primary key unique index
    try {
        sql = translator.buildCreateUniqueIndexStm(this);
        //print(".perform() - unique index SQL = " + sql);
        statement.executeUpdate(sql);

    } catch(Exception ex) {
        GenLib.exception("AddTable.perform()",
            "Cannot create unique index for table using SQL = " + sql, ex);
        // Exception could be due to variety of causes
        this.setFailureText("Exception, probably bad SQL.");
        this.setFailureException(ex);
        return this;
    }
    return this;
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("AddTable" + text);
}

} // End class
