Search in sources :

Example 1 with UniquenessCheckAttributes

use of bio.terra.workspace.db.model.UniquenessCheckAttributes in project terra-workspace-manager by DataBiosphere.

the class ResourceDao method verifyUniqueness.

// Verify that the resource to be created doesn't already exist according to per-resource type
// uniqueness rules. This prevents a race condition allowing a new resource to point to the same
// cloud artifact as another, even if it has a different resource name and ID.
private void verifyUniqueness(ControlledResource controlledResource) {
    Optional<UniquenessCheckAttributes> optionalUniquenessCheck = controlledResource.getUniquenessCheckAttributes();
    if (optionalUniquenessCheck.isPresent()) {
        UniquenessCheckAttributes uniquenessCheck = optionalUniquenessCheck.get();
        StringBuilder queryBuilder = new StringBuilder().append("SELECT COUNT(1) FROM resource WHERE exact_resource_type = :exact_resource_type");
        MapSqlParameterSource params = new MapSqlParameterSource().addValue("exact_resource_type", controlledResource.getResourceType().toSql());
        if (uniquenessCheck.getUniquenessScope() == UniquenessScope.WORKSPACE) {
            queryBuilder.append(" AND workspace_id = :workspace_id");
            params.addValue("workspace_id", controlledResource.getWorkspaceId().toString());
        }
        for (Pair<String, String> pair : uniquenessCheck.getParameters()) {
            String name = pair.getKey();
            queryBuilder.append(String.format(" AND attributes->>'%s' = :%s", name, name));
            params.addValue(name, pair.getValue());
        }
        Integer matchingCount = jdbcTemplate.queryForObject(queryBuilder.toString(), params, Integer.class);
        if (matchingCount != null && matchingCount > 0) {
            throw new DuplicateResourceException("A resource with matching attributes already exists");
        }
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) UniquenessCheckAttributes(bio.terra.workspace.db.model.UniquenessCheckAttributes) DuplicateResourceException(bio.terra.workspace.service.resource.exception.DuplicateResourceException)

Aggregations

UniquenessCheckAttributes (bio.terra.workspace.db.model.UniquenessCheckAttributes)1 DuplicateResourceException (bio.terra.workspace.service.resource.exception.DuplicateResourceException)1 MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)1