Query the las level table.

@param db the db to use.
@param levelNum the level to query.
@param envelope an optional {@link Envelope} to query spatially.
@return the list of extracted level cells.
@throws Exception
180516
public static List<LasLevel> getLasLevels( ASpatialDb db, int levelNum, Envelope envelope ) throws Exception {
        String tableName = TABLENAME + levelNum;
        List<LasLevel> lasLevels = new ArrayList<>();
        String sql = "SELECT " + COLUMN_GEOM + "," + //
                COLUMN_ID + "," + COLUMN_SOURCE_ID + "," + COLUMN_AVG_ELEV + "," + //
                COLUMN_MIN_ELEV + "," + //
                COLUMN_MAX_ELEV + "," + //
                COLUMN_AVG_INTENSITY + "," + //
                COLUMN_MIN_INTENSITY + "," + //
                COLUMN_MAX_INTENSITY;

        sql += " FROM " + tableName;

        if (envelope != null) {
            double x1 = envelope.getMinX();
            double y1 = envelope.getMinY();
            double x2 = envelope.getMaxX();
            double y2 = envelope.getMaxY();
            sql += " WHERE " + db.getSpatialindexBBoxWherePiece(tableName, null, x1, y1, x2, y2);
        }

        String _sql = sql;
        IGeometryParser gp = db.getType().getGeometryParser();
        return db.execOnConnection(conn -> {
            try (IHMStatement stmt = conn.createStatement(); IHMResultSet rs = stmt.executeQuery(_sql)) {
                while( rs.next() ) {
                    LasLevel lasLevel = new LasLevel();
                    lasLevel.level = levelNum;
                    int i = 1;
                    Geometry geometry = gp.fromResultSet(rs, i++);
                    if (geometry instanceof Polygon) {
                        Polygon polygon = (Polygon) geometry;
                        lasLevel.polygon = polygon;
                        lasLevel.id = rs.getLong(i++);
                        lasLevel.sourceId = rs.getLong(i++);
                        lasLevel.avgElev = rs.getDouble(i++);
                        lasLevel.minElev = rs.getDouble(i++);
                        lasLevel.maxElev = rs.getDouble(i++);
                        lasLevel.avgIntensity = rs.getShort(i++);
                        lasLevel.minIntensity = rs.getShort(i++);
                        lasLevel.maxIntensity = rs.getShort(i++);
                        lasLevels.add(lasLevel);
                    }
                }
                return lasLevels;
            }
        });

    }
490808
function get_db (ent, done) {
    var folder = internals.makefolderpath(opts.folder, ent)
    var db = dbmap[folder]
    if (db) {
      return done(null, db)
    }
    internals.ensurefolder(folder, internals.error(done, function () {
      db = dbmap[folder]
      if (db) {
        return done(null, db)
      }
      try {
        db = dbmap[folder] = LevelQuery(Levelup(folder, opts))
        db.query.use(JsonqueryEngine())
      }
      catch (e) {
        db = dbmap[folder]
        if (db) {
          return done(null, db)
        }
        return done(e)
      }
      return done(null, db)
    }))
  }
871768
private void analyzeAutoGeneratedQueries(long corpusID)
  {
    // read the example queries from the staging area
    List<ExampleQuery> exampleQueries = getJdbcTemplate().query(
      "SELECT * FROM _" + EXAMPLE_QUERIES_TAB, new RowMapper<ExampleQuery>()
      {
        @Override
        public ExampleQuery mapRow(ResultSet rs, int i) throws SQLException
        {
          ExampleQuery eQ = new ExampleQuery();
          eQ.setExampleQuery(rs.getString("example_query"));
          return eQ;
        }
      });

    // count the nodes of the aql Query
    countExampleQueryNodes(exampleQueries);

    // fetch the operators
    getOperators(exampleQueries, "\\.(\\*)?|\\>|\\>\\*|_i_");

    writeAmountOfNodesBack(exampleQueries);
  }
1371749
public function findByLevels($levels = 1, $ids = array())
    {
        $query = $this->createQueryBuilder('c');

        if ($levels > 0) {
            $selects = ['c'];
            for ($i = 1; $i <= $levels; ++$i) {
                $selects[] = 'c'.$i;
            }

            $query->select($selects);

            for ($i = 1; $i <= $levels; ++$i) {
                $previous = ($i - 1 == 0) ? '' : ($i - 1);
                $query->leftJoin('c'.$previous.'.children', 'c'.$i, 'WITH', 'c'.$i.'.active = :active AND c'.$i.'.showInNavigation = :show');
            }
        }

        if ($ids) {
            $query->andWhere('c.id IN (:ids)')->setParameter('ids', $ids);
        } else {
            $query->andWhere('c.parent IS NULL');
        }

        $query->andWhere('c.active = :active')->setParameter('active', true);
        $query->andWhere('c.layout = :layout')->setParameter('layout', false);
        $query->andWhere('c.showInNavigation = :show')->setParameter('show', true);

        return $query->getQuery()->getResult();
    }
1001710
LevelDBTypeInfo getTypeInfo(Class<?> type) throws Exception {
    LevelDBTypeInfo ti = types.get(type);
    if (ti == null) {
      LevelDBTypeInfo tmp = new LevelDBTypeInfo(this, type, getTypeAlias(type));
      ti = types.putIfAbsent(type, tmp);
      if (ti == null) {
        ti = tmp;
      }
    }
    return ti;
  }
1153142
@Override
    public boolean supportsTransactionIsolationLevel(int level) throws SQLException
    {
        checkClosed();
        if (level == Connection.TRANSACTION_SERIALIZABLE)
            return true;
        return false;
    }
460172
@Override
    public List<Integer> getStepThreadInstancePartitionNumbersOfRelatedCompletedPartitions(
                                                                                           final StepThreadInstanceKey topLevelKey) {

        final EntityManager em = getPsu().createEntityManager();

        try {
            List<Integer> exec = new TranRequest<List<Integer>>(em) {
                @Override
                public List<Integer> call() throws Exception {
                    TypedQuery<Integer> query = em.createNamedQuery(TopLevelStepInstanceEntity.GET_RELATED_PARTITION_LEVEL_COMPLETED_PARTITION_NUMBERS,
                                                                    Integer.class);
                    query.setParameter("instanceId", topLevelKey.getJobInstance());
                    query.setParameter("stepName", topLevelKey.getStepName());

                    return query.getResultList();
                }
            }.runInNewOrExistingGlobalTran();
            return exec;
        } finally {
            em.close();
        }

    }
204134
public List<ExtendedRelation> getTableRelations(String table)
			throws SQLException {

		QueryBuilder<ExtendedRelation, Long> qb = queryBuilder();
		qb.where().like(ExtendedRelation.COLUMN_BASE_TABLE_NAME, table).or()
				.like(ExtendedRelation.COLUMN_RELATED_TABLE_NAME, table);
		PreparedQuery<ExtendedRelation> preparedQuery = qb.prepare();

		return query(preparedQuery);
	}
1270900
@SuppressWarnings("unchecked")
    private static <T> T getHighLevelElementByServiceImplBean(String portLink, Adaptable containerToAdapt, Class<T> clazz, LinkType linkType) throws UnableToAdaptException {
        if (null == portLink) {
            return null;
        }
        if (PortComponent.class.isAssignableFrom(clazz)
            || WebserviceDescription.class.isAssignableFrom(clazz)) {
            Webservices wsXml = containerToAdapt.adapt(Webservices.class);
            if (null == wsXml) {
                return null;
            }
            for (WebserviceDescription wsDes : wsXml.getWebServiceDescriptions()) {
                if (wsDes.getPortComponents().size() == 0) {
                    continue;
                }
                for (PortComponent portCmpt : wsDes.getPortComponents()) {
                    ServiceImplBean servImplBean = portCmpt.getServiceImplBean();

                    String serviceLink = LinkType.SERVLET == linkType ? servImplBean.getServletLink() : servImplBean.getEJBLink();

                    if (serviceLink == null) {
                        continue;
                    } else if (serviceLink.equals(portLink)) {
                        if (PortComponent.class.isAssignableFrom(clazz)) {
                            return (T) portCmpt;
                        } else {
                            return (T) wsDes;
                        }
                    }
                }
            }
            return null;
        }
        return null;
    }
615689
@Override
    public final <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)
    {
        return super.findAll(entityClass, columnsToSelect, rowIds);
    }
1039484
function levelsToSelect($levelIds, $mode)
    {
        $levelsToSelect = array();
        foreach ($this->schema->getLevels() as $level) {
            if (self::INCLUDE_PARTIALS == $mode && !$levelIds[$level]) {
                continue;
            }
            if (self::INCLUDE_PARTIALS == $mode && !$levelIds[$level]) {
                continue;
            }
            array_push($levelsToSelect, $level);
        }
        return $levelsToSelect;
    }
341930
VoltXMLElement voltGetRangeVariableXML(Session session)
    throws org.hsqldb_voltpatches.HSQLInterface.HSQLParseException
    {
        Index        index;
        Index        primaryIndex;

        index        = rangeIndex;
        primaryIndex = rangeTable.getPrimaryIndex();

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

        // output open tag
        VoltXMLElement scan = new VoltXMLElement("tablescan");

        if (rangeTable.tableType == TableBase.SYSTEM_SUBQUERY) {
            if (rangeTable instanceof TableDerived) {
                if (tableAlias == null || tableAlias.name == null) {
                    // VoltDB require derived sub select table with user specified alias
                    throw new org.hsqldb_voltpatches.HSQLInterface.HSQLParseException(
                            "SQL Syntax error: Every derived table must have its own alias.");
                }
                scan.attributes.put("table", tableAlias.name.toUpperCase());

                VoltXMLElement subQuery = ((TableDerived) rangeTable).dataExpression.voltGetXML(session);
                scan.children.add(subQuery);
            }
        } else {
            scan.attributes.put("table", rangeTable.getName().name.toUpperCase());
        }

        if (tableAlias != null && !rangeTable.getName().name.equals(tableAlias)) {
            scan.attributes.put("tablealias", tableAlias.name.toUpperCase());
        }

        // note if this is an outer join
        if (isLeftJoin && isRightJoin) {
            scan.attributes.put("jointype", "full");
        } else if (isLeftJoin) {
            scan.attributes.put("jointype", "left");
        } else if (isRightJoin) {
            scan.attributes.put("jointype", "right");
        } else {
            scan.attributes.put("jointype", "inner");
        }

        Expression joinCond = null;
        Expression whereCond = null;
        // if isJoinIndex and indexCondition are set then indexCondition is join condition
        // else if indexCondition is set then it is where condition
        if (isJoinIndex == true) {
            joinCond = indexCondition;
            if (indexEndCondition != null) {
            	joinCond = makeConjunction(joinCond, indexEndCondition);
            }
            // then go to the nonIndexJoinCondition
            if (nonIndexJoinCondition != null) {
            	joinCond = makeConjunction(joinCond, nonIndexJoinCondition);
            }
            // then go to the nonIndexWhereCondition
            whereCond = nonIndexWhereCondition;
        } else {
            joinCond = nonIndexJoinCondition;

            whereCond = indexCondition;
            if (indexEndCondition != null) {
            	whereCond = makeConjunction(whereCond, indexEndCondition);
            }
            // then go to the nonIndexWhereCondition
            if (nonIndexWhereCondition != null) {
            	whereCond = makeConjunction(whereCond, nonIndexWhereCondition);
            }

        }
        if (joinCond != null) {
            joinCond = joinCond.eliminateDuplicates(session);
            VoltXMLElement joinCondEl = new VoltXMLElement("joincond");
            joinCondEl.children.add(joinCond.voltGetXML(session));
            scan.children.add(joinCondEl);
        }

        if (whereCond != null) {
            whereCond = whereCond.eliminateDuplicates(session);
            VoltXMLElement whereCondEl = new VoltXMLElement("wherecond");
            whereCondEl.children.add(whereCond.voltGetXML(session));
            scan.children.add(whereCondEl);
        }

        return scan;
    }
862712
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        Object connection = getConnection();
        List results = new ArrayList();
        try
        {
            for (Object key : keys)
            {
                Object result = fetch(entityClass, key, connection, null);
                if (result != null)
                {
                    results.add(result);
                }
            }
        }
        catch (InstantiationException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        catch (IllegalAccessException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        return results;
    }
280674
@Override
    public SequenceRange get(String schemaName, String tableName, int step) throws Exception {
        Map<String, String> param = new HashMap<>();
        param.put("clientId", clientId);
        param.put("accessToken", accessToken);
        param.put("schemaName", schemaName);
        param.put("tableName", tableName);
        param.put("step", String.valueOf(step));
        String result = HttpUtils.sendPost(accessUrl, param);
        Map<String, String> resultMap = parseHttpKvString(result);
        if (resultMap.isEmpty()) {
            return null;
        } else {
            if (resultMap.get("errorCode") != null) {
                authorize();
                result = HttpUtils.sendPost(accessUrl, param);
                resultMap = parseHttpKvString(result);
                if (resultMap.get("errorCode") != null) {
                    throw new GetSequenceFailedException("clientId:" + clientId
                                                         + " access data failed, return message is:" + result);
                }
            }
            SequenceRange sequenceRange = new SequenceRange();
            sequenceRange.setBeginValue(parseLong(resultMap.get("beginValue")));
            sequenceRange.setEndValue(parseLong(resultMap.get("endValue")));
            return sequenceRange;
        }
    }
736166
public final void loadSqlTables() throws Exception {
    for (Class<?> clazz : this.mngSettings.getClasses()) {
      TableSql tableSql = new TableSql();
      makeTableSqlFromXml(tableSql, clazz);
      this.tablesMap.put(clazz.getSimpleName(), tableSql);
    }
    for (Class<?> clazz : this.mngSettings.getClasses()) {
      TableSql tableSql = this.tablesMap.get(clazz.getSimpleName());
      StringBuffer sbIdNamesUc = new StringBuffer("");
      for (int i = 0; i < tableSql.getIdColumnsNames().length; i++) {
        if (i > 0) {
          sbIdNamesUc.append(",");
        }
        sbIdNamesUc.append(tableSql.getIdColumnsNames()[i].toUpperCase());
      }
      Field[] fields = getUtlReflection().retrieveFields(clazz);
      for (Field field : fields) {
        FieldSql fieldSql = tableSql.getFieldsMap().get(field.getName());
        if (fieldSql != null) { //if persistable or composite (foreign CID)
          String fldTypeSmpNm = field.getType().getSimpleName();
          try {
            TableSql tableSqlForeign = this.tablesMap.get(fldTypeSmpNm);
            if (tableSqlForeign != null) {
              //if it's foreign entity according entities list ORDER
              //make sure ORDER of entities!!!
              fieldSql.setForeignEntity(fldTypeSmpNm);
              String isNullableStr = this.mngSettings
                .lazFldSts(clazz, field.getName()).get("isNullable");
              if (fieldSql.getDefinition() != null // FK composite ID
                && !Boolean.valueOf(isNullableStr)
                  && !fieldSql.getDefinition().contains("not null")) {
                fieldSql.setDefinition(fieldSql.getDefinition() + " not null");
              }
              //FK:
              StringBuffer sbForeignIdNamesUc = new StringBuffer("");
              for (int i = 0; i < tableSqlForeign.getIdColumnsNames()
                .length; i++) {
                if (i > 0) {
                  sbForeignIdNamesUc.append(",");
                }
                sbForeignIdNamesUc.append(tableSqlForeign
                  .getIdColumnsNames()[i].toUpperCase());
              }
              String fkNames;
              if (tableSqlForeign.getIdColumnsNames().length > 1) {
                // composite FK:
                fkNames = sbForeignIdNamesUc.toString();
                // check if it is also primary key:
                boolean isAlsoPk = true;
                if (tableSql.getIdColumnsNames().length
                  == tableSqlForeign.getIdColumnsNames().length) {
                  for (int i = 0; i < tableSql.getIdColumnsNames()
                    .length; i++) {
                    if (!tableSqlForeign.getIdColumnsNames()[0]
                      .equals(tableSql.getIdColumnsNames()[0])) {
                      isAlsoPk = false;
                      break;
                    }
                  }
                }
                if (isAlsoPk) {
                  fieldSql.setTypeField(ETypeField.COMPOSITE_FK_PK);
                } else {
                  fieldSql.setTypeField(ETypeField.COMPOSITE_FK);
                }
                for (String cIdNm : tableSqlForeign.getIdColumnsNames()) {
                  FieldSql fldCid = new FieldSql();
                  fldCid.setTypeField(ETypeField.DERIVED_FROM_COMPOSITE);
                  if (!Boolean.valueOf(isNullableStr)
                      && !tableSqlForeign.getFieldsMap()
                        .get(cIdNm).getDefinition().contains("not null")) {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition() + " not null");
                  } else if (Boolean.valueOf(isNullableStr)
                      && fldCid.getDefinition().contains("not null")) {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition().replace(" not null", ""));
                  } else {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition());
                  }
                  fldCid.setForeignEntity(tableSqlForeign.getFieldsMap()
                    .get(cIdNm).getForeignEntity());
                  tableSql.getFieldsMap().put(cIdNm, fldCid);
                }
              } else {
                fkNames = field.getName().toUpperCase();
                if (fieldSql.getDefinition() == null) {
                  throw new ExceptionWithCode(ExceptionWithCode
                    .CONFIGURATION_MISTAKE,
                      "Where is no definition FID class/name: "
                        + clazz.getSimpleName() + "/" + field.getName());
                }
              }
              int hc = fldTypeSmpNm.hashCode();
              String hashCfesn;
              if (hc < 0) {
                hc = -hc;
                hashCfesn = "M" + hc;
              } else {
                hashCfesn = String.valueOf(hc);
              }

              String constraintFk = "constraint fk"
                + clazz.getSimpleName()
                + hashCfesn + field.getName()
                + " foreign key (" + fkNames
                + ") references " + fldTypeSmpNm.toUpperCase()
                + " (" + sbForeignIdNamesUc + ")";
              String constraint = tableSql.getConstraint();
              if (constraint != null) {
                constraint += ",\n" + constraintFk;
              } else {
                constraint = constraintFk;
              }
              tableSql.setConstraint(constraint);
            }
            //if field is PK, make sure NOT NULL:
            if (sbIdNamesUc.toString().contains(field.getName().toUpperCase())
                && !fieldSql.getDefinition().contains("not null")) {
              fieldSql.setDefinition(fieldSql.getDefinition()
                + " not null");
            }
          } catch (Exception e) {
            this.logger.error(null, ASrvOrm.class, "Error on load SQL tables:"
              + " class/field/fieldSql/tableSql - " + clazz.getSimpleName()
                + "/" + field.getName() + "/" + fieldSql + "/" + tableSql);
            throw e;
          }
        }
      }
      try {
        for (String colIdNm : tableSql.getIdColumnsNames()) {
          if (tableSql.getFieldsMap().get(colIdNm) == null) {
          throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
            "Where is no column ID class/name: " + clazz.getSimpleName()
              + "/" + colIdNm);
          }
        }
        //PK if complex (composite or foreign entity):
        if (tableSql.getIdColumnsNames().length > 1 || tableSql.getFieldsMap()
          .get(tableSql.getIdColumnsNames()[0]).getForeignEntity() != null) {
          String constraintPk = "constraint pk"
            + clazz.getSimpleName() + tableSql.getIdColumnsNames()[0]
              + " primary key (" + sbIdNamesUc + ")";
          if (tableSql.getConstraint() == null) {
            tableSql.setConstraint(constraintPk);
          } else {
            tableSql.setConstraint(constraintPk
              + ",\n" + tableSql.getConstraint());
          }
        }
        String constraintAdd = this.mngSettings.lazClsSts(clazz)
          .get("constraintAdd");
        if (constraintAdd != null) {
          if (tableSql.getConstraint() == null) {
            tableSql.setConstraint(constraintAdd);
          } else {
            tableSql.setConstraint(tableSql.getConstraint()
              + ",\n" + constraintAdd);
          }
        }
      } catch (Exception e) {
        this.logger.error(null, ASrvOrm.class, "Error on load SQL tables:"
          + " class/tableSql - " + clazz.getSimpleName() + "/" + tableSql);
        throw e;
      }
    }
  }
853500
@Override
    public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,
            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception
    {
        return super.fromThriftRow(clazz, m, relationNames, isWrapReq, consistencyLevel, rowIds);
    }
687194
public void open() throws DBException
    {
        super.open();
        Iterator<BaseTable> iterator = this.getTables();
        while (iterator.hasNext())
        {
            BaseTable table = iterator.next();
            if ((table != null) && (table != this.getNextTable()))
            {
                table.open();
            }
        }
    }