org.jooq.Record Java Examples

The following examples show how to use org.jooq.Record. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResultBuilder.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private <R extends Record> Cursor<R> timeQuery(ResultQuery<R> query) {
    if (persistenceSettings.isTimeoutQueries()) {
        query.queryTimeout(persistenceSettings.getQueryTimeout());
    }
    if (!persistenceSettings.isLogSlowQueries()) {
        return query.fetchLazy();
    }
    long start = System.currentTimeMillis();
    Cursor<R> result;
    try {
        result = query.fetchLazy();
    } catch (DataAccessException exc) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.info("Failed to run query:\n{}", query.getSQL(ParamType.INLINED));
        }
        throw new IllegalStateException("Failed to run query: " + exc.getMessage());
    }
    long end = System.currentTimeMillis();
    long duration = end - start;
    if (LOGGER.isInfoEnabled() && duration > persistenceSettings.getSlowQueryThreshold()) {
        LOGGER.info("Slow Query executed in {} ms:\n{}", duration, query.getSQL(ParamType.INLINED));
    }
    return result;
}
 
Example #2
Source File: HmfGenePanelBuilder.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws ParseException, IOException, SQLException {
    final Options options = createOptions();
    final CommandLine cmd = createCommandLine(args, options);

    final String outputFilePath = cmd.getOptionValue(OUT_PATH);
    final String ensemblVersion = cmd.getOptionValue(ENSEMBL_VERSION);

    if (outputFilePath == null || !VERSIONS.contains(ensemblVersion)) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("HmfGenePanelBuilder", options);
        System.exit(1);
    }

    final String database = ensemblVersion.equals("37") ? ENSEMBLDB_URL_37 : ENSEMBLDB_URL_38;

    LOGGER.info("Querying " + database);
    final Result<Record> queryResults = queryEnsembldb(database);
    writeFile(cmd, queryResults);
    LOGGER.info("Written output to " + new File(outputFilePath).getAbsolutePath());
}
 
Example #3
Source File: JooqUnmapperTest.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCacheMapper() {

	SfmRecordUnmapperProvider recordMapperProvider = JooqMapperFactory.newInstance()
			.newRecordUnmapperProvider((Configuration) null);
	RecordType rt = mock(RecordType.class);
	Field field1 = mock(Field.class);
	when(field1.getName()).thenReturn("id");
	when(field1.getType()).thenReturn(long.class);
	when(rt.size()).thenReturn(1);
	when(rt.fields()).thenReturn(new Field[] {field1});

	JooqRecordUnmapperWrapper provider1 =
			(JooqRecordUnmapperWrapper) recordMapperProvider.<DbObject, Record>provide(DbObject.class, rt);
	JooqRecordUnmapperWrapper provider2 =
			(JooqRecordUnmapperWrapper) recordMapperProvider.<DbObject, Record>provide(DbObject.class, rt);
	assertSame(provider1.getMapper(), provider2.getMapper());
}
 
Example #4
Source File: SensorFactory.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Sensor create(Record record, Query query, DataSize dataSize) {
    Set<Property> select = query == null ? Collections.emptySet() : query.getSelect();
    Sensor entity = new Sensor();
    entity.setName(getFieldOrNull(record, table.colName));
    entity.setDescription(getFieldOrNull(record, table.colDescription));
    entity.setEncodingType(getFieldOrNull(record, table.colEncodingType));
    J id = getFieldOrNull(record, table.getId());
    if (id != null) {
        entity.setId(entityFactories.idFromObject(id));
    }
    if (select.isEmpty() || select.contains(EntityProperty.METADATA)) {
        String metaDataString = getFieldOrNull(record, table.colMetadata);
        dataSize.increase(metaDataString == null ? 0 : metaDataString.length());
        entity.setMetadata(metaDataString);
    }
    if (select.isEmpty() || select.contains(EntityProperty.PROPERTIES)) {
        String props = getFieldOrNull(record, table.colProperties);
        entity.setProperties(Utils.jsonToObject(props, Map.class));
    }
    return entity;
}
 
Example #5
Source File: MetricsDSLContextTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void userExecuteListenerShouldBePreserved() {
    ExecuteListener userExecuteListener = mock(ExecuteListener.class);
    Configuration configuration = new DefaultConfiguration().set(() -> userExecuteListener);

    MetricsDSLContext jooq = withMetrics(using(configuration), meterRegistry, Tags.empty());

    ExecuteListenerProvider[] executeListenerProviders = jooq.configuration().executeListenerProviders();
    assertThat(executeListenerProviders).hasSize(2);
    assertThat(executeListenerProviders[0].provide()).isSameAs(userExecuteListener);
    assertThat(executeListenerProviders[1].provide()).isInstanceOf(JooqExecuteListener.class);

    SelectSelectStep<Record> select = jooq.tag("name", "selectAllAuthors").select(asterisk());
    executeListenerProviders = select.configuration().executeListenerProviders();
    assertThat(executeListenerProviders).hasSize(2);
    assertThat(executeListenerProviders[0].provide()).isSameAs(userExecuteListener);
    assertThat(executeListenerProviders[1].provide()).isInstanceOf(JooqExecuteListener.class);
}
 
Example #6
Source File: ActuatorFactory.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Actuator create(Record record, Query query, DataSize dataSize) {
    Set<Property> select = query == null ? Collections.emptySet() : query.getSelect();
    Actuator entity = new Actuator();
    J id = getFieldOrNull(record, table.getId());
    if (id != null) {
        entity.setId(entityFactories.idFromObject(id));
    }
    entity.setName(getFieldOrNull(record, table.colName));
    entity.setDescription(getFieldOrNull(record, table.colDescription));
    entity.setEncodingType(getFieldOrNull(record, table.colEncodingType));
    if (select.isEmpty() || select.contains(EntityProperty.PROPERTIES)) {
        String props = getFieldOrNull(record, table.colProperties);
        entity.setProperties(Utils.jsonToObject(props, Map.class));
    }
    if (select.isEmpty() || select.contains(EntityProperty.METADATA)) {
        String metaDataString = getFieldOrNull(record, table.colMetadata);
        dataSize.increase(metaDataString == null ? 0 : metaDataString.length());
        entity.setMetadata(metaDataString);
    }
    return entity;
}
 
Example #7
Source File: FeatureOfInterestFactory.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public FeatureOfInterest create(Record record, Query query, DataSize dataSize) {
    Set<Property> select = query == null ? Collections.emptySet() : query.getSelect();
    FeatureOfInterest entity = new FeatureOfInterest();
    J id = getFieldOrNull(record, table.getId());
    if (id != null) {
        entity.setId(entityFactories.idFromObject(id));
    }
    entity.setName(getFieldOrNull(record, table.colName));
    entity.setDescription(getFieldOrNull(record, table.colDescription));
    String encodingType = getFieldOrNull(record, table.colEncodingType);
    entity.setEncodingType(encodingType);
    if (select.isEmpty() || select.contains(EntityProperty.FEATURE)) {
        String locationString = getFieldOrNull(record, table.colFeature);
        dataSize.increase(locationString == null ? 0 : locationString.length());
        entity.setFeature(Utils.locationFromEncoding(encodingType, locationString));
    }
    if (select.isEmpty() || select.contains(EntityProperty.PROPERTIES)) {
        String props = getFieldOrNull(record, table.colProperties);
        entity.setProperties(Utils.jsonToObject(props, Map.class));
    }
    return entity;
}
 
Example #8
Source File: TaskFactory.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Task create(Record record, Query query, DataSize dataSize) {
    Set<Property> select = query == null ? Collections.emptySet() : query.getSelect();
    Task entity = new Task();
    J id = getFieldOrNull(record, table.getId());
    if (id != null) {
        entity.setId(entityFactories.idFromObject(id));
    }
    entity.setTaskingCapability(entityFactories.taskingCapabilityFromId(record, table.getTaskingCapabilityId()));
    entity.setCreationTime(Utils.instantFromTime(getFieldOrNull(record, table.colCreationTime)));
    if (select.isEmpty() || select.contains(EntityProperty.TASKINGPARAMETERS)) {
        String taskingParams = getFieldOrNull(record, table.colTaskingParameters);
        entity.setTaskingParameters(Utils.jsonToObject(taskingParams, Map.class));
    }

    return entity;
}
 
Example #9
Source File: MeasurableExporterHarness.java    From waltz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);


    long categoryId = 1L;

    SelectConditionStep<Record> qry = dsl
            .select(MEASURABLE.NAME, MEASURABLE.DESCRIPTION, MEASURABLE.ID, MEASURABLE.PARENT_ID, MEASURABLE.EXTERNAL_ID)
            .select(INVOLVEMENT_KIND.NAME)
            .select(PERSON.DISPLAY_NAME)
            .from(MEASURABLE)
            .leftJoin(INVOLVEMENT)
            .on(INVOLVEMENT.ENTITY_ID.eq(MEASURABLE.ID).and(INVOLVEMENT.ENTITY_KIND.eq(EntityKind.MEASURABLE.name())))
            .leftJoin(INVOLVEMENT_KIND)
            .on(INVOLVEMENT_KIND.ID.eq(INVOLVEMENT.KIND_ID))
            .leftJoin(PERSON)
            .on(PERSON.EMPLOYEE_ID.eq(INVOLVEMENT.EMPLOYEE_ID))
            .where(MEASURABLE.MEASURABLE_CATEGORY_ID.eq(categoryId));

    qry.fetch().forEach(System.out::println);

}
 
Example #10
Source File: IdsConverter.java    From sbp with Apache License 2.0 5 votes vote down vote up
@Override
public MatchResult match(Class<?> sourceType, Class<?> destinationType) {
    return Record.class.isAssignableFrom(sourceType)
            && Collection.class.isAssignableFrom(destinationType)
            ? MatchResult.FULL
            : MatchResult.NONE;
}
 
Example #11
Source File: PurityDAO.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
List<String> getSampleIds() {
    List<String> sampleIds = Lists.newArrayList();

    Result<Record> result = context.select().from(PURITY).fetch();

    for (Record record : result) {
        sampleIds.add(record.getValue(PURITY.SAMPLEID));
    }

    return sampleIds;
}
 
Example #12
Source File: Dao.java    From StubbornJava with MIT License 5 votes vote down vote up
/**
 * [#2700] [#3582] If a POJO attribute is NULL, but the column is NOT NULL
 * then we should let the database apply DEFAULT values
 */
private static final void resetChangedOnNotNull(Record record) {
    int size = record.size();

    for (int i = 0; i < size; i++)
        if (record.get(i) == null)
            if (!record.field(i).getDataType().nullable())
                record.changed(i, false);
}
 
Example #13
Source File: TaxonomyChangeDao.java    From waltz with Apache License 2.0 5 votes vote down vote up
private static Map<String, ? extends String> readParams(Record r) {
    try {
        return JSON_MAPPER.readValue(
                r.get(TAXONOMY_CHANGE.PARAMS),
                Map.class);
    } catch (Exception e) {
        return new HashMap<>();
    }
}
 
Example #14
Source File: CMSCrawler.java    From oneops with Apache License 2.0 5 votes vote down vote up
private void crawlClouds(Connection conn) {

        DSLContext create = DSL.using(conn, SQLDialect.POSTGRES);

        log.info("Fetching all clouds..");
        Result<Record> cloudRecords = create.select().from(CM_CI)
                .join(MD_CLASSES).on(CM_CI.CLASS_ID.eq(MD_CLASSES.CLASS_ID))
                .join(NS_NAMESPACES).on(CM_CI.NS_ID.eq(NS_NAMESPACES.NS_ID))
                .where(MD_CLASSES.CLASS_NAME.eq("account.Cloud"))
                .fetch(); //all the env cis
        log.info("Got all clouds ");


        for (Record r : cloudRecords) {
            if (shutDownRequested) {
                log.info("Shutdown requested, exiting !");
                break;
            }

            long cloudId = r.getValue(CM_CI.CI_ID);
            String cloudName = r.getValue(CM_CI.CI_NAME);
            String cloudNS = r.getValue(NS_NAMESPACES.NS_PATH);
            if (syncClouds) {
                syncCloudVariables(cloudId, cloudName, cloudNS, conn);
            }
        }
    }
 
Example #15
Source File: HmfGenePanelBuilder.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private static void writeFile(@NotNull final CommandLine cmd, @NotNull final Result<Record> records) throws IOException {
    final BufferedWriter writer = new BufferedWriter(new FileWriter(cmd.getOptionValue(OUT_PATH), false));
    // Format as tsv without header containing column names
    final CSVFormat format = new CSVFormat().header(false).delimiter('\t').nullString("").quoteString("");
    writer.write(records.formatCSV(format));
    writer.close();
}
 
Example #16
Source File: IdsConverter.java    From sbp with Apache License 2.0 5 votes vote down vote up
@Override
public List<Long> convert(MappingContext<Record, List<Long>> context) {
    Object source = context.getSource();
    String idsInString = (String) source;
    if (idsInString == null || idsInString.length() <= 0)
        return new ArrayList<>();

    String[] ids = idsInString.split(",");
    return Arrays.stream(ids)
            .map(Long::parseLong)
            .collect(Collectors.toList());
}
 
Example #17
Source File: AclDAO.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
public ImmutableSet<SanitizedSecret> getSanitizedSecretsFor(Client client) {
  checkNotNull(client);

  ImmutableSet.Builder<SanitizedSecret> sanitizedSet = ImmutableSet.builder();

  SelectQuery<Record> query = dslContext.select(SECRETS.fields())
      .from(SECRETS)
      .join(ACCESSGRANTS).on(SECRETS.ID.eq(ACCESSGRANTS.SECRETID))
      .join(MEMBERSHIPS).on(ACCESSGRANTS.GROUPID.eq(MEMBERSHIPS.GROUPID))
      .join(CLIENTS).on(CLIENTS.ID.eq(MEMBERSHIPS.CLIENTID))
      .join(SECRETS_CONTENT).on(SECRETS_CONTENT.ID.eq(SECRETS.CURRENT))
      .where(CLIENTS.NAME.eq(client.getName()).and(SECRETS.CURRENT.isNotNull()))
      .getQuery();
  query.addSelect(SECRETS_CONTENT.CONTENT_HMAC);
  query.addSelect(SECRETS_CONTENT.CREATEDAT);
  query.addSelect(SECRETS_CONTENT.CREATEDBY);
  query.addSelect(SECRETS_CONTENT.METADATA);
  query.addSelect(SECRETS_CONTENT.EXPIRY);
  query.addSelect(ACCESSGRANTS.ROW_HMAC);
  query.addSelect(MEMBERSHIPS.ROW_HMAC);
  query.addSelect(MEMBERSHIPS.GROUPID);
  query.addSelect(CLIENTS.ROW_HMAC);
  query.addSelect(SECRETS.ROW_HMAC);
  query.fetch()
      .map(row -> processSanitizedSecretRow(row, client))
      .forEach(sanitizedSet::add);

  return sanitizedSet.build();
}
 
Example #18
Source File: Labels.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
public <O extends Record> Labels(Table<O> child, ForeignKey<O, LabelsRecord> key) {
    super(child, key, LABELS);
    this.ID = createField("id", SQLDataType.INTEGER.nullable(false).defaultValue(DSL.field("nextval('tags_id_seq'::regclass)", SQLDataType.INTEGER)), this, "");
    this.UUID = createField("uuid", SQLDataType.UUID.nullable(false), this, "");
    this.NAME = createField("name", SQLDataType.VARCHAR(500).nullable(false), this, "");
    this.OBSOLETE = createField("obsolete", SQLDataType.BOOLEAN.nullable(false).defaultValue(DSL.field("false", SQLDataType.BOOLEAN)), this, "");
}
 
Example #19
Source File: CopyNumberDAO.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public List<PurpleCopyNumber> read(@NotNull String sample) {
    List<PurpleCopyNumber> copyNumbers = Lists.newArrayList();

    Result<Record> result = context.select().from(COPYNUMBER).where(COPYNUMBER.SAMPLEID.eq(sample)).fetch();

    for (Record record : result) {
        copyNumbers.add(ImmutablePurpleCopyNumber.builder()
                .chromosome(record.getValue(COPYNUMBER.CHROMOSOME))
                .start(record.getValue(COPYNUMBER.START))
                .end(record.getValue(COPYNUMBER.END))
                .bafCount(record.getValue(COPYNUMBER.BAFCOUNT))
                .method(CopyNumberMethod.valueOf(record.getValue(COPYNUMBER.COPYNUMBERMETHOD)))
                .segmentStartSupport(SegmentSupport.valueOf(record.getValue(COPYNUMBER.SEGMENTSTARTSUPPORT)))
                .segmentEndSupport(SegmentSupport.valueOf(record.getValue(COPYNUMBER.SEGMENTENDSUPPORT)))
                .averageActualBAF(record.getValue(COPYNUMBER.BAF))
                .averageObservedBAF(record.getValue(COPYNUMBER.OBSERVEDBAF))
                .averageTumorCopyNumber(record.getValue(COPYNUMBER.COPYNUMBER_))
                .depthWindowCount(record.getValue(COPYNUMBER.DEPTHWINDOWCOUNT))
                .gcContent(record.getValue(COPYNUMBER.GCCONTENT))
                .minStart(record.getValue(COPYNUMBER.MINSTART))
                .maxStart(record.getValue(COPYNUMBER.MAXSTART))
                .build());
    }

    Collections.sort(copyNumbers);
    return copyNumbers;
}
 
Example #20
Source File: HistoricalLocationFactory.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public HistoricalLocation create(Record tuple, Query query, DataSize dataSize) {
    HistoricalLocation entity = new HistoricalLocation();
    J id = getFieldOrNull(tuple, table.getId());
    if (id != null) {
        entity.setId(entityFactories.idFromObject(id));
    }
    entity.setThing(entityFactories.thingFromId(tuple, table.getThingId()));
    entity.setTime(Utils.instantFromTime(getFieldOrNull(tuple, table.time)));
    return entity;
}
 
Example #21
Source File: TableLongFeatures.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Class<Record> getRecordType() {
    return Record.class;
}
 
Example #22
Source File: Somethingwithoutjson.java    From vertx-jooq with MIT License 4 votes vote down vote up
public <O extends Record> Somethingwithoutjson(Table<O> child, ForeignKey<O, SomethingwithoutjsonRecord> key) {
    super(child, key, SOMETHINGWITHOUTJSON);
}
 
Example #23
Source File: EntityFactories.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Datastream datastreamFromId(Record tuple, Field<J> path) {
    return datastreamFromId(getFieldOrNull(tuple, path));
}
 
Example #24
Source File: Somethingcomposite.java    From vertx-jooq with MIT License 4 votes vote down vote up
public <O extends Record> Somethingcomposite(Table<O> child, ForeignKey<O, SomethingcompositeRecord> key) {
    super(child, key, SOMETHINGCOMPOSITE);
}
 
Example #25
Source File: TableLongMultiDatastreamsObsProperties.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Class<Record> getRecordType() {
    return Record.class;
}
 
Example #26
Source File: JDBCQueryResult.java    From vertx-jooq with MIT License 4 votes vote down vote up
private JDBCQueryResult(Result<? extends Record> result, int index) {
    this.result = result;
    this.index = index;
}
 
Example #27
Source File: Somethingwithoutjson.java    From vertx-jooq with MIT License 4 votes vote down vote up
public <O extends Record> Somethingwithoutjson(Table<O> child, ForeignKey<O, SomethingwithoutjsonRecord> key) {
    super(child, key, SOMETHINGWITHOUTJSON);
}
 
Example #28
Source File: Issue587Test.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
@Test
public void testFetchResultSet() throws SQLException {
    Connection conn = DbHelper.getDbConnection(DbHelper.TargetDB.POSTGRESQL);
    if (conn == null) return;
    try {


        Statement statement = conn.createStatement();

        statement.executeUpdate("CREATE TABLE IF NOT EXISTS issue_587(id int, t timestamptz)");
        statement.executeUpdate("TRUNCATE issue_587");
        statement.executeUpdate("insert into issue_587 values (1, timestamp with time zone '2018-11-15 11:45:11.00000+01:00')");

        DSLContext dsl = DSL
                .using(new DefaultConfiguration().set(conn)
                        .set(SQLDialect.POSTGRES)
                        .set(SfmRecordMapperProviderFactory.newInstance().ignorePropertyNotFound().newProvider()));

        DynamicJdbcMapper<Issue587> mapper = JdbcMapperFactory.newInstance().newMapper(Issue587.class);
        OffsetDateTime date = OffsetDateTime.parse("2018-11-15T11:45:11+01:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);

        OffsetDateTime expected = date.withOffsetSameInstant(ZoneOffset.UTC);

        SelectWhereStep<Record> select = dsl.selectFrom("issue_587");


        try (ResultSet rs = select.fetchResultSet()) {
            ResultSetMetaData metaData = rs.getMetaData();
            System.out.println("metaData = " + metaData.getColumnType(2));
            System.out.println("metaData = " + metaData.getColumnClassName(2));
            System.out.println("metaData = " + metaData.getColumnTypeName(2));

            while (rs.next()) {
                System.out.println("rs.getObject(2) = " + rs.getObject(2));
            }
        }
        

        try (ResultSet rs = select.fetchResultSet()) {
            Issue587[] issue587s = mapper.stream(rs).toArray(Issue587[]::new);
            System.out.println("issue587s = " + Arrays.toString(issue587s));

            assertEquals(1, issue587s.length);

            assertEquals(1, issue587s[0].id);
            assertEquals(expected, issue587s[0].t);
        }

    } finally {
        conn.close();
    }
    

}
 
Example #29
Source File: JooqMapperBuilder.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
public JooqMapperBuilder(final ClassMeta<E> classMeta,
						 MappingContextFactoryBuilder<Record, JooqFieldKey> mappingContextFactoryBuilder) throws MapperBuildingException {
	this(classMeta, mappingContextFactoryBuilder, MapperConfig.<JooqFieldKey, Record>fieldMapperConfig());
}
 
Example #30
Source File: TableUuidMultiDatastreams.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public TableField<Record, UUID> getId() {
    return colId;
}