Search in sources :

Example 1 with RowView

use of org.jdbi.v3.core.result.RowView in project jdbi by jdbi.

the class RowViewMapperTest method testRowViewMap.

@Test
public void testRowViewMap() {
    Handle h = h2Extension.getSharedHandle();
    final Map<Integer, String> expected = new HashMap<>();
    expected.put(1, "SFO");
    expected.put(2, "OAK");
    expected.put(3, "YYZ");
    h.execute("create table airport (id int, code varchar)");
    PreparedBatch batch = h.prepareBatch("insert into airport (id, code) values (:id, :code)");
    expected.forEach((id, code) -> batch.bind("id", id).bind("code", code).add());
    batch.execute();
    assertThat(h.createQuery("select id, code from airport").map(rowView -> new AbstractMap.SimpleEntry<>(rowView.getColumn("id", Integer.class), rowView.getColumn("code", String.class))).collect(Collectors.toMap(Entry::getKey, Entry::getValue))).isEqualTo(expected);
}
Also used : H2DatabaseExtension(org.jdbi.v3.core.junit5.H2DatabaseExtension) Test(org.junit.jupiter.api.Test) AbstractMap(java.util.AbstractMap) PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Map(java.util.Map) Handle(org.jdbi.v3.core.Handle) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Entry(java.util.Map.Entry) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) HashMap(java.util.HashMap) PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) Handle(org.jdbi.v3.core.Handle) Test(org.junit.jupiter.api.Test)

Example 2 with RowView

use of org.jdbi.v3.core.result.RowView in project jdbi by jdbi.

the class ResultBearing method collectRows.

/**
 * Collect the results using the given collector. Do not attempt to accumulate the
 * {@link RowView} objects into the result--they are only valid within the
 * {@link Collector#accumulator()} function. Instead, extract mapped types from the
 * RowView by calling {@code RowView.getRow()} or {@code RowView.getColumn()}.
 *
 * @param collector the collector to collect the result rows.
 * @param <A> the mutable accumulator type used by the collector.
 * @param <R> the result type returned by the collector.
 * @return the result of the collection
 */
default <A, R> R collectRows(Collector<RowView, A, R> collector) {
    return scanResultSet((supplier, ctx) -> {
        try (ResultSet rs = supplier.get()) {
            RowView rv = new RowViewImpl(rs, ctx);
            A acc = collector.supplier().get();
            BiConsumer<A, RowView> consumer = collector.accumulator();
            while (rs.next()) {
                consumer.accept(acc, rv);
            }
            return collector.finisher().apply(acc);
        } catch (SQLException e) {
            throw new UnableToProduceResultException(e, ctx);
        } finally {
            ctx.close();
        }
    });
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) RowViewImpl(org.jdbi.v3.core.result.internal.RowViewImpl)

Example 3 with RowView

use of org.jdbi.v3.core.result.RowView in project consent by DataBiosphere.

the class DacWithDatasetsReducer method accumulate.

@Override
public void accumulate(Map<Integer, Dac> container, RowView rowView) {
    try {
        Dac dac = container.computeIfAbsent(rowView.getColumn("dac_id", Integer.class), id -> rowView.getRow(Dac.class));
        if (Objects.nonNull(rowView.getColumn("datasetid", Integer.class))) {
            DatasetDTO dto = rowView.getRow(DatasetDTO.class);
            try {
                if (Objects.nonNull(rowView.getColumn("dataset_alias", String.class))) {
                    String dsAlias = rowView.getColumn("dataset_alias", String.class);
                    try {
                        dto.setAlias(Integer.parseInt(dsAlias));
                    } catch (Exception e) {
                        logger.error("Exception parsing dataset alias: " + dsAlias, e);
                    }
                }
                if (Objects.nonNull(rowView.getColumn("dataset_create_date", Date.class))) {
                    Date createDate = rowView.getColumn("dataset_create_date", Date.class);
                    dto.setCreateDate(createDate);
                }
                if (Objects.nonNull(rowView.getColumn("dataset_update_date", Timestamp.class))) {
                    Timestamp updateDate = rowView.getColumn("dataset_update_date", Timestamp.class);
                    dto.setUpdateDate(updateDate);
                }
            } catch (Exception e) {
            // no values for these columns
            }
            if (Objects.nonNull(rowView.getColumn("consent_data_use", String.class))) {
                String duStr = rowView.getColumn("consent_data_use", String.class);
                Optional<DataUse> du = DataUse.parseDataUse(duStr);
                du.ifPresent(dto::setDataUse);
            }
            if (Objects.nonNull(dto)) {
                dac.addDatasetDTO(dto);
            }
        }
    } catch (MappingException e) {
        logger.warn(e.getMessage());
    }
}
Also used : DatasetDTO(org.broadinstitute.consent.http.models.dto.DatasetDTO) DataUse(org.broadinstitute.consent.http.models.DataUse) Dac(org.broadinstitute.consent.http.models.Dac) Timestamp(java.sql.Timestamp) MappingException(org.jdbi.v3.core.mapper.MappingException) Date(java.sql.Date) MappingException(org.jdbi.v3.core.mapper.MappingException)

Example 4 with RowView

use of org.jdbi.v3.core.result.RowView in project consent by DataBiosphere.

the class UserWithRolesReducer method accumulate.

@Override
public void accumulate(Map<Integer, User> map, RowView rowView) {
    User user = map.computeIfAbsent(rowView.getColumn("dacuserid", Integer.class), id -> rowView.getRow(User.class));
    try {
        if (Objects.nonNull(rowView.getColumn("user_role_id", Integer.class))) {
            UserRole ur = rowView.getRow(UserRole.class);
            user.addRole(ur);
        }
    } catch (MappingException e) {
    // Ignore any attempt to map a column that doesn't exist
    }
    try {
        if (Objects.nonNull(rowView.getColumn("i_id", Integer.class))) {
            Institution institution = rowView.getRow(Institution.class);
            // There are unusual cases where we somehow create an institution with null values
            if (Objects.nonNull(institution.getId())) {
                user.setInstitution(institution);
            }
        }
    } catch (MappingException e) {
    // Ignore institution mapping errors, possible for new users to not have an institution
    }
    // Below only adds LC if not currently saved on the array
    try {
        if (Objects.nonNull(rowView.getColumn("lc_id", Integer.class))) {
            LibraryCard lc = rowView.getRow(LibraryCard.class);
            try {
                if (Objects.nonNull(rowView.getColumn("lci_id", Integer.class))) {
                    Institution institution = rowView.getRow(Institution.class);
                    // There are unusual cases where we somehow create an institution with null values
                    if (Objects.nonNull(institution.getId())) {
                        lc.setInstitution(institution);
                    }
                }
            } catch (MappingException e) {
            // Ignore institution mapping errors
            }
            if (Objects.isNull(user.getLibraryCards()) || user.getLibraryCards().stream().noneMatch(card -> card.getId().equals(lc.getId()))) {
                user.addLibraryCard(lc);
            }
        }
    } catch (MappingException e) {
    // Ignore exceptions here, user may not have a library card issued under this instiution
    }
    try {
        if (Objects.nonNull(rowView.getColumn("up_property_id", Integer.class))) {
            UserProperty p = rowView.getRow(UserProperty.class);
            user.addProperty(p);
            // Note that the completed field is deprecated and will be removed in a future PR.
            if (p.getPropertyKey().equalsIgnoreCase(UserFields.COMPLETED.getValue())) {
                user.setProfileCompleted(Boolean.valueOf(p.getPropertyValue()));
            }
        }
    } catch (MappingException e) {
    // Ignore any attempt to map a column that doesn't exist
    }
}
Also used : LibraryCard(org.broadinstitute.consent.http.models.LibraryCard) Objects(java.util.Objects) Institution(org.broadinstitute.consent.http.models.Institution) UserProperty(org.broadinstitute.consent.http.models.UserProperty) LinkedHashMapRowReducer(org.jdbi.v3.core.result.LinkedHashMapRowReducer) Map(java.util.Map) RowView(org.jdbi.v3.core.result.RowView) UserRole(org.broadinstitute.consent.http.models.UserRole) MappingException(org.jdbi.v3.core.mapper.MappingException) UserFields(org.broadinstitute.consent.http.enumeration.UserFields) User(org.broadinstitute.consent.http.models.User) LibraryCard(org.broadinstitute.consent.http.models.LibraryCard) User(org.broadinstitute.consent.http.models.User) UserProperty(org.broadinstitute.consent.http.models.UserProperty) UserRole(org.broadinstitute.consent.http.models.UserRole) Institution(org.broadinstitute.consent.http.models.Institution) MappingException(org.jdbi.v3.core.mapper.MappingException)

Example 5 with RowView

use of org.jdbi.v3.core.result.RowView in project cudami by dbmdz.

the class IdentifiableRepositoryImpl method retrieveOne.

public I retrieveOne(String fieldsSql, String sqlSelectAllFieldsJoins, Filtering filtering, Map<String, Object> argumentMappings, String innerSelect) {
    StringBuilder sql = new StringBuilder("SELECT" + fieldsSql + "," + IdentifierRepositoryImpl.SQL_FULL_FIELDS_ID + "," + ImageFileResourceRepositoryImpl.SQL_PREVIEW_IMAGE_FIELDS_PI + ", " + UrlAliasRepositoryImpl.getSelectFields(true) + " FROM " + (StringUtils.hasText(innerSelect) ? innerSelect : tableName) + " AS " + tableAlias + (sqlSelectAllFieldsJoins != null ? sqlSelectAllFieldsJoins : "") + " LEFT JOIN " + IdentifierRepositoryImpl.TABLE_NAME + " AS " + IdentifierRepositoryImpl.TABLE_ALIAS + " ON " + tableAlias + ".uuid = " + IdentifierRepositoryImpl.TABLE_ALIAS + ".identifiable" + " LEFT JOIN " + ImageFileResourceRepositoryImpl.TABLE_NAME + " AS file ON " + tableAlias + ".previewfileresource = file.uuid" + " LEFT JOIN " + UrlAliasRepositoryImpl.TABLE_NAME + " AS " + UrlAliasRepositoryImpl.TABLE_ALIAS + " ON " + tableAlias + ".uuid = " + UrlAliasRepositoryImpl.TABLE_ALIAS + ".target_uuid" + UrlAliasRepositoryImpl.WEBSITESJOIN);
    if (argumentMappings == null) {
        argumentMappings = new HashMap<>(0);
    }
    addFiltering(filtering, sql, argumentMappings);
    Map<String, Object> bindMap = Map.copyOf(argumentMappings);
    I result = dbi.withHandle(h -> h.createQuery(sql.toString()).bindMap(bindMap).reduceRows((Map<UUID, I> map, RowView rowView) -> {
        fullReduceRowsBiFunction.apply(map, rowView);
        additionalReduceRowsBiFunction.apply(map, rowView);
    })).findFirst().orElse(null);
    return result;
}
Also used : RowView(org.jdbi.v3.core.result.RowView) URI(java.net.URI) SQL_PREVIEW_IMAGE_FIELDS_PI(de.digitalcollections.cudami.server.backend.impl.jdbi.identifiable.resource.FileResourceMetadataRepositoryImpl.SQL_PREVIEW_IMAGE_FIELDS_PI) UUID(java.util.UUID)

Aggregations

MappingException (org.jdbi.v3.core.mapper.MappingException)5 Institution (org.broadinstitute.consent.http.models.Institution)4 ResultSet (java.sql.ResultSet)3 SQLException (java.sql.SQLException)3 Map (java.util.Map)3 LibraryCard (org.broadinstitute.consent.http.models.LibraryCard)3 User (org.broadinstitute.consent.http.models.User)3 RowViewImpl (org.jdbi.v3.core.result.internal.RowViewImpl)3 Test (org.junit.jupiter.api.Test)3 HashMap (java.util.HashMap)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 UserProperty (org.broadinstitute.consent.http.models.UserProperty)2 Handle (org.jdbi.v3.core.Handle)2 Something (org.jdbi.v3.core.Something)2 H2DatabaseExtension (org.jdbi.v3.core.junit5.H2DatabaseExtension)2 RowView (org.jdbi.v3.core.result.RowView)2 RegisterExtension (org.junit.jupiter.api.extension.RegisterExtension)2 SQL_PREVIEW_IMAGE_FIELDS_PI (de.digitalcollections.cudami.server.backend.impl.jdbi.identifiable.resource.FileResourceMetadataRepositoryImpl.SQL_PREVIEW_IMAGE_FIELDS_PI)1 URI (java.net.URI)1 Date (java.sql.Date)1