Esempio n. 1
0
  private void buildContraints(Table table) {
    addConstraints(table.getAccessPatterns(), "AP", ACCESSPATTERN); // $NON-NLS-1$

    KeyRecord pk = table.getPrimaryKey();
    if (pk != null) {
      addConstraint("PK", PRIMARY_KEY, pk, true); // $NON-NLS-1$
    }

    addConstraints(table.getUniqueKeys(), UNIQUE, UNIQUE);
    addConstraints(table.getIndexes(), INDEX, INDEX);
    addConstraints(table.getFunctionBasedIndexes(), INDEX, INDEX);

    for (int i = 0; i < table.getForeignKeys().size(); i++) {
      ForeignKey key = table.getForeignKeys().get(i);
      addConstraint("FK" + i, FOREIGN_KEY, key, false); // $NON-NLS-1$
      append(SPACE).append(REFERENCES);
      if (key.getReferenceKey() != null) {
        if (key.getReferenceKey().getParent().getParent().equals(key.getParent().getParent())) {
          append(SPACE).append(new GroupSymbol(key.getReferenceKey().getParent().getName()));
        } else {
          append(SPACE).append(new GroupSymbol(key.getReferenceKey().getParent().getFullName()));
        }
      } else if (key.getReferenceTableName() != null) {
        append(SPACE).append(new GroupSymbol(key.getReferenceTableName()));
      }
      append(SPACE);
      addNames(key.getReferenceColumns());
      appendOptions(key);
    }
  }
Esempio n. 2
0
  /**
   * Called when the column is removed from its table. Removes the column from all table constraints
   * and indexes, then invalidates it.
   */
  void remove() {
    Table table = getTable();
    if (table == null) return;

    Schema schema = table.getSchema();
    if (schema != null && schema.getSchemaGroup() != null) {
      Schema[] schemas = schema.getSchemaGroup().getSchemas();
      Table[] tabs;
      ForeignKey[] fks;
      Column[] cols;
      Column[] pks;
      for (int i = 0; i < schemas.length; i++) {
        tabs = schemas[i].getTables();
        for (int j = 0; j < tabs.length; j++) {
          fks = tabs[j].getForeignKeys();
          for (int k = 0; k < fks.length; k++) {
            cols = fks[k].getColumns();
            pks = fks[k].getPrimaryKeyColumns();
            for (int l = 0; l < cols.length; l++)
              if (this.equals(cols[l]) || this.equals(pks[l])) fks[k].removeJoin(cols[l]);

            cols = fks[k].getConstantColumns();
            for (int l = 0; l < cols.length; l++)
              if (this.equals(cols[l])) fks[k].removeJoin(cols[l]);

            pks = fks[k].getConstantPrimaryKeyColumns();
            for (int l = 0; l < pks.length; l++) if (this.equals(pks[l])) fks[k].removeJoin(pks[l]);

            if (fks[k].getColumns().length == 0 && fks[k].getConstantColumns().length == 0)
              tabs[j].removeForeignKey(fks[k]);
          }
        }
      }
    }

    Index[] idxs = table.getIndexes();
    for (int i = 0; i < idxs.length; i++)
      if (idxs[i].removeColumn(this) && idxs[i].getColumns().length == 0)
        table.removeIndex(idxs[i]);

    Unique[] unqs = table.getUniques();
    for (int i = 0; i < unqs.length; i++)
      if (unqs[i].removeColumn(this) && unqs[i].getColumns().length == 0)
        table.removeUnique(unqs[i]);

    PrimaryKey pk = table.getPrimaryKey();
    if (pk != null && pk.removeColumn(this) && pk.getColumns().length == 0)
      table.removePrimaryKey();

    _table = null;
  }
Esempio n. 3
0
  @Test
  public void testConstraints() throws Exception {
    String ddl =
        "CREATE FOREIGN TABLE G1( e1 integer, e2 varchar, e3 date, "
            + " PRIMARY KEY (e1, e2), INDEX(e2, e3), ACCESSPATTERN(e1), UNIQUE(e1),"
            + " ACCESSPATTERN(e2, e3))";

    Schema s = helpParse(ddl, "model").getSchema();
    Map<String, Table> tableMap = s.getTables();

    assertTrue("Table not found", tableMap.containsKey("G1"));
    Table table = tableMap.get("G1");

    assertEquals(table.getColumns().subList(0, 2), table.getPrimaryKey().getColumns());
    assertEquals(table.getColumns().subList(1, 3), table.getIndexes().get(0).getColumns());
    assertEquals(table.getColumns().subList(0, 1), table.getUniqueKeys().get(0).getColumns());
    assertEquals(2, table.getAccessPatterns().size());
    assertEquals(table.getColumns().subList(0, 1), table.getAccessPatterns().get(0).getColumns());
    assertEquals(table.getColumns().subList(1, 3), table.getAccessPatterns().get(1).getColumns());
  }
Esempio n. 4
0
  @Test
  public void testForeignTable() throws Exception {

    String ddl =
        "CREATE FOREIGN TABLE G1(\n"
            + "e1 integer primary key,\n"
            + "e2 varchar(10) unique,\n"
            + "e3 date not null unique,\n"
            + "e4 decimal(12,3) default 12.2 options (searchable 'unsearchable'),\n"
            + "e5 integer auto_increment INDEX OPTIONS (UUID 'uuid', NAMEINSOURCE 'nis', SELECTABLE 'NO'),\n"
            + "e6 varchar index default 'hello')\n"
            + "OPTIONS (CARDINALITY 12, UUID 'uuid2',  UPDATABLE 'true', FOO 'BAR', ANNOTATION 'Test Table')";

    Schema s = helpParse(ddl, "model").getSchema();
    Map<String, Table> tableMap = s.getTables();

    assertTrue("Table not found", tableMap.containsKey("G1"));
    Table table = tableMap.get("G1");
    assertTrue(table.isPhysical());
    assertFalse(table.isVirtual());
    assertFalse(table.isSystem());
    assertFalse(table.isMaterialized());
    assertFalse(table.isDeletePlanEnabled());
    assertEquals("uuid2", table.getUUID());
    assertEquals(12, table.getCardinality());
    assertTrue(table.supportsUpdate());
    assertEquals("BAR", table.getProperties().get("FOO"));
    assertEquals("Test Table", table.getAnnotation());

    assertEquals(6, table.getColumns().size());

    List<Column> columns = table.getColumns();
    Column e1 = columns.get(0);
    Column e2 = columns.get(1);
    Column e3 = columns.get(2);
    Column e4 = columns.get(3);
    Column e5 = columns.get(4);
    Column e6 = columns.get(5);

    assertEquals("e1", e1.getName());
    assertEquals("int", e1.getDatatype().getName());
    assertEquals("primary key not same", e1, table.getPrimaryKey().getColumns().get(0));

    assertEquals("e2", e2.getName());
    assertEquals("string", e2.getDatatype().getName());
    assertEquals("unique", e2, table.getUniqueKeys().get(0).getColumns().get(0));
    assertEquals(NullType.Nullable, e2.getNullType());
    assertEquals(10, e2.getLength());
    assertEquals(0, e2.getPrecision());

    assertEquals("e3", e3.getName());
    assertEquals("date", e3.getDatatype().getName());
    assertEquals("unique", e3, table.getUniqueKeys().get(1).getColumns().get(0));
    assertEquals(NullType.No_Nulls, e3.getNullType());

    assertEquals("e4", e4.getName());
    assertEquals("bigdecimal", e4.getDatatype().getName());
    assertEquals(false, e4.isAutoIncremented());
    assertEquals(12, e4.getPrecision());
    assertEquals(3, e4.getScale());
    assertEquals(SearchType.Unsearchable, e4.getSearchType());
    assertEquals("12.2", e4.getDefaultValue());

    assertEquals("e5", e5.getName());
    assertEquals("int", e5.getDatatype().getName());
    assertEquals(true, e5.isAutoIncremented());
    assertEquals("uuid", e5.getUUID());
    assertEquals("nis", e5.getNameInSource());
    assertEquals(false, e5.isSelectable());
    assertEquals("index", e5, table.getIndexes().get(0).getColumns().get(0));

    assertEquals("e6", e6.getName());
    assertEquals("string", e6.getDatatype().getName());
    assertEquals("index", e6, table.getIndexes().get(1).getColumns().get(0));
    assertEquals("hello", e6.getDefaultValue());
  }
Esempio n. 5
0
  protected boolean doSetup(
      Object source,
      String database,
      String username,
      String password,
      String table,
      boolean doDelete)
      throws ClassNotFoundException, IOException, SQLException {
    try {
      Document doc = null;
      if (source instanceof String) {
        doc = this.readDocument((String) source);
      } else if (source instanceof InputStream) {
        doc = this.readDocument((InputStream) source);
      }

      // //////////////////////////////////////////////////////
      // Make sure we can connect to the database

      JDBC.loadDriver(database);
      if (this.isQuiet() == false) System.out.println("Successfully loaded the database driver.");

      m_conn = connect(database, username, password);
      if (this.isQuiet() == false) System.out.println("Successfully connected to the database.");

      Collection collTypeMaps = null;
      if (m_typeMapFile != null) {
        collTypeMaps = TypeMap.readTypeMaps(readDocument(m_typeMapFile).getFirstChild());
      } else if (m_typeMapStream != null) {
        collTypeMaps = TypeMap.readTypeMaps(readDocument(m_typeMapStream).getFirstChild());
      } else {
        collTypeMaps = TypeMap.readTypeMaps(doc.getFirstChild());
      }

      /**
       * // check to see if we're dealing with a view or a table Node dbSetupNode =
       * doc.getFirstChild(); // actually, its the first child of the main node in the schema
       *
       * <p>NodeList nodeList = dbSetupNode.getChildNodes(); for(int i=0;i < nodeList.getLength();
       * i++) { Node rootNode = nodeList.item(i);
       * if(rootNode.getNodeName().equalsIgnoreCase("table")) {
       */
      Node rootNode = doc.getFirstChild();
      Iterator iterTab = Table.getTables(rootNode, JDBC.toType(database), this).iterator();

      // /////////////////////////////////////////////////////////////////
      // Open the log file if we are supposed to log SQL statements.
      if (m_logFileName != null) {
        m_log = new FileWriter(m_logFileName, m_logAppend);
      }

      while (iterTab.hasNext() == true) {
        Table tab = (Table) iterTab.next();

        if (table != null) {
          if (!table.equals(tab.getName())) {
            continue;
          }
          if (doDelete) tab.clear();
        }

        if (this.isVerbose() == true) System.out.println("Processing Table: " + tab.getName());

        if (m_bDMLonly == false) {
          // ////////////////////////////////////////////////////////////
          // Create the Table
          try {
            // Only attempt to create the table if the table tag has columns

            if (tab.getColumns().size() > 0) {
              tab.create(collTypeMaps);

              if (this.isQuiet() == false) System.out.println("Created Table: " + tab.getName());

              this.m_lCreatedTables++;
            }
          } catch (SQLException e) {
            if (this.isQuiet() == false) {
              System.out.println("Error: " + "Cannot create table " + tab.getName());
              JDBC.printSQLException(e);
            }

            this.m_lFailedTables++;
          }

          // /////////////////////////////////////////////////////////////
          // Create the Indexes

          Iterator iterCol = tab.getIndexes().iterator();

          while (iterCol.hasNext() == true) {
            Index idx = (Index) iterCol.next();

            try {
              idx.create();

              if (this.isQuiet() == false)
                System.out.println(
                    "Created Index: "
                        + idx.getName()
                        + " for Table \'"
                        + idx.getTable().getName()
                        + '\'');

              this.m_lCreatedIndexes++;
            } catch (SQLException e) {
              if (this.isQuiet() == false) {
                System.out.println("Error: Cannot create index " + idx.getName());
                JDBC.printSQLException(e);
              }

              this.m_lFailedIndexes++;
            }
          }
        }

        // ////////////////////////////////////////////////////////////
        // Create the Data

        DataSet dataset = tab.getDataSet();

        try {
          int iRowCnt = dataset.create();

          if (this.isQuiet() == false) System.out.println("Created " + iRowCnt + " Row(s).");
        } catch (SQLException e) {
          if (this.isQuiet() == false) {
            System.out.println("Error: " + "Cannot create Row.");
            JDBC.printSQLException(e);

            if (this.isVerbose() == true) e.printStackTrace();
          }
        }
      }
      // }

      // if(rootNode.getNodeName().equalsIgnoreCase("view")) {
      // process views
      Iterator iterView = View.getViews(rootNode, JDBC.toType(database), this).iterator();
      // //////////////////////////////////////////////////
      // /////////////
      // Open the log file if we are supposed to log SQL statements.
      if (m_logFileName != null) {
        m_log = new FileWriter(m_logFileName, m_logAppend);
      }

      while (iterView.hasNext() == true) {
        View view = (View) iterView.next();

        if (this.isVerbose() == true) System.out.println("Processing view: " + view.getName());

        if (m_bDMLonly == false) {
          // //////////////////////////////////////////
          // ////////////////
          // Create the View
          try {
            view.create(collTypeMaps);

            if (this.isQuiet() == false) System.out.println("Created View: " + view.getName());

            this.m_lCreatedViews++;
          } catch (SQLException e) {
            if (this.isQuiet() == false) {
              System.out.println("Error: " + "Cannot create View.");
              JDBC.printSQLException(e);

              if (this.isVerbose() == true) e.printStackTrace();
            }
          }
        }
      }
      // }
      // }

      // ////////////////////////////////////////////////////////////
      // Print Results

      if (this.isQuiet() == false) {
        DecimalFormat fmt = new DecimalFormat("#,###");

        System.out.println();
        System.out.println(fmt.format(this.m_lCreatedTables) + " tables created succesfully.");
        System.out.println(fmt.format(this.m_lCreatedViews) + " views created succesfully.");
        System.out.println(fmt.format(this.m_lCreatedIndexes) + " indexes created successfully.");
        System.out.println(fmt.format(this.m_lFailedTables) + " tables failed to create.");
        System.out.println(fmt.format(this.m_lFailedIndexes) + " indexes failed to create.");
      }
    } catch (SAXException e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    } finally {
      if (m_log != null) {
        try {
          m_log.close();
        } catch (Exception e) {
        }
      }

      try {
        if (m_conn != null) m_conn.close();
      } catch (SQLException e) {
      }
    }

    return true;
  }