Here are the examples of the java api org.jooq.Record taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
58 Examples
19
Source : Dao.java
with MIT License
from StubbornJava
with MIT License
from StubbornJava
// Copy pasted from jOOQ's Tools.java
/**
* [#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);
}
19
Source : Reader.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
/**
* 批量记录读取操作
*/
static DataEvent doReads(/* 执行该方法的类 */
final Clreplaced<?> clazz, /* 入参,专用DTO */
final DataEvent event, /* 核心执行函数,到多张表 */
final BiFunction<String, List<DataMatrix>, Record[]> actor) {
/* 读取所有数据行,有几张表查几次 */
Data.doExecute(clazz, event, (rows) -> {
/* 按表转换,转换成 Table -> List<DataMatrix> 的结构 */
final ConcurrentMap<String, List<DataMatrix>> batch = Argument.batch(rows);
/* 按表批量处理 */
batch.keySet().forEach(table -> {
/* 执行单表记录 */
final List<DataMatrix> values = batch.get(table);
Data.doInput(table, values);
final Record[] records = actor.apply(table, values);
/* 合并两个结果集 */
Data.doJoin(rows, records).accept(table);
});
});
/* 执行最终返回 */
return Data.doFinal(event);
}
19
Source : Reader.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
/**
* 单条记录读取操作
*/
static DataEvent doRead(/* 执行该方法的类 */
final Clreplaced<?> clazz, /* 入参,专用DTO */
final DataEvent event, /* 核心执行函数,到单张表 */
final BiFunction<String, DataMatrix, Record> actor) {
/* 读取所有数据行 */
Data.doExecute(clazz, event, (rows) -> rows.forEach(row -> row.matrixData().forEach((table, matrix) -> {
Data.doInput(table, matrix);
/* 记录处理 */
final Record record = actor.apply(table, matrix);
/* 设置反向同步记录 */
row.success(table, record, new HashSet<>());
})));
/* 执行最终返回 */
return Data.doFinal(event);
}
19
Source : Query.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
/**
* 查询和其他操作执行分流处理
*/
static DataEvent doQuery(/* 当前操作类 */
final Clreplaced<?> clazz, /* 发送的事件 */
final DataEvent event, /* Bi Consumer */
final BiFunction<Set<String>, Ingest, Record> consumer) {
final Ingest ingest = getIngest(event);
final ConcurrentMap<String, DataMatrix> matrix = getMatrix(clazz, event);
final DataTpl tpl = event.getTpl();
final Set<String> projection = event.getProjection();
/* 5. 执行结果 */
final Record record = consumer.apply(matrix.keySet(), ingest);
/* 6. 处理行数据 */
event.stored(Data.doJoin(matrix.keySet(), new Record[] { record }, tpl, projection));
return event;
}
19
Source : Query.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
static DataEvent doQuery(/* 当前操作类 */
final Clreplaced<?> clazz, /* 发送的事件 */
final DataEvent event, /* Bi Consumer */
final BiFunction<Set<String>, Ingest, Record[]> consumer, /* Bi Counter */
final BiFunction<Set<String>, Ingest, Long> counter) {
final Ingest ingest = getIngest(event);
final ConcurrentMap<String, DataMatrix> matrix = getMatrix(clazz, event);
final DataTpl tpl = event.getTpl();
final Set<String> projection = event.getProjection();
final Record[] records = consumer.apply(matrix.keySet(), ingest);
event.stored(Data.doJoin(matrix.keySet(), records, tpl, projection));
if (Objects.nonNull(counter)) {
final Long count = counter.apply(matrix.keySet(), ingest);
event.stored(count);
}
return event;
}
19
Source : Data.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
static Consumer<String> doJoin(final List<DataRow> rows, final Record[] records) {
return table -> {
/* 两个数据集按索引合并 */
for (int idx = Values.IDX; idx < rows.size(); idx++) {
final DataRow row = rows.get(idx);
if (null != row) {
if (idx < records.length) {
final Record record = records[idx];
/* 直接调用内置方法 */
row.success(table, record, new HashSet<>());
} else {
/* 空数据返回 */
row.success(table, null, new HashSet<>());
}
}
}
};
}
19
Source : Data.java
with Apache License 2.0
from silentbalanceyh
with Apache License 2.0
from silentbalanceyh
static List<DataRow> doJoin(final Set<String> tableSet, final Record[] records, final DataTpl tpl, final Set<String> projection) {
final List<DataRow> rows = new ArrayList<>();
for (final Record record : records) {
final DataRow row = new DataRow(tpl);
tableSet.forEach(table -> row.success(table, record, projection));
rows.add(row);
}
return rows;
}
19
Source : TestUtil.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
/**
* Creates a record with the given fields mapped to the given values. If any of the fields are
* table fields, and some of the other fields in the same table are not given in the mapping, then
* null values are inserted automatically for those other fields. If {@code nullTables} is given,
* then also null values are inserted for all fields in those tables.
*/
static Record createRecord(ImmutableMap<Field<?>, Object> values, Table<?>... nullTables) {
Stream<Field<?>> tableFields = Stream.concat(Stream.of(nullTables), values.keySet().stream().filter(TableField.clreplaced::isInstance).map(f -> (TableField<?, ?>) f).map(TableField::getTable)).flatMap(Table::fieldStream);
Stream<Field<?>> extraFields = values.keySet().stream().filter(f -> !(f instanceof TableField));
Record result = MOCK_CONTEXT.newRecord(Stream.concat(tableFields, extraFields).toArray(Field<?>[]::new));
values.forEach((f, v) -> setValue(result, f, v));
return result;
}
19
Source : TestUtil.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
private static <T> void setValue(Record record, Field<T> field, Object value) {
checkArgument(value == null || field.getType().isInstance(value));
record.set(field, field.getType().cast(value));
}
19
Source : EntityTest.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
@Test
public void testLoadExtraAttributes() {
Field<?> v = DSL.field("v", Integer.clreplaced);
Enreplacedy<?, ?> aEnreplacedy = new Enreplacedy<>(FOO, FooEnreplacedy.clreplaced).withExtraFields(v);
Record record = createRecord(ImmutableMap.of(FOO.ID, 1L, FOO.FOO_, 1, FOO.RELATEDFOOIDS, new Long[0], v, 2));
aEnreplacedy.load(record);
replacedertions.replacedertEquals(aEnreplacedy.get(1), new FooEnreplacedy(1L, 1, new Long[0], 2));
}
19
Source : EntityTest.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
@Test
public void testLoadAdHocTable() {
Field<Long> id = DSL.field("id", Long.clreplaced);
Field<Integer> foo = DSL.field("foo", Integer.clreplaced);
Table<Record2<Long, Integer>> adHoc = DSL.select(id, foo).asTable("AdHoc");
Enreplacedy<?, ?> aEnreplacedy = new Enreplacedy<>(adHoc, FooEnreplacedy.clreplaced, adHoc.field(id));
Record record = createRecord(ImmutableMap.of(adHoc.field(id), 1L, adHoc.field(foo), 1));
aEnreplacedy.load(record);
replacedertions.replacedertEquals(aEnreplacedy.get(1), new FooEnreplacedy(1L, 1, null));
}
19
Source : EntityTest.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
@Test
public void testLoadWrongTable() {
Foo bar = FOO.as("BAR");
Enreplacedy<?, ?> aEnreplacedy = new Enreplacedy<>(FOO, FooEnreplacedy.clreplaced);
Record record = createRecord(ImmutableMap.of(bar.ID, 1L, bar.FOO_, 1));
replacedertThrows(ValidationException.clreplaced, () -> aEnreplacedy.load(record));
}
19
Source : Relation.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
/**
* Attempts to load a single pair from this relation from the given record. This is done by
* looking up the two key fields replacedociated with this record (either a primary key and a foreign
* key, or two foreign keys in case of a many-to-may relation), and if both can be found, the two
* values are considered to represent a pair that is part of the relation.
*/
private void foreignKeyRelationLoader(Record record, Set<IdPair> sink) {
Long leftId = record.get(leftKey);
Long rightId = record.get(rightKey);
if (leftId != null && rightId != null) {
sink.add(IdPair.of(leftId, rightId));
}
}
19
Source : UserRepository.java
with Apache License 2.0
from oneops
with Apache License 2.0
from oneops
/**
* A helper method to map the team record to {@link OneOpsTeam}
*/
private static OneOpsTeam mapRecord(Record r) {
return r.into(TEAMS.NAME, TEAMS.DESCRIPTION, TEAMS.DESIGN, TEAMS.TRANSITION, TEAMS.OPERATIONS).into(OneOpsTeam.clreplaced);
}
19
Source : Application.java
with MIT License
from hellokoding
with MIT License
from hellokoding
public static void main(String[] args) throws Exception {
String user = System.getProperty("jdbc.user");
String preplacedword = System.getProperty("jdbc.preplacedword");
String url = System.getProperty("jdbc.url");
String driver = System.getProperty("jdbc.driver");
Clreplaced.forName(driver).newInstance();
try (Connection connection = DriverManager.getConnection(url, user, preplacedword)) {
DSLContext dslContext = DSL.using(connection, SQLDialect.MYSQL);
Result<Record> result = dslContext.select().from(AUTHOR).fetch();
for (Record r : result) {
Integer id = r.getValue(AUTHOR.ID);
String firstName = r.getValue(AUTHOR.FIRST_NAME);
String lastName = r.getValue(AUTHOR.LAST_NAME);
System.out.println("ID: " + id + " first name: " + firstName + " last name: " + lastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
19
Source : RowConverter.java
with MIT License
from gofabian
with MIT License
from gofabian
public <R extends Record> R convertRowToRecord(DSLContext dslContext, Row row, List<Field<?>> fields, Clreplaced<? extends R> recordType) {
// collect values in fields order
Object[] values = new Object[fields.size()];
for (int i = 0; i < fields.size(); i++) {
Object value = row.get(i, Object.clreplaced);
Clreplaced<?> targetType = fields.get(i).getConverter().fromType();
values[i] = converter.toJooqValue(value, targetType);
}
// create intermediate record
Record record = dslContext.newRecord(fields);
record.fromArray(values);
record.changed(false);
return record.into(recordType);
}
19
Source : Utils.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
private static <J extends Comparable> void handleNumber(Observation enreplacedy, Record tuple, AbstractTableObservations<J> table) {
try {
enreplacedy.setResult(new BigDecimal(Utils.getFieldOrNull(tuple, table.colResultString)));
} catch (NumberFormatException | NullPointerException e) {
// It was not a Number? Use the double value.
enreplacedy.setResult(Utils.getFieldOrNull(tuple, table.colResultNumber));
}
}
19
Source : Utils.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
/**
* Get the given Field from the record, or null if the record does not have
* the Field.
*
* @param <T> The type of the requested Field.
* @param record The record to fetch the field from.
* @param field The field to fetch from the record.
* @return The value of the field, or null if the record does not have the
* Field.
*/
public static <T> T getFieldOrNull(Record record, Field<T> field) {
if (record.field(field) != null) {
return record.get(field);
}
return null;
}
19
Source : Utils.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public static <J extends Comparable<J>> void readResultFromDb(AbstractTableObservations<J> table, Record tuple, Observation enreplacedy, DataSize dataSize) {
Short resultTypeOrd = Utils.getFieldOrNull(tuple, table.colResultType);
if (resultTypeOrd != null) {
ResultType resultType = ResultType.fromSqlValue(resultTypeOrd);
switch(resultType) {
case BOOLEAN:
enreplacedy.setResult(Utils.getFieldOrNull(tuple, table.colResultBoolean));
break;
case NUMBER:
handleNumber(enreplacedy, tuple, table);
break;
case OBJECT_ARRAY:
JsonValue jsonData = Utils.getFieldJsonValue(tuple, table.colResultJson);
dataSize.increase(jsonData.getStringLength());
enreplacedy.setResult(jsonData.getValue());
break;
case STRING:
String stringData = Utils.getFieldOrNull(tuple, table.colResultString);
dataSize.increase(stringData == null ? 0 : stringData.length());
enreplacedy.setResult(stringData);
break;
default:
LOGGER.error("Unhandled result type: {}", resultType);
throw new IllegalStateException("Unhandled resultType: " + resultType);
}
}
}
19
Source : Utils.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public static JsonValue getFieldJsonValue(Record record, Field<JsonValue> field) {
if (record.field(field) != null) {
return record.get(field);
}
return NULL_JSON_VALUE;
}
19
Source : QueryState.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public E enreplacedyFromQuery(Record tuple, DataSize dataSize) {
return mainTable.enreplacedyFromQuery(tuple, this, dataSize);
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public Datastream datastreamFromId(Record tuple, Field<J> path) {
return datastreamFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public Thing thingFromId(Record tuple, Field<J> path) {
return thingFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public Task taskFromId(Record tuple, Field<J> path) {
return taskFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public Sensor sensorFromId(Record tuple, Field<J> path) {
return sensorFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public MultiDatastream multiDatastreamFromId(Record tuple, Field<J> path) {
return multiDatastreamFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public Actuator actuatorFromId(Record tuple, Field<J> path) {
return actuatorFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public FeatureOfInterest featureOfInterestFromId(Record tuple, Field<J> path) {
return featureOfInterestFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public TaskingCapability taskingCapabilityFromId(Record tuple, Field<J> path) {
return taskingCapabilityFromId(getFieldOrNull(tuple, path));
}
19
Source : EntityFactories.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public ObservedProperty observedProperyFromId(Record tuple, Field<J> path) {
return observedProperyFromId(getFieldOrNull(tuple, path));
}
19
Source : Database.java
with MIT License
from bennofs
with MIT License
from bennofs
private static DumpRunZenodo recordToDumpRunZenodo(Record record) {
return new DumpRunZenodo(recordToDump(record.into(DUMP)), recordToRun(record.into(RUN)), recordToZenodo(record.into(ZENODO_SANDBOX)), recordToZenodo(record.into(ZENODO_RELEASE)));
}
19
Source : PdnsOutput.java
with MIT License
from 1and1
with MIT License
from 1and1
private void queueTransaction(List<OutputUpdate> actions) {
long output_id = actions.get(0).output_id;
long retryInterval = (long) Double.parseDouble(config.getProperty("retryInterval")) * 1000;
OutputThread thread = outputs.computeIfAbsent(output_id, key -> {
Record output = transactionCall(dimDataSource, dim -> dim.fetchOne("SELECT * FROM output WHERE id=?", output_id));
if (output == null)
throw new DataAccessException(String.format("output %d was deleted", output_id));
// Make sure the connection pool for the dim db can handle all outputs simultaneously
// we need at least:
// outputs.size() + 1 for the OutputThread we add now + 1 for the polling thread
dimDataSource.setMaximumPoolSize(outputs.size() + 5);
OutputThread ret = new OutputThread(output_id, output.get("name", String.clreplaced), output.get("db_uri", String.clreplaced), dimDataSource, retryInterval, printTxn, maxQuerySize);
executor.execute(ret);
return ret;
});
thread.offer(actions);
}
18
Source : Relation.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
/**
* Attempts to load a relation from the given record.
*/
void load(Record record) {
relationLoader.accept(record, pairs);
}
18
Source : Loader.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
@Override
public void next(Record record) {
enreplacedies.forEach(e -> e.load(record));
relations.forEach(r -> r.load(record));
}
18
Source : Entity.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
/**
* Attempts to load an object of type {@code T} from the given record. If the {@link
* #getPrimaryKey() primary key} is not present in the record, no object is loaded. If the primary
* key is found in this record, and an object was already loaded for the same key, then the
* first-loaded object for this key is used.
*/
public void load(Record record) {
if (resultFields == null) {
/*
* jOOQ does not give us a heads up when it loads the first record, so we manually
* detect when the first record is loaded and perform some extra checks in that case.
* Most importantly, we check that the primary key is actually present, but we also
* figure out which of the expected fields are actually present in the record. If we do
* not take this precaution, the default behaviour of jOOQ is to load values from
* similarly named fields, which can lead to very unexpected results.
*
* Since this method is called for every record, we only do all of this once. This is
* not ideal because we have no control over re-use of this object, but in a normal
* usage scenario this object will only ever be used with the same query, and therefore
* we will always retrieve records with the same set of columns.
*/
validate(equalFieldNames(primaryKey, record.field(primaryKey)), "Primary key column %s not found in result record", primaryKey);
resultFields = stream(fields).filter(f -> equalFieldNames(f, record.field(f))).toArray(Field<?>[]::new);
}
Long id = record.get(primaryKey);
if (id != null) {
/*
* The .into(resultFields) makes sure we don't let jOOQ magically use values from fields
* not included in `this.fields`. E.g., if `this.fields = [FOO.ID, FOO.X]` and the
* record contains FOO.ID=1 and BAR.X=1, then without this measure, BAR.X would be used
* instead of FOO.X.
*/
enreplacedies.computeIfAbsent(id, x -> record.into(resultFields).into(type));
}
}
18
Source : QueryState.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
public EnreplacedySet<E> createSetFromRecords(Cursor<Record> tuples, Query query, long maxDataSize) {
EnreplacedySet<E> enreplacedySet = mainTable.newSet();
int count = 0;
DataSize size = new DataSize();
int top = query.getTopOrDefault();
while (tuples.hasNext() && count < top) {
Record tuple = tuples.fetchNext();
enreplacedySet.add(enreplacedyFromQuery(tuple, size));
count++;
if (size.getDataSize() > maxDataSize) {
LOGGER.debug("Size limit reached: {} > {}.", size.getDataSize(), maxDataSize);
return enreplacedySet;
}
}
return enreplacedySet;
}
18
Source : StaTableAbstract.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
@Override
public E enreplacedyFromQuery(Record tuple, QueryState<J, E, T> state, DataSize dataSize) {
E newEnreplacedy = newEnreplacedy();
for (PropertyFields<T, E> sp : state.getSelectedProperties()) {
sp.setter.setOn(state.getMainTable(), tuple, newEnreplacedy, dataSize);
}
return newEnreplacedy;
}
18
Source : MetadataUtils.java
with Apache License 2.0
from fasten-project
with Apache License 2.0
from fasten-project
/**
* Gets the moduleId that corresponds to the file.
* @param fileId - Long fileId
* @return list of module Ids
*/
public List<Long> getModuleIds(Long fileId) {
List<Long> moduleIds = new ArrayList<>();
Result<Record> mcr = selectedContext.select().from(ModuleContents.MODULE_CONTENTS).where(ModuleContents.MODULE_CONTENTS.FILE_ID.equal(fileId)).fetch();
if (mcr.isNotEmpty()) {
for (Record record : mcr) {
moduleIds.add((Long) record.get(0));
}
}
// we cannot return-1 here since that implies external callable
return moduleIds;
}
18
Source : Database.java
with MIT License
from bennofs
with MIT License
from bennofs
public Optional<DumpFullInfo> getDumpWithFullInfo(int id) {
final Record dumpRunRecord = context().selectFrom(DUMP_RUN_ZENODO).where(DUMP.ID.eq(id)).fetchOne();
if (dumpRunRecord == null)
return Optional.empty();
final Dump dump = recordToDump(dumpRunRecord.into(DUMP));
final Run run = recordToRun(dumpRunRecord.into(RUN));
final Zenodo zenodoSandbox = recordToZenodo(dumpRunRecord.into(ZENODO_SANDBOX));
final Zenodo zenodoRelease = recordToZenodo(dumpRunRecord.into(ZENODO_RELEASE));
replacedert dump != null : "SQL query should ensure dump cannot be null";
Condition relatedError = DUMP_ERROR.DUMP_ID.eq(dump.id());
if (run != null) {
relatedError = relatedError.or(DUMP_ERROR.RUN_ID.eq(run.id()));
}
if (zenodoSandbox != null) {
relatedError = relatedError.or(DUMP_ERROR.ZENODO_ID.eq(zenodoSandbox.id()));
}
if (zenodoRelease != null) {
relatedError = relatedError.or(DUMP_ERROR.ZENODO_ID.eq(zenodoRelease.id()));
}
final List<DumpError> errors = context().selectFrom(DUMP_ERROR).where(relatedError).fetch().stream().map(Database::recordToDumpError).collect(Collectors.toList());
return Optional.of(new DumpFullInfo(dump, run, zenodoSandbox, zenodoRelease, errors));
}
17
Source : JooqExamples.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private void jooqFetch() {
Result<Record> results = this.dsl.select().from(AUTHOR).fetch();
for (Record result : results) {
Integer id = result.getValue(AUTHOR.ID);
String firstName = result.getValue(AUTHOR.FIRST_NAME);
String lastName = result.getValue(AUTHOR.LAST_NAME);
System.out.println("jOOQ Fetch " + id + " " + firstName + " " + lastName);
}
}
17
Source : LoaderTest.java
with MIT License
from PicnicSupermarket
with MIT License
from PicnicSupermarket
private static void customRelationLoader(Record record, Set<IdPair> pairs) {
Long barId = record.get(BAR.ID);
if (barId == null) {
return;
}
Long[] fooIds = record.get(FOO.RELATEDFOOIDS);
if (fooIds == null) {
return;
}
Stream.of(fooIds).map(fooId -> IdPair.of(fooId, barId)).forEach(pairs::add);
}
17
Source : QueryTest.java
with MIT License
from gofabian
with MIT License
from gofabian
@Test
void fetchAny() {
Select<?> query = dslContext.select(field(name("id"), Long.clreplaced), field(name("name"), String.clreplaced)).from(name("tab"));
Record record = ReactiveJooq.fetchAny(query).block();
replacedertNotNull(record);
replacedertEquals("fab", record.get(name("name"), String.clreplaced));
}
17
Source : QueryTest.java
with MIT License
from gofabian
with MIT License
from gofabian
@Test
void fetchOne() {
Select<?> query = dslContext.select(field(name("id"), Long.clreplaced), field(name("name"), String.clreplaced)).from(name("tab"));
Record record = ReactiveJooq.fetchOne(query).block();
replacedertNotNull(record);
replacedertEquals("fab", record.get(name("name"), String.clreplaced));
}
17
Source : DefaultJobPersistence.java
with MIT License
from airbytehq
with MIT License
from airbytehq
private static long getEpoch(Record record, String fieldName) {
return record.get(fieldName, LocalDateTime.clreplaced).toEpochSecond(ZoneOffset.UTC);
}
16
Source : PostgresPersistenceManager.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
with GNU Lesser General Public License v3.0
from FraunhoferIOSB
/**
* Gets the requested enreplacedy and locks the row for update. End the
* transaction quickly to release the lock.
*
* @param enreplacedyType The type of enreplacedy to fetch.
* @param id The ID of the enreplacedy to fetch.
* @param forUpdate if true, lock the enreplacedies row for update.
* @return the requested enreplacedy.
*/
private Enreplacedy get(EnreplacedyType enreplacedyType, Id id, boolean forUpdate, Query query) {
QueryBuilder<J> psb = new QueryBuilder<>(this, settings, getTableCollection());
ResultQuery sqlQuery = psb.forTypeAndId(enreplacedyType, id).usingQuery(query).forUpdate(forUpdate).buildSelect();
Record record = sqlQuery.fetchAny();
if (record == null) {
return null;
}
return psb.getQueryState().enreplacedyFromQuery(record, new DataSize());
}
15
Source : MetadataUtils.java
with Apache License 2.0
from fasten-project
with Apache License 2.0
from fasten-project
/**
* Retrieves the callables information from the DB with a given values for the start and end line.
*
* @param moduleId - Long ID of the file where the callable belongs.
* @param qaName - String that represents callable name from Lizard tool.
* @param lineStart - int value that indicates start callable line in source file from Lizard tool.
* @param lineEnd - int value that indicates the last callable line in source file from Lizard tool.
* @param metadata - JSON object that contains callable metadata, to be stored in Metadata DB.
*
* @return List of CallableHolder (empty List if no callable could be found)
*/
private List<CallableHolder> getCallablesInformation(Long moduleId, String qaName, int lineStart, int lineEnd, JSONObject metadata) {
List<CallableHolder> calls = new ArrayList<>();
/*
Get all the records with the moduleId given, with callable name, and
for which there is an overlap between line intervals from Lizard
and OPAL.
*/
Result<Record> crs = selectedContext.select().from(Callables.CALLABLES).where(Callables.CALLABLES.MODULE_ID.equal(moduleId)).andNot(Callables.CALLABLES.LINE_START.gt(lineEnd)).andNot(Callables.CALLABLES.LINE_END.lt(lineStart)).fetch();
logger.info("Fetched " + crs.size() + " entries from callables table");
for (Record cr : crs) {
String fastenUri = (String) cr.get(2);
String separator = ":";
int position = qaName.lastIndexOf(separator);
String methodName = qaName.substring(position + separator.length());
logger.info("fastenUri (from DB) is " + fastenUri);
logger.info("Lizard callable name is " + qaName + " parsed methodName is " + methodName);
if (fastenUri.contains(methodName)) {
// Create callable object
CallableHolder ch = new CallableHolder(cr);
ch.setCallableMetadata(metadata);
// filter and store callable only if start and end line overlap with input
calls.add(ch);
}
}
return calls;
}
13
Source : CMSCrawler.java
with Apache License 2.0
from oneops
with Apache License 2.0
from oneops
private List<Deployment> getDeployments(Connection conn, Environment env) {
List<Deployment> deployments = new ArrayList<>();
DSLContext create = DSL.using(conn, SQLDialect.POSTGRES);
Result<Record> records = create.select().from(DJ_DEPLOYMENT).join(DJ_DEPLOYMENT_STATES).on(DJ_DEPLOYMENT_STATES.STATE_ID.eq(DJ_DEPLOYMENT.STATE_ID)).join(NS_NAMESPACES).on(NS_NAMESPACES.NS_ID.eq(DJ_DEPLOYMENT.NS_ID)).where(NS_NAMESPACES.NS_PATH.eq(env.getPath() + "/" + env.getName() + "/bom")).and(DJ_DEPLOYMENT.CREATED_BY.notEqual("oneops-autoreplace")).orderBy(DJ_DEPLOYMENT.CREATED.desc()).limit(10).fetch();
for (Record r : records) {
Deployment deployment = new Deployment();
deployment.setCreatedAt(r.getValue(DJ_DEPLOYMENT.CREATED));
deployment.setCreatedBy(r.getValue(DJ_DEPLOYMENT.CREATED_BY));
deployment.setState(r.getValue(DJ_DEPLOYMENT_STATES.STATE_NAME));
deployment.setDeploymentId(r.getValue(DJ_DEPLOYMENT.DEPLOYMENT_ID));
deployments.add(deployment);
}
return deployments;
}
12
Source : CMSCrawler.java
with Apache License 2.0
from oneops
with Apache License 2.0
from oneops
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_CLreplacedES).on(CM_CI.CLreplaced_ID.eq(MD_CLreplacedES.CLreplaced_ID)).join(NS_NAMESPACES).on(CM_CI.NS_ID.eq(NS_NAMESPACES.NS_ID)).where(MD_CLreplacedES.CLreplaced_NAME.eq("account.Cloud")).fetch();
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);
}
}
}
11
Source : CMSCrawler.java
with Apache License 2.0
from oneops
with Apache License 2.0
from oneops
private void init(Connection conn) {
DSLContext create = DSL.using(conn, SQLDialect.POSTGRES);
Result<Record> coresAttributes = create.select().from(MD_CLreplaced_ATTRIBUTES).join(MD_CLreplacedES).on(MD_CLreplaced_ATTRIBUTES.CLreplaced_ID.eq(MD_CLreplacedES.CLreplaced_ID)).where(MD_CLreplacedES.CLreplaced_NAME.like("bom%Compute")).and(MD_CLreplaced_ATTRIBUTES.ATTRIBUTE_NAME.eq("cores")).fetch();
for (Record coresAttribute : coresAttributes) {
coresAttributeIds.add(coresAttribute.getValue(MD_CLreplaced_ATTRIBUTES.ATTRIBUTE_ID));
}
// create = DSL.using(conn, SQLDialect.POSTGRES);
Result<Record> computeClreplacedes = create.select().from(MD_CLreplacedES).where(MD_CLreplacedES.CLreplaced_NAME.like("bom%Compute")).fetch();
for (Record computeClreplaced : computeClreplacedes) {
computeClreplacedIds.add(computeClreplaced.get(MD_CLreplacedES.CLreplaced_ID));
}
log.info("cached compute clreplaced ids: " + computeClreplacedIds);
log.info("cached compute cores attribute ids: " + coresAttributeIds);
populateBaseOrganizationClreplacedAttribMappingsCache(conn);
// cache relation attribute ids
Result<Record> relationsAttributes = create.select().from(MD_RELATION_ATTRIBUTES).join(MD_RELATIONS).on(MD_RELATION_ATTRIBUTES.RELATION_ID.eq(MD_RELATIONS.RELATION_ID)).fetch();
for (Record relationAttribute : relationsAttributes) {
if (relationAttribute.getValue(MD_RELATIONS.RELATION_NAME).equalsIgnoreCase("manifest.ComposedOf") && relationAttribute.getValue(MD_RELATION_ATTRIBUTES.ATTRIBUTE_NAME).equalsIgnoreCase("enabled")) {
// cache the "enabled" attribute id of platform
platformEnabledAttributeId = relationAttribute.getValue(MD_RELATION_ATTRIBUTES.ATTRIBUTE_ID);
}
// Here cache more attribute ids as needed for different cases
}
}
10
Source : DefaultJobPersistence.java
with MIT License
from airbytehq
with MIT License
from airbytehq
private static List<Job> getJobsFromResult(Result<Record> result) {
final Map<Long, List<Record>> jobIdToAttempts = result.stream().collect(Collectors.groupingBy(r -> r.getValue("job_id", Long.clreplaced)));
return jobIdToAttempts.values().stream().map(records -> {
final Record jobEntry = records.get(0);
List<Attempt> attempts = Collections.emptyList();
if (jobEntry.get("attempt_number") != null) {
attempts = records.stream().map(attemptRecord -> {
final String outputDb = attemptRecord.get("attempt_output", String.clreplaced);
final JobOutput output = outputDb == null ? null : Jsons.deserialize(outputDb, JobOutput.clreplaced);
return new Attempt(attemptRecord.get("attempt_number", Long.clreplaced), attemptRecord.get("job_id", Long.clreplaced), Path.of(attemptRecord.get("log_path", String.clreplaced)), output, Enums.toEnum(attemptRecord.get("attempt_status", String.clreplaced), AttemptStatus.clreplaced).orElseThrow(), getEpoch(attemptRecord, "attempt_created_at"), getEpoch(attemptRecord, "attempt_updated_at"), Optional.ofNullable(attemptRecord.get("attempt_ended_at")).map(value -> getEpoch(attemptRecord, "attempt_ended_at")).orElse(null));
}).sorted(Comparator.comparingLong(Attempt::getId)).collect(Collectors.toList());
}
final JobConfig jobConfig = Jsons.deserialize(jobEntry.get("config", String.clreplaced), JobConfig.clreplaced);
return new Job(jobEntry.get("job_id", Long.clreplaced), Enums.toEnum(jobEntry.get("config_type", String.clreplaced), ConfigType.clreplaced).orElseThrow(), jobEntry.get("scope", String.clreplaced), jobConfig, attempts, JobStatus.valueOf(jobEntry.get("job_status", String.clreplaced).toUpperCase()), Optional.ofNullable(jobEntry.get("job_started_at")).map(value -> getEpoch(jobEntry, "started_at")).orElse(null), getEpoch(jobEntry, "job_created_at"), getEpoch(jobEntry, "job_updated_at"));
}).sorted(Comparator.comparingLong(Job::getCreatedAtInSecond).reversed()).collect(Collectors.toList());
}
See More Examples