public SqlUpdateHandler(Class<?> sqlObjectType, Method method) { super(sqlObjectType, method); if (method.isAnnotationPresent(UseRowReducer.class)) { throw new UnsupportedOperationException("Cannot declare @UseRowReducer on a @SqlUpdate method."); } boolean isGetGeneratedKeys = method.isAnnotationPresent(GetGeneratedKeys.class); QualifiedType<?> returnType = QualifiedType.of( GenericTypes.resolveType(method.getGenericReturnType(), sqlObjectType)) .with(getQualifiers(method)); if (isGetGeneratedKeys) { ResultReturner magic = ResultReturner.forMethod(sqlObjectType, method); String[] columnNames = method.getAnnotation(GetGeneratedKeys.class).value(); this.returner = update -> { ResultBearing resultBearing = update.executeAndReturnGeneratedKeys(columnNames); UseRowMapper useRowMapper = method.getAnnotation(UseRowMapper.class); ResultIterable<?> iterable = useRowMapper == null ? resultBearing.mapTo(returnType) : resultBearing.map(rowMapperFor(useRowMapper)); return magic.mappedResult(iterable, update.getContext()); }; } else if (isNumeric(method.getReturnType())) { this.returner = update -> update.execute(); } else if (isBoolean(method.getReturnType())) { this.returner = update -> update.execute() > 0; } else { throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method, returnType)); } }
@Test public void testDelete() { Handle h = dbRule.openHandle(); Update insert = h.createUpdate("insert into something_else (name) values (:name)"); insert.bind("name", "Brian"); Long id1 = insert.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly(); assertThat(id1).isNotNull(); Update delete = h.createUpdate("delete from something_else where id = :id"); delete.bind("id", id1); Optional<Long> id2 = delete.executeAndReturnGeneratedKeys().mapTo(long.class).findFirst(); assertThat(id2.isPresent()).isFalse(); } }
@Test public void testUpdate() { Handle h = dbRule.openHandle(); Update insert = h.createUpdate("insert into something_else (name) values (:name)"); insert.bind("name", "Brian"); Long id1 = insert.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly(); assertThat(id1).isNotNull(); Update update = h.createUpdate("update something_else set name = :name where id = :id"); update.bind("id", id1); update.bind("name", "Tom"); Optional<Long> id2 = update.executeAndReturnGeneratedKeys().mapTo(long.class).findFirst(); assertThat(id2.isPresent()).isFalse(); }
@Test public void testInsert() { Handle h = dbRule.openHandle(); Update insert1 = h.createUpdate("insert into something_else (name) values (:name)"); insert1.bind("name", "Brian"); Long id1 = insert1.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly(); assertThat(id1).isNotNull(); Update insert2 = h.createUpdate("insert into something_else (name) values (:name)"); insert2.bind("name", "Tom"); Long id2 = insert2.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly(); assertThat(id2).isNotNull(); assertThat(id2).isGreaterThan(id1); }
@Test // tag::fluent[] public void fluentInsertKeys() { db.useHandle(handle -> { User data = handle.createUpdate("INSERT INTO users (name) VALUES(?)") .bind(0, "Data") .executeAndReturnGeneratedKeys() .mapTo(User.class) .findOnly(); assertEquals(1, data.id); // This value is generated by the database assertEquals("Data", data.name); }); } // end::fluent[]
/** * @see io.apicurio.hub.core.storage.IStorage#addContent(java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ApiContentType, java.lang.String) */ @Override public long addContent(String userId, String designId, ApiContentType type, String data) throws StorageException { logger.debug("Inserting a 'command' content row for: {}", designId); try { return this.jdbi.withHandle( handle -> { // Insert a row in the api_content table. Retrieve the ID. String statement = sqlStatements.insertContent(); CharacterStreamArgument contentClob = new CharacterStreamArgument(new StringReader(data), data.length()); Long contentVersion = handle.createUpdate(statement) .bind(0, Long.parseLong(designId)) .bind(1, type.getId()) .bind(2, contentClob) .bind(3, userId) .bind(4, new Date()) .executeAndReturnGeneratedKeys("version") .mapTo(Long.class) .findOnly(); return contentVersion; }); } catch (Exception e) { throw new StorageException("Error adding content entry for API design.", e); } }
/** * @see io.apicurio.hub.core.storage.IStorage#addContent(java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ApiContentType, java.lang.String) */ @Override public long addContent(String userId, String designId, ApiContentType type, String data) throws StorageException { logger.debug("Inserting a 'command' content row for: {}", designId); try { return this.jdbi.withHandle( handle -> { // Insert a row in the api_content table. Retrieve the ID. String statement = sqlStatements.insertContent(); CharacterStreamArgument contentClob = new CharacterStreamArgument(new StringReader(data), data.length()); Long contentVersion = handle.createUpdate(statement) .bind(0, Long.parseLong(designId)) .bind(1, type.getId()) .bind(2, contentClob) .bind(3, userId) .bind(4, new Date()) .executeAndReturnGeneratedKeys("version") .mapTo(Long.class) .findOnly(); return contentVersion; }); } catch (Exception e) { throw new StorageException("Error adding content entry for API design.", e); } }
private static int updateResource(final Handle handle, final Metadata metadata, final Dataset dataset, final Instant time, final boolean isDelete) { handle.execute("DELETE FROM resource WHERE subject = ?", metadata.getIdentifier().getIRIString()); final String query = "INSERT INTO resource (subject, interaction_model, modified, deleted, is_part_of, acl, " + "ldp_member, ldp_membership_resource, ldp_has_member_relation, ldp_is_member_of_relation, " + "ldp_inserted_content_relation, binary_location, binary_format) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // Set ldp:insertedContentRelation only for LDP-IC and LDP-DC resources final String icr = asList(LDP.DirectContainer, LDP.IndirectContainer).contains(metadata.getInteractionModel()) ? metadata.getInsertedContentRelation().orElse(LDP.MemberSubject).getIRIString() : null; try (final Update update = handle.createUpdate(query) .bind(0, metadata.getIdentifier().getIRIString()) .bind(1, metadata.getInteractionModel().getIRIString()) .bind(2, time.toEpochMilli()) .bind(3, isDelete) .bind(4, metadata.getContainer().map(IRI::getIRIString).orElse(null)) .bind(5, dataset.contains(of(PreferAccessControl), null, null, null)) .bind(6, metadata.getMembershipResource().map(IRI::getIRIString) .map(str -> str.split("#")[0]).orElse(null)) .bind(7, metadata.getMembershipResource().map(IRI::getIRIString).orElse(null)) .bind(8, metadata.getMemberRelation().map(IRI::getIRIString).orElse(null)) .bind(9, metadata.getMemberOfRelation().map(IRI::getIRIString).orElse(null)) .bind(10, icr) .bind(11, metadata.getBinary().map(BinaryMetadata::getIdentifier).map(IRI::getIRIString).orElse(null)) .bind(12, metadata.getBinary().flatMap(BinaryMetadata::getMimeType).orElse(null))) { return update.executeAndReturnGeneratedKeys("id").mapTo(Integer.class).findOnly(); } }
/** * @see io.apicurio.hub.core.storage.IStorage#createCodegenProject(java.lang.String, io.apicurio.hub.core.beans.CodegenProject) */ @Override public String createCodegenProject(String userId, CodegenProject project) throws StorageException { logger.debug("Inserting a codegen project: {}", project.getType()); try { return this.jdbi.withHandle( handle -> { String statement = sqlStatements.insertCodegenProject(); String attrs = CodegenProjectRowMapper.toString(project.getAttributes()); CharacterStreamArgument attributesClob = new CharacterStreamArgument(new StringReader(attrs), attrs.length()); String projectId = handle.createUpdate(statement) .bind(0, project.getCreatedBy()) .bind(1, project.getCreatedOn()) .bind(2, project.getCreatedBy()) .bind(3, project.getCreatedOn()) .bind(4, Long.valueOf(project.getDesignId())) .bind(5, project.getType().toString()) .bind(6, attributesClob) .executeAndReturnGeneratedKeys("id") .mapTo(String.class) .findOnly(); return projectId; }); } catch (Exception e) { throw new StorageException("Error inserting codegen project.", e); } }
/** * @see io.apicurio.hub.core.storage.IStorage#createCodegenProject(java.lang.String, io.apicurio.hub.core.beans.CodegenProject) */ @Override public String createCodegenProject(String userId, CodegenProject project) throws StorageException { logger.debug("Inserting a codegen project: {}", project.getType()); try { return this.jdbi.withHandle( handle -> { String statement = sqlStatements.insertCodegenProject(); String attrs = CodegenProjectRowMapper.toString(project.getAttributes()); CharacterStreamArgument attributesClob = new CharacterStreamArgument(new StringReader(attrs), attrs.length()); String projectId = handle.createUpdate(statement) .bind(0, project.getCreatedBy()) .bind(1, project.getCreatedOn()) .bind(2, project.getCreatedBy()) .bind(3, project.getCreatedOn()) .bind(4, Long.valueOf(project.getDesignId())) .bind(5, project.getType().toString()) .bind(6, attributesClob) .executeAndReturnGeneratedKeys("id") .mapTo(String.class) .findOnly(); return projectId; }); } catch (Exception e) { throw new StorageException("Error inserting codegen project.", e); } }
.bind(3, design.getCreatedOn()) .bind(4, asCsv(design.getTags())) .executeAndReturnGeneratedKeys("id") .mapTo(String.class) .findOnly();
.bind(4, asCsv(design.getTags())) .bind(5, design.getType().name()) .executeAndReturnGeneratedKeys("id") .mapTo(String.class) .findOnly();