Exemplo 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);
    }
  }
Exemplo n.º 2
0
  /**
   * Batch update models using the attrs names of the first model in modelList. Ensure all the
   * models can use the same sql as the first model.
   */
  public int[] batchUpdate(List<? extends Model> modelList, int batchSize) {
    if (modelList == null || modelList.size() == 0) return new int[0];

    Model model = modelList.get(0);
    Table table = TableMapping.me().getTable(model.getClass());
    String[] pKeys = table.getPrimaryKey();
    Map<String, Object> attrs = model.getAttrs();
    List<String> attrNames = new ArrayList<String>();
    // the same as the iterator in Dialect.forModelSave() to ensure the order of the attrs
    for (Entry<String, Object> e : attrs.entrySet()) {
      String attr = e.getKey();
      if (config.dialect.isPrimaryKey(attr, pKeys) == false) attrNames.add(attr);
    }
    for (String pKey : pKeys) attrNames.add(pKey);
    String columns = StrKit.join(attrNames.toArray(new String[attrNames.size()]), ",");

    // update all attrs of the model not use the midifyFlag of every single model
    Set<String> modifyFlag = attrs.keySet(); // model.getModifyFlag();

    StringBuilder sql = new StringBuilder();
    List<Object> parasNoUse = new ArrayList<Object>();
    config.dialect.forModelUpdate(
        TableMapping.me().getTable(model.getClass()), attrs, modifyFlag, sql, parasNoUse);
    return batch(sql.toString(), columns, modelList, batchSize);
  }
Exemplo n.º 3
0
  @Test
  public void testMultiKeyPK() throws Exception {
    String ddl = "CREATE FOREIGN TABLE G1( e1 integer, e2 varchar, e3 date, PRIMARY KEY (e1, e2))";

    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());
  }
Exemplo n.º 4
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;
  }
Exemplo n.º 5
0
 @Test
 public void secondPrimaryKeyTableMigration() throws IOException {
   configFactory.copyRealmFromAssets(context, "0841_annotationtypes.realm", "default.realm");
   SharedGroup db =
       new SharedGroup(
           new File(configFactory.getRoot(), Realm.DEFAULT_REALM_NAME).getAbsolutePath(),
           SharedGroup.Durability.FULL,
           null);
   ImplicitTransaction tr = db.beginImplicitTransaction();
   Table t = tr.getTable("class_AnnotationTypes");
   assertEquals(t.getColumnIndex("id"), t.getPrimaryKey());
   assertTrue(t.hasPrimaryKey());
   assertEquals("AnnotationTypes", tr.getTable("pk").getString(0, 0));
   db.close();
 }
Exemplo n.º 6
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());
  }
Exemplo n.º 7
0
 public static String getPk(Table table) {
   PrimaryKey pk = table.getPrimaryKey();
   StringBuffer buf = new StringBuffer();
   buf.append("{\n");
   printJsonValue(buf, "pkName", pk.getPrimaryKeyName(), false);
   buf.append("\"columns\": [\n");
   int i = 1;
   int size = pk.getPrimaryKeyColumns().size();
   for (PrimaryKeyColumn col : pk.getPrimaryKeyColumns()) {
     buf.append("{\n");
     printJsonValue(buf, "name", col.getColumnName(), true);
     buf.append("}\n");
     if (i != size) {
       buf.append(",");
     }
     i++;
   }
   buf.append("]\n");
   buf.append("}\n");
   return buf.toString();
 }
  /**
   * Retreives a String representation of this obejct.
   *
   * <p>The returned String describes this object's table, alias access mode, index, join mode,
   * Start, End and And conditions.
   *
   * @return a String representation of this object
   */
  public String toString() {

    StringBuffer sb;
    Index index;
    Index primaryIndex;
    int[] primaryKey;
    boolean hidden;
    boolean fullScan;

    sb = new StringBuffer();
    index = filterIndex;
    primaryIndex = filterTable.getPrimaryIndex();
    primaryKey = filterTable.getPrimaryKey();
    hidden = false;
    fullScan = (eStart == null && eEnd == null);

    if (index == null) {
      index = primaryIndex;
    }

    if (index == primaryIndex && primaryKey == null) {
      hidden = true;
      fullScan = true;
    }

    sb.append(super.toString()).append('\n');
    sb.append("table=[").append(filterTable.getName().name).append("]\n");
    sb.append("alias=[").append(tableAlias).append("]\n");
    sb.append("access=[").append(fullScan ? "FULL SCAN" : "INDEX PRED").append("]\n");
    sb.append("index=[");
    sb.append(index == null ? "NONE" : index.getName() == null ? "UNNAMED" : index.getName().name);
    sb.append(hidden ? "[HIDDEN]]\n" : "]\n");
    sb.append("isOuterJoin=[").append(isOuterJoin).append("]\n");
    sb.append("eStart=[").append(eStart).append("]\n");
    sb.append("eEnd=[").append(eEnd).append("]\n");
    sb.append("eAnd=[").append(eAnd).append("]");

    return sb.toString();
  }
  private static void buildAssosiationSets(MetadataStore metadataStore, List<Builder> edmSchemas) {
    for (Schema schema : metadataStore.getSchemaList()) {

      EdmSchema.Builder odataSchema = findSchema(edmSchemas, schema.getName());
      EdmEntityContainer.Builder entityContainer =
          findEntityContainer(edmSchemas, schema.getName());
      List<EdmAssociationSet.Builder> assosiationSets = new ArrayList<EdmAssociationSet.Builder>();
      List<EdmAssociation.Builder> assosiations = new ArrayList<EdmAssociation.Builder>();

      for (Table table : schema.getTables().values()) {
        // build Associations
        for (ForeignKey fk : table.getForeignKeys()) {

          EdmEntitySet.Builder entitySet =
              findEntitySet(edmSchemas, schema.getName(), table.getName());
          EdmEntitySet.Builder refEntitySet =
              findEntitySet(edmSchemas, schema.getName(), fk.getReferenceTableName());
          EdmEntityType.Builder entityType =
              findEntityType(edmSchemas, schema.getName(), table.getName());
          EdmEntityType.Builder refEntityType =
              findEntityType(edmSchemas, schema.getName(), fk.getReferenceTableName());

          // check to see if fk is part of this table's pk, then it is 1 to 1 relation
          boolean onetoone = sameColumnSet(table.getPrimaryKey(), fk);

          // Build Association Ends
          EdmAssociationEnd.Builder endSelf =
              EdmAssociationEnd.newBuilder()
                  .setRole(table.getName())
                  .setType(entityType)
                  .setMultiplicity(onetoone ? EdmMultiplicity.ZERO_TO_ONE : EdmMultiplicity.MANY);

          EdmAssociationEnd.Builder endRef =
              EdmAssociationEnd.newBuilder()
                  .setRole(fk.getReferenceTableName())
                  .setType(refEntityType)
                  .setMultiplicity(EdmMultiplicity.ZERO_TO_ONE);

          // Build Association
          EdmAssociation.Builder association = EdmAssociation.newBuilder();
          association.setName(table.getName() + "_" + fk.getName());
          association.setEnds(endSelf, endRef);
          association.setNamespace(
              refEntityType
                  .getFullyQualifiedTypeName()
                  .substring(0, refEntityType.getFullyQualifiedTypeName().indexOf('.')));
          assosiations.add(association);

          // Build ReferentialConstraint
          if (fk.getReferenceColumns() != null) {
            EdmReferentialConstraint.Builder erc = EdmReferentialConstraint.newBuilder();
            erc.setPrincipalRole(fk.getReferenceTableName());
            erc.addPrincipalReferences(fk.getReferenceColumns());
            erc.setDependentRole(table.getName());
            erc.addDependentReferences(getColumnNames(fk.getColumns()));
            association.setRefConstraint(erc);
          }

          // Add EdmNavigationProperty to entity type
          EdmNavigationProperty.Builder nav =
              EdmNavigationProperty.newBuilder(fk.getReferenceTableName());
          nav.setRelationshipName(fk.getName());
          nav.setFromToName(table.getName(), fk.getReferenceTableName());
          nav.setRelationship(association);
          nav.setFromTo(endSelf, endRef);
          entityType.addNavigationProperties(nav);

          // Add EdmNavigationProperty to Reference entity type
          EdmNavigationProperty.Builder refNav = EdmNavigationProperty.newBuilder(table.getName());
          refNav.setRelationshipName(fk.getName());
          refNav.setFromToName(fk.getReferenceTableName(), table.getName());
          refNav.setRelationship(association);
          refNav.setFromTo(endRef, endSelf);
          refEntityType.addNavigationProperties(refNav);

          // build AssosiationSet
          EdmAssociationSet.Builder assosiationSet =
              EdmAssociationSet.newBuilder()
                  .setName(table.getName() + "_" + fk.getName())
                  .setAssociationName(fk.getName());

          // Build AssosiationSet Ends
          EdmAssociationSetEnd.Builder endOne =
              EdmAssociationSetEnd.newBuilder()
                  .setEntitySet(entitySet)
                  .setRoleName(table.getName())
                  .setRole(
                      EdmAssociationEnd.newBuilder()
                          .setType(entityType)
                          .setRole(entityType.getName()));

          EdmAssociationSetEnd.Builder endTwo =
              EdmAssociationSetEnd.newBuilder()
                  .setEntitySet(refEntitySet)
                  .setRoleName(fk.getReferenceTableName())
                  .setRole(
                      EdmAssociationEnd.newBuilder()
                          .setType(refEntityType)
                          .setRole(refEntityType.getName()));
          assosiationSet.setEnds(endOne, endTwo);

          assosiationSet.setAssociation(association);
          assosiationSets.add(assosiationSet);
        }
      }
      entityContainer.addAssociationSets(assosiationSets);
      odataSchema.addAssociations(assosiations);
    }
  }
Exemplo n.º 10
0
  private static void buildEntityTypes(
      MetadataStore metadataStore, List<EdmSchema.Builder> edmSchemas) {
    for (Schema schema : metadataStore.getSchemaList()) {

      List<EdmEntitySet.Builder> entitySets = new ArrayList<EdmEntitySet.Builder>();
      List<EdmEntityType.Builder> entityTypes = new ArrayList<EdmEntityType.Builder>();

      for (Table table : schema.getTables().values()) {

        KeyRecord primaryKey = table.getPrimaryKey();
        List<KeyRecord> uniques = table.getUniqueKeys();
        if (primaryKey == null && uniques.isEmpty()) {
          LogManager.logDetail(
              LogConstants.CTX_ODATA,
              ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16002, table.getFullName()));
          continue;
        }

        EdmEntityType.Builder entityType =
            EdmEntityType.newBuilder().setName(table.getName()).setNamespace(schema.getName());

        // adding key
        if (primaryKey != null) {
          for (Column c : primaryKey.getColumns()) {
            entityType.addKeys(c.getName());
          }
        } else {
          for (Column c : uniques.get(0).getColumns()) {
            entityType.addKeys(c.getName());
          }
        }

        // adding properties
        for (Column c : table.getColumns()) {
          EdmProperty.Builder property =
              EdmProperty.newBuilder(c.getName())
                  .setType(ODataTypeManager.odataType(c.getDatatype().getRuntimeTypeName()))
                  .setNullable(c.getNullType() == NullType.Nullable);
          if (c.getDatatype()
              .getRuntimeTypeName()
              .equals(DataTypeManager.DefaultDataTypes.STRING)) {
            property.setFixedLength(c.isFixedLength()).setMaxLength(c.getLength()).setUnicode(true);
          }
          entityType.addProperties(property);
        }

        // entity set one for one entity type
        EdmEntitySet.Builder entitySet =
            EdmEntitySet.newBuilder().setName(table.getName()).setEntityType(entityType);

        entityType.setNamespace(schema.getName());
        entitySets.add(entitySet);

        // add enitity types for entity schema
        entityTypes.add(entityType);
      }

      // entity container is holder entity sets, association sets, function imports
      EdmEntityContainer.Builder entityContainer =
          EdmEntityContainer.newBuilder()
              .setName(schema.getName())
              .setIsDefault(false)
              .addEntitySets(entitySets);

      // build entity schema
      EdmSchema.Builder modelSchema =
          EdmSchema.newBuilder()
              .setNamespace(schema.getName())
              .addEntityTypes(entityTypes)
              .addEntityContainers(entityContainer);

      edmSchemas.add(modelSchema);
    }
  }
Exemplo n.º 11
0
  /**
   * Retreives a String representation of this obejct.
   *
   * <p>The returned String describes this object's table, alias access mode, index, join mode,
   * Start, End and And conditions.
   *
   * @return a String representation of this object
   */
  public String describe(Session session) {

    StringBuffer sb;
    String temp;
    Index index;
    Index primaryIndex;
    int[] primaryKey;
    boolean hidden;
    boolean fullScan;

    sb = new StringBuffer();
    index = rangeIndex;
    primaryIndex = rangeTable.getPrimaryIndex();
    primaryKey = rangeTable.getPrimaryKey();
    hidden = false;
    fullScan = (indexCondition == null && indexEndCondition == null);

    if (index == null) {
      index = primaryIndex;
    }

    if (index == primaryIndex && primaryKey.length == 0) {
      hidden = true;
      fullScan = true;
    }

    sb.append(super.toString()).append('\n');
    sb.append("table=[").append(rangeTable.getName().name).append("]\n");

    if (tableAlias != null) {
      sb.append("alias=[").append(tableAlias.name).append("]\n");
    }

    sb.append("access=[").append(fullScan ? "FULL SCAN" : "INDEX PRED").append("]\n");
    sb.append("index=[");
    sb.append(index == null ? "NONE" : index.getName() == null ? "UNNAMED" : index.getName().name);
    sb.append(hidden ? "[HIDDEN]]\n" : "]\n");

    temp = "INNER";

    if (isLeftJoin) {
      temp = "LEFT OUTER";

      if (isRightJoin) {
        temp = "FULL";
      }
    } else if (isRightJoin) {
      temp = "RIGHT OUTER";
    }

    sb.append("joinType=[").append(temp).append("]\n");

    temp = indexCondition == null ? "null" : indexCondition.describe(session);

    if (findFirstExpressions != null) {
      StringBuffer sbt = new StringBuffer();

      for (int i = 0; i < multiColumnCount; i++) {
        sbt.append(findFirstExpressions[i].describe(session));
      }

      temp = sbt.toString();
    }

    sb.append("eStart=[").append(temp).append("]\n");

    temp = indexEndCondition == null ? "null" : indexEndCondition.describe(session);

    sb.append("eEnd=[").append(temp).append("]\n");

    temp = nonIndexJoinCondition == null ? "null" : nonIndexJoinCondition.describe(session);

    sb.append("eAnd=[").append(temp).append("]");

    return sb.toString();
  }
Exemplo n.º 12
0
  /**
   * VoltDB added method to get a non-catalog-dependent representation of this HSQLDB object.
   *
   * @param session The current Session object may be needed to resolve some names.
   * @param indent A string of whitespace to be prepended to every line in the resulting XML.
   * @return XML, correctly indented, representing this object.
   * @throws HSQLParseException
   */
  String voltGetXML(Session session, String orig_indent) throws HSQLParseException {
    StringBuffer sb;
    Index index;
    Index primaryIndex;
    int[] primaryKey;
    boolean isSeqScan;

    sb = new StringBuffer();
    index = rangeIndex;
    primaryIndex = rangeTable.getPrimaryIndex();
    primaryKey = rangeTable.getPrimaryKey();
    isSeqScan = indexCondition == null;
    String indent = orig_indent + HSQLInterface.XML_INDENT;

    // get the index for this scan (/filter)
    // note: ignored if scan if full table scan
    if (index == null) index = primaryIndex;

    // check if this is a sequential scan
    if (index == primaryIndex && primaryKey.length == 0) isSeqScan = true;

    // output open tag + metadata
    sb.append(orig_indent + "<tablescan type=\"");
    if (isSeqScan) sb.append("sequential\" ");
    else sb.append("index\" ");
    sb.append("table=\"").append(rangeTable.getName().name).append("\"");
    if ((index != null) && (isSeqScan == false)) {
      String indexName = (index.getName() == null ? "UNNAMED" : index.getName().name);
      sb.append(" index=\"").append(indexName).append("\"");
    }
    if (tableAlias != null && !rangeTable.getName().name.equals(tableAlias))
      sb.append(" alias=\"").append(tableAlias).append("\"");

    // note if this is an outer join
    if (isLeftJoin || isRightJoin) {
      sb.append(" isouterjoin=\"true\"");
    }
    sb.append(">\n");

    // start with the indexCondition
    Expression cond = indexCondition;
    // then go to the indexEndCondition
    if (indexEndCondition != null) {
      if (cond != null) {
        cond = new ExpressionLogical(OpTypes.AND, cond, indexEndCondition);
      } else {
        cond = indexEndCondition;
      }
    }
    // then go to the nonIndexJoinCondition
    if (nonIndexJoinCondition != null) {
      if (cond != null) {
        cond = new ExpressionLogical(OpTypes.AND, cond, nonIndexJoinCondition);
      } else {
        cond = nonIndexJoinCondition;
      }
    }
    // then go to the nonIndexWhereCondition
    if (nonIndexWhereCondition != null) {
      if (cond != null) {
        cond = new ExpressionLogical(OpTypes.AND, cond, nonIndexWhereCondition);
      } else {
        cond = nonIndexWhereCondition;
      }
    }

    //
    // END EXPRESSION
    //
    if (indexEndCondition != null) {
      sb.append(indent + "<postexp>\n");
      sb.append(cond.voltGetXML(session, indent + HSQLInterface.XML_INDENT)).append("\n");
      sb.append(indent + "</postexp>\n");
    }

    sb.append(orig_indent + "</tablescan>");

    return sb.toString();
  }
Exemplo n.º 13
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());
  }
Exemplo n.º 14
0
  /**
   * 事实表和关联报表属于当前传入数组的交叉报表
   *
   * @param request
   * @param tables elements are table.id
   * @return elements are ArrayList, first is cxtab id, second is cxtab name
   */
  public List getCxtabs(HttpServletRequest request, List<Integer> tables) {
    TableManager manager = TableManager.getInstance();
    UserWebImpl userWeb =
        ((UserWebImpl)
            WebUtils.getSessionContextManager(request.getSession())
                .getActor(nds.util.WebKeys.USER));
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < tables.size(); i++) {
      // Table t= tables.get(i);
      if (i > 0) sb.append(",");
      sb.append(tables.get(i));
    }
    String ts = sb.toString();
    try {
      Table cxtabTable = manager.getTable("AD_CXTAB");
      QueryRequestImpl queryData;
      // only pk,dk will be selected, order by ak asc
      queryData = QueryEngine.getInstance().createRequest(userWeb.getSession());
      queryData.setMainTable(cxtabTable.getId());

      queryData.addSelection(cxtabTable.getPrimaryKey().getId());
      queryData.addSelection(cxtabTable.getDisplayKey().getId());

      Column colOrderNo = cxtabTable.getColumn("orderno");
      queryData.setOrderBy(new int[] {colOrderNo.getId()}, true);
      queryData.setRange(0, Integer.MAX_VALUE);

      Expression expr =
          new Expression(
              null,
              "(AD_CXTAB.AD_TABLE_ID in ("
                  + ts
                  + ") or exists (select 1 from ad_cxtab_reftable r where r.ad_cxtab_id=AD_CXTAB.id and r.ad_table_id in ("
                  + ts
                  + ")))",
              null);

      // set reporttype to "S"
      expr =
          expr.combine(
              new Expression(new ColumnLink("AD_CXTAB.REPORTTYPE"), "=S", null),
              SQLCombination.SQL_AND,
              null);
      expr =
          expr.combine(
              new Expression(new ColumnLink("AD_CXTAB.ISACTIVE"), "=Y", null),
              SQLCombination.SQL_AND,
              null);
      expr =
          expr.combine(
              new Expression(new ColumnLink("AD_CXTAB.ISPUBLIC"), "=Y", null),
              SQLCombination.SQL_AND,
              null);
      expr =
          expr.combine(
              userWeb.getSecurityFilter(cxtabTable.getName(), 1), SQLCombination.SQL_AND, null);
      queryData.addParam(expr); // read permission

      return QueryEngine.getInstance().doQueryList(queryData.toSQL());
    } catch (Throwable t) {
      logger.error(
          "Fail to load reports for user " + userWeb.getUserId() + " with table ids: " + ts, t);
    }
    return Collections.EMPTY_LIST;
  }