Beispiel #1
0
 public String getDDL() {
   final StringBuffer sql_columns = new StringBuffer();
   for (final MIndexColumn ic : getColumns()) {
     if (sql_columns.length() > 0) {
       sql_columns.append(",");
     }
     sql_columns.append(ic.getColumnName());
   }
   if (sql_columns.length() == 0) {
     throw new AdempiereException("Index has no columns defined");
   }
   //
   final StringBuffer sql = new StringBuffer("CREATE ");
   if (isUnique()) {
     sql.append("UNIQUE ");
   }
   sql.append("INDEX ")
       .append(getName())
       .append(" ON ")
       .append(getTableName())
       .append(" (")
       .append(sql_columns)
       .append(")");
   //
   final String whereClause = getWhereClause();
   if (!Check.isEmpty(whereClause, true)) {
     if (DB.isPostgreSQL()) {
       sql.append(" WHERE ").append(whereClause);
     } else {
       throw new AdempiereException("Partial Index not supported for this database");
     }
   }
   //
   return sql.toString();
 }
  @Override
  public void startElement(Properties ctx, Element element) throws SAXException {
    String elementValue = element.getElementValue();
    int AD_Backup_ID = -1;
    String Object_Status = null;

    log.info(elementValue);
    Attributes atts = element.attributes;
    String DBType = atts.getValue("DBType");
    String sql = atts.getValue("statement").trim();
    if (sql.endsWith(";")) sql = sql.substring(0, sql.length() - 1);
    PreparedStatement pstmt = DB.prepareStatement(sql, getTrxName(ctx));
    try {
      if (DBType.equals("ALL")) {
        int n = pstmt.executeUpdate();
        log.info("Executed SQL Statement: " + atts.getValue("statement"));
      } else if (DB.isOracle() == true && DBType.equals("Oracle")) {
        pstmt.executeUpdate();
        log.info("Executed SQL Statement for Oracle: " + atts.getValue("statement"));
      } else if (DB.isPostgreSQL()
          && (DBType.equals("Postgres")
              || DBType.equals(
                  "PostgreSQL") // backward compatibility with old packages developed by hand
          )) {
        // Avoid convert layer - command specific for postgresql
        //
        // pstmt = DB.prepareStatement(sql, null);
        // pstmt.executeUpdate();
        //
        Connection m_con = DB.getConnectionRW();
        try {
          Statement stmt = m_con.createStatement();
          int n = stmt.executeUpdate(atts.getValue("statement"));
          log.info("Executed SQL Statement for PostgreSQL: " + atts.getValue("statement"));
          // Postgres needs to commit DDL statements
          if (m_con != null && !m_con.getAutoCommit()) m_con.commit();
          stmt.close();
        } finally {
          m_con.close();
        }
      }
      pstmt.close();
    } catch (Exception e) {
      log.log(Level.SEVERE, "SQLSatement", e);
    }
  }
  /**
   * Doit
   *
   * @return ""
   */
  @Override
  protected String doIt() throws Exception {

    X_AD_Package_Imp_Proc adPackageImp = new X_AD_Package_Imp_Proc(getCtx(), p_PackIn_ID, null);

    // clear cache of previous runs
    IDFinder.clearIDCache();

    // Create Target directory if required
    String packageDirectory = adPackageImp.getAD_Package_Dir();
    if (packageDirectory == null || packageDirectory.trim().length() == 0) {
      packageDirectory = Adempiere.getAdempiereHome();
    }
    File targetDir = new File(packageDirectory + File.separator + "packages");

    if (!targetDir.exists()) {
      boolean success = (new File(packageDirectory + File.separator + "packages")).mkdirs();
      if (!success) {
        log.info("Target directory creation failed");
      }
    }

    // Unzip package
    File zipFilepath = new File(adPackageImp.getAD_Package_Source());
    log.info("zipFilepath->" + zipFilepath);
    String PackageName = CreateZipFile.getParentDir(zipFilepath);
    CreateZipFile.unpackFile(zipFilepath, targetDir);

    String dict_file =
        packageDirectory
            + File.separator
            + "packages"
            + File.separator
            + PackageName
            + File.separator
            + "dict"
            + File.separator
            + "PackOut.xml";
    log.info("dict file->" + dict_file);
    PackIn packIn = new PackIn();

    if (adPackageImp.isAD_Override_Dict() == true) PackIn.m_UpdateMode = "true";
    else PackIn.m_UpdateMode = "false";

    PackIn.m_Package_Dir =
        packageDirectory
            + File.separator
            + "packages"
            + File.separator
            + PackageName
            + File.separator;
    if (DB.isOracle()) PackIn.m_Database = "Oracle";
    else if (DB.isPostgreSQL()) PackIn.m_Database = "PostgreSQL";

    // call XML Handler
    String msg = packIn.importXML(dict_file, getCtx(), get_TrxName());

    // Generate Model Classes
    // globalqss - don't call Generate Model must be done manual
    // String args[] =
    // {IntPackIn.getAD_Package_Dir()+"/dbPort/src/org/compiere/model/",
    // "org.compiere.model","'U'"};
    // org.compiere.util.GenerateModel.main(args) ;

    return msg;
  } // doIt
  /**
   * Check if column exists in database and modify. If not create column.
   *
   * @param tablename
   * @param columnname
   * @param v_AD_Reference_ID
   * @param v_FieldLength
   * @param v_DefaultValue
   * @param v_IsMandatory
   */
  private int createColumn(Properties ctx, MTable table, MColumn column, boolean doAlter) {

    int no = 0;

    String sql = null;
    ResultSet rst = null;
    ResultSet rsc = null;
    Connection conn = null;
    Trx trx = Trx.get(getTrxName(ctx), true);
    if (!trx.commit()) return 0;

    try {
      // Find Column in Database
      conn = trx.getConnection();
      DatabaseMetaData md = conn.getMetaData();
      String catalog = DB.getDatabase().getCatalog();
      String schema = DB.getDatabase().getSchema();
      String tableName = table.getTableName();
      String columnName = column.getColumnName();
      if (DB.isOracle()) {
        tableName = tableName.toUpperCase();
        columnName = columnName.toUpperCase();
      } else if (DB.isPostgreSQL()) {
        tableName = tableName.toLowerCase();
        columnName = columnName.toLowerCase();
      }

      rst = md.getTables(catalog, schema, tableName, new String[] {"TABLE"});
      if (!rst.next()) {
        // table doesn't exist
        sql = table.getSQLCreate();
      } else {
        //
        rsc = md.getColumns(catalog, schema, tableName, columnName);
        if (rsc.next()) {
          if (doAlter) {
            // update existing column
            boolean notNull = DatabaseMetaData.columnNoNulls == rsc.getInt("NULLABLE");
            sql = column.getSQLModify(table, column.isMandatory() != notNull);
          }
        } else {
          // No existing column
          sql = column.getSQLAdd(table);
        }
        rsc.close();
        rsc = null;
      }

      rst.close();
      rst = null;
      // execute modify or add if needed
      if (sql != null && sql.trim().length() > 0) {
        log.info(sql);

        if (sql.indexOf(DB.SQLSTATEMENT_SEPARATOR) == -1) {
          no = DB.executeUpdate(sql, false, trx.getTrxName());
          if (no == -1) return 0;
        } else {
          String statements[] = sql.split(DB.SQLSTATEMENT_SEPARATOR);
          for (int i = 0; i < statements.length; i++) {
            int count = DB.executeUpdate(statements[i], false, trx.getTrxName());
            if (count == -1) {
              return 0;
            }
            no += count;
          }
        }
      }
      trx.commit(true);
    } catch (SQLException e) {
      log.log(Level.SEVERE, e.getLocalizedMessage(), e);
      if (rsc != null) {
        try {
          rsc.close();
        } catch (SQLException e1) {
        }
        rsc = null;
      }
      if (rst != null) {
        try {
          rst.close();
        } catch (SQLException e1) {
        }
        rst = null;
      }
      trx.rollback();
      return 0;
    }

    return 1;
  }