/** Creates a non unique index for the given table. */
  private void createNonUnique(Table t) throws SQLException {
    boolean comma = false;
    int indexNumber = 1;

    Iterator<Key> j = t.getKeys().iterator();

    while (j.hasNext()) {
      Key key = j.next();
      if (key.getType() == Key.NonUnique) {
        String SQL = "CREATE INDEX " + t.getName() + "_" + indexNumber;
        SQL += " ON " + t.getSchema() + "." + t.getName() + "(";

        Iterator<Column> i = key.getColumns().iterator();
        comma = false;
        while (i.hasNext()) {
          Column c = i.next();
          SQL += (comma ? ", " : "") + c.getName();
          comma = true;
        }
        indexNumber++;
        SQL += ")";
        execute(SQL);
      }
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     com.continuent.tungsten.replicator.database.AbstractDatabase#createTable(com.continuent.tungsten.replicator.database.Table,
   *     boolean, java.lang.String)
   */
  @Override
  public void createTable(Table t, boolean replace) throws SQLException {
    boolean comma = false;
    boolean hasNonUnique = false;

    if (replace) dropTable(t);
    else {
      // If table already exists, do nothing. This behavior is a mimic of
      // MySQLDatabase for initial configuration to work. For some reason,
      // Replicator is trying to create Tungsten tables more than once.
      if (tableExists(t)) return;
    }

    String temporary = t.isTemporary() ? "TEMPORARY " : "";
    // Temporary tables cannot specify a schema name:
    String SQL =
        "CREATE "
            + temporary
            + "TABLE "
            + t.getSchema()
            + (t.isTemporary() ? "_" : ".")
            + t.getName()
            + " (";

    Iterator<Column> i = t.getAllColumns().iterator();
    while (i.hasNext()) {
      Column c = i.next();
      SQL +=
          (comma ? ", " : "")
              + c.getName()
              + " "
              + columnToTypeString(c)
              + (c.isNotNull() ? " NOT NULL" : "");
      comma = true;
    }
    Iterator<Key> j = t.getKeys().iterator();

    while (j.hasNext()) {
      Key key = j.next();
      if (key.getType() == Key.NonUnique) {
        // Non-unique keys will be created with a separate CREATE
        // INDEX statement.
        hasNonUnique = true;
        continue;
      }
      SQL += ", ";
      switch (key.getType()) {
        case Key.Primary:
          SQL += "PRIMARY KEY (";
          break;
        case Key.Unique:
          SQL += "UNIQUE (";
          break;
      }
      i = key.getColumns().iterator();
      comma = false;
      while (i.hasNext()) {
        Column c = i.next();
        SQL += (comma ? ", " : "") + c.getName();
        comma = true;
      }
      SQL += ")";
    }
    SQL += ")";

    // Create the table.
    execute(SQL);

    // Create non-unique keys.
    if (hasNonUnique) createNonUnique(t);
  }