Search in sources :

Example 1 with InvalidQueryException

use of bio.terra.grammar.exception.InvalidQueryException in project jade-data-repo by DataBiosphere.

the class Query method parse.

public static Query parse(String sql) {
    CharStream charStream = CharStreams.fromString(sql);
    SQLLexer lexer = new SQLLexer(charStream);
    SQLParser parser = new SQLParser(new CommonTokenStream(lexer));
    parser.setErrorHandler(new BailErrorStrategy());
    try {
        return new Query(parser, parser.query_statement());
    } catch (ParseCancellationException ex) {
        throw new InvalidQueryException("Could not parse query: " + sql, ex);
    }
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) BailErrorStrategy(org.antlr.v4.runtime.BailErrorStrategy) CharStream(org.antlr.v4.runtime.CharStream) InvalidQueryException(bio.terra.grammar.exception.InvalidQueryException)

Example 2 with InvalidQueryException

use of bio.terra.grammar.exception.InvalidQueryException in project jade-data-repo by DataBiosphere.

the class BigQueryPdao method queryForRowIds.

// insert the rowIds into the snapshot row ids table and then kick off the rest of the relationship walking
// once we have the row ids in addition to the asset spec, this should look familiar to wAsset
public void queryForRowIds(AssetSpecification assetSpecification, Snapshot snapshot, String sqlQuery) throws InterruptedException {
    BigQueryProject bigQueryProject = bigQueryProjectForSnapshot(snapshot);
    BigQuery bigQuery = bigQueryProject.getBigQuery();
    String snapshotName = snapshot.getName();
    Dataset dataset = snapshot.getSnapshotSources().get(0).getDataset();
    String datasetBqDatasetName = prefixName(dataset.getName());
    String projectId = bigQueryProject.getProjectId();
    // create snapshot bq dataset
    try {
        // create snapshot BQ dataset
        snapshotCreateBQDataset(bigQueryProject, snapshot);
        // now create a temp table with all the selected row ids based on the query in it
        bigQueryProject.createTable(snapshotName, PDAO_TEMP_TABLE, tempTableSchema());
        QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(sqlQuery).setDestinationTable(TableId.of(snapshotName, PDAO_TEMP_TABLE)).setWriteDisposition(JobInfo.WriteDisposition.WRITE_APPEND).build();
        try {
            final TableResult query = bigQuery.query(queryConfig);
            // get results and validate that it got back more than 0 value
            if (query.getTotalRows() < 1) {
                // should this be a different error?
                throw new InvalidQueryException("Query returned 0 results");
            }
        } catch (InterruptedException ie) {
            throw new PdaoException("Append query unexpectedly interrupted", ie);
        }
        // join on the root table to validate that the dataset's rootTable.rowid is never null
        // and thus matches the PDAO_ROW_ID_COLUMN
        AssetTable rootAssetTable = assetSpecification.getRootTable();
        Table rootTable = rootAssetTable.getTable();
        String datasetTableName = rootTable.getName();
        String rootTableId = rootTable.getId().toString();
        ST sqlTemplate = new ST(joinTablesToTestForMissingRowIds);
        sqlTemplate.add("snapshotDatasetName", snapshotName);
        sqlTemplate.add("tempTable", PDAO_TEMP_TABLE);
        sqlTemplate.add("datasetDatasetName", datasetBqDatasetName);
        sqlTemplate.add("datasetTable", datasetTableName);
        sqlTemplate.add("commonColumn", PDAO_ROW_ID_COLUMN);
        TableResult result = bigQueryProject.query(sqlTemplate.render());
        FieldValueList mismatchedCount = result.getValues().iterator().next();
        Long mismatchedCountLong = mismatchedCount.get(0).getLongValue();
        if (mismatchedCountLong > 0) {
            throw new MismatchedValueException("Query results did not match dataset root row ids");
        }
        // TODO should this be pulled up to the top of queryForRowIds() / added to snapshotCreateBQDataset() helper
        bigQueryProject.createTable(snapshotName, PDAO_ROW_ID_TABLE, rowIdTableSchema());
        // populate root row ids. Must happen before the relationship walk.
        // NOTE: when we have multiple sources, we can put this into a loop
        // insert into the PDAO_ROW_ID_TABLE the literal that is the table id
        // and then all the row ids from the temp table
        ST sqlLoadTemplate = new ST(loadRootRowIdsFromTempTableTemplate);
        sqlLoadTemplate.add("project", projectId);
        sqlLoadTemplate.add("snapshot", snapshotName);
        sqlLoadTemplate.add("dataset", datasetBqDatasetName);
        sqlLoadTemplate.add("tableId", rootTableId);
        // this is the disc from classic asset
        sqlLoadTemplate.add("commonColumn", PDAO_ROW_ID_COLUMN);
        sqlLoadTemplate.add("tempTable", PDAO_TEMP_TABLE);
        bigQueryProject.query(sqlLoadTemplate.render());
        // ST sqlValidateTemplate = new ST(validateRowIdsForRootTemplate);
        // TODO do we want to reuse this validation? if yes, maybe mismatchedCount / query should be updated
        // walk and populate relationship table row ids
        List<WalkRelationship> walkRelationships = WalkRelationship.ofAssetSpecification(assetSpecification);
        walkRelationships(datasetBqDatasetName, snapshotName, walkRelationships, rootTableId, projectId, bigQuery);
        // populate root row ids. Must happen before the relationship walk.
        // NOTE: when we have multiple sources, we can put this into a loop
        snapshotViewCreation(datasetBqDatasetName, snapshotName, snapshot, projectId, bigQuery, bigQueryProject);
    } catch (PdaoException ex) {
        // TODO what if the query is invalid? Seems like there might be more to catch here.
        throw new PdaoException("createSnapshot failed", ex);
    }
}
Also used : AssetTable(bio.terra.service.dataset.AssetTable) ST(org.stringtemplate.v4.ST) BigQuery(com.google.cloud.bigquery.BigQuery) DatasetTable(bio.terra.service.dataset.DatasetTable) Table(bio.terra.common.Table) AssetTable(bio.terra.service.dataset.AssetTable) SnapshotTable(bio.terra.service.snapshot.SnapshotTable) SnapshotMapTable(bio.terra.service.snapshot.SnapshotMapTable) Dataset(bio.terra.service.dataset.Dataset) TableResult(com.google.cloud.bigquery.TableResult) PdaoException(bio.terra.common.exception.PdaoException) MismatchedValueException(bio.terra.service.snapshot.exception.MismatchedValueException) FieldValueList(com.google.cloud.bigquery.FieldValueList) QueryJobConfiguration(com.google.cloud.bigquery.QueryJobConfiguration) InvalidQueryException(bio.terra.grammar.exception.InvalidQueryException)

Example 3 with InvalidQueryException

use of bio.terra.grammar.exception.InvalidQueryException in project jade-data-repo by DataBiosphere.

the class CreateSnapshotPrimaryDataQueryStep method doStep.

@Override
public StepResult doStep(FlightContext context) throws InterruptedException {
    // TODO: this assumes single-dataset snapshots, will need to add a loop for multiple
    // (based on the validation flight step that already occurred.)
    /*
         * get dataset and assetName
         * get asset from dataset
         * which gives the root table
         * to use in conjunction with the filtered row ids to create this snapshot
         */
    Snapshot snapshot = snapshotDao.retrieveSnapshotByName(snapshotReq.getName());
    SnapshotRequestQueryModel snapshotQuerySpec = snapshotReq.getContents().get(0).getQuerySpec();
    String snapshotAssetName = snapshotQuerySpec.getAssetName();
    String snapshotQuery = snapshotReq.getContents().get(0).getQuerySpec().getQuery();
    Query query = Query.parse(snapshotQuery);
    List<String> datasetNames = query.getDatasetNames();
    // TODO this makes the assumption that there is only one dataset
    // (based on the validation flight step that already occurred.)
    // This will change when more than 1 dataset is allowed
    String datasetName = datasetNames.get(0);
    Dataset dataset = datasetService.retrieveByName(datasetName);
    DatasetModel datasetModel = datasetService.retrieveModel(dataset);
    // get asset out of dataset
    Optional<AssetSpecification> assetSpecOp = dataset.getAssetSpecificationByName(snapshotAssetName);
    AssetSpecification assetSpec = assetSpecOp.orElseThrow(() -> new AssetNotFoundException("Expected asset specification"));
    Map<String, DatasetModel> datasetMap = Collections.singletonMap(datasetName, datasetModel);
    BigQueryVisitor bqVisitor = new BigQueryVisitor(datasetMap);
    String sqlQuery = query.translateSql(bqVisitor);
    // validate that the root table is actually a table being queried in the query -->
    // and the grammar only picks up tables names in the from clause (though there may be more than one)
    List<String> tableNames = query.getTableNames();
    String rootTablename = assetSpec.getRootTable().getTable().getName();
    if (!tableNames.contains(rootTablename)) {
        throw new InvalidQueryException("The root table of the selected asset is not present in this query");
    }
    // now using the query, get the rowIds
    // insert the rowIds into the snapshot row ids table and then kick off the rest of the relationship walking
    bigQueryPdao.queryForRowIds(assetSpec, snapshot, sqlQuery);
    return StepResult.getStepResultSuccess();
}
Also used : BigQueryVisitor(bio.terra.grammar.google.BigQueryVisitor) Query(bio.terra.grammar.Query) SnapshotRequestQueryModel(bio.terra.model.SnapshotRequestQueryModel) Dataset(bio.terra.service.dataset.Dataset) AssetSpecification(bio.terra.service.dataset.AssetSpecification) AssetNotFoundException(bio.terra.service.snapshot.exception.AssetNotFoundException) Snapshot(bio.terra.service.snapshot.Snapshot) DatasetModel(bio.terra.model.DatasetModel) InvalidQueryException(bio.terra.grammar.exception.InvalidQueryException)

Aggregations

InvalidQueryException (bio.terra.grammar.exception.InvalidQueryException)3 Dataset (bio.terra.service.dataset.Dataset)2 Table (bio.terra.common.Table)1 PdaoException (bio.terra.common.exception.PdaoException)1 Query (bio.terra.grammar.Query)1 BigQueryVisitor (bio.terra.grammar.google.BigQueryVisitor)1 DatasetModel (bio.terra.model.DatasetModel)1 SnapshotRequestQueryModel (bio.terra.model.SnapshotRequestQueryModel)1 AssetSpecification (bio.terra.service.dataset.AssetSpecification)1 AssetTable (bio.terra.service.dataset.AssetTable)1 DatasetTable (bio.terra.service.dataset.DatasetTable)1 Snapshot (bio.terra.service.snapshot.Snapshot)1 SnapshotMapTable (bio.terra.service.snapshot.SnapshotMapTable)1 SnapshotTable (bio.terra.service.snapshot.SnapshotTable)1 AssetNotFoundException (bio.terra.service.snapshot.exception.AssetNotFoundException)1 MismatchedValueException (bio.terra.service.snapshot.exception.MismatchedValueException)1 BigQuery (com.google.cloud.bigquery.BigQuery)1 FieldValueList (com.google.cloud.bigquery.FieldValueList)1 QueryJobConfiguration (com.google.cloud.bigquery.QueryJobConfiguration)1 TableResult (com.google.cloud.bigquery.TableResult)1