org.skife.jdbi.v2.Query.fold()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(11.1k)|赞(0)|评价(0)|浏览(174)

本文整理了Java中org.skife.jdbi.v2.Query.fold方法的一些代码示例,展示了Query.fold的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query.fold方法的具体详情如下:
包路径:org.skife.jdbi.v2.Query
类名称:Query
方法名:fold

Query.fold介绍

[英]Used to execute the query and traverse the result set with a accumulator. Folding over the result involves invoking a callback for each row, passing into the callback the return value from the previous function invocation.
[中]用于执行查询并使用累加器遍历结果集。结果上的{$0$}涉及为每一行调用回调,将上一次函数调用的返回值传递到回调中。

代码示例

代码示例来源:origin: apache/hive

/**
 * @param connector                   SQL metadata connector to the metadata storage
 * @param metadataStorageTablesConfig Table config
 *
 * @return all the active data sources in the metadata storage
 */
static Collection<String> getAllDataSourceNames(SQLMetadataConnector connector,
  final MetadataStorageTablesConfig metadataStorageTablesConfig) {
 return connector.getDBI()
   .withHandle((HandleCallback<List<String>>) handle -> handle.createQuery(String.format(
     "SELECT DISTINCT(datasource) FROM %s WHERE used = true",
     metadataStorageTablesConfig.getSegmentsTable()))
     .fold(Lists.<String>newArrayList(),
       (druidDataSources, stringObjectMap, foldController, statementContext) -> {
        druidDataSources.add(MapUtils.getString(stringObjectMap, "datasource"));
        return druidDataSources;
       }));
}

代码示例来源:origin: apache/incubator-druid

.fold(
  new HashMap<>(),
  new Folder3<Map<String, List<Rule>>, Pair<String, List<Rule>>>()

代码示例来源:origin: apache/incubator-druid

).fold(
  new HashMap<>(),
  new Folder3<Map<String, SupervisorSpec>, Pair<String, SupervisorSpec>>()

代码示例来源:origin: apache/incubator-druid

).fold(
  new HashMap<>(),
  new Folder3<Map<String, List<VersionedSupervisorSpec>>, Pair<String, VersionedSupervisorSpec>>()

代码示例来源:origin: apache/hive

/**
 * @param connector                   SQL connector to metadata
 * @param metadataStorageTablesConfig Tables configuration
 * @param dataSource                  Name of data source
 *
 * @return List of all data segments part of the given data source
 */
static List<DataSegment> getDataSegmentList(final SQLMetadataConnector connector,
  final MetadataStorageTablesConfig metadataStorageTablesConfig,
  final String dataSource) {
 return connector.retryTransaction((handle, status) -> handle.createQuery(String.format(
   "SELECT payload FROM %s WHERE dataSource = :dataSource",
   metadataStorageTablesConfig.getSegmentsTable()))
   .setFetchSize(getStreamingFetchSize(connector))
   .bind("dataSource", dataSource)
   .map(ByteArrayMapper.FIRST)
   .fold(new ArrayList<>(), (Folder3<List<DataSegment>, byte[]>) (accumulator, payload, control, ctx) -> {
    try {
     final DataSegment segment = DATA_SEGMENT_INTERNER.intern(JSON_MAPPER.readValue(payload, DataSegment.class));
     accumulator.add(segment);
     return accumulator;
    } catch (Exception e) {
     throw new SQLException(e.toString());
    }
   }), 3, DEFAULT_MAX_TRIES);
}

代码示例来源:origin: apache/incubator-druid

@Override
public Collection<String> getAllDataSourceNames()
{
 return connector.getDBI().withHandle(
   handle -> handle.createQuery(
     StringUtils.format("SELECT DISTINCT(datasource) FROM %s", getSegmentsTable())
   )
           .fold(
             new ArrayList<>(),
             new Folder3<List<String>, Map<String, Object>>()
             {
              @Override
              public List<String> fold(
                List<String> druidDataSources,
                Map<String, Object> stringObjectMap,
                FoldController foldController,
                StatementContext statementContext
              )
              {
               druidDataSources.add(
                 MapUtils.getString(stringObjectMap, "datasource")
               );
               return druidDataSources;
              }
             }
           )
 );
}

代码示例来源:origin: apache/incubator-druid

@Override
 public List<LogType> withHandle(Handle handle)
 {
  return handle
    .createQuery(
      StringUtils.format(
        "SELECT log_payload FROM %1$s WHERE %2$s_id = :entryId",
        logTable, entryTypeName
      )
    )
    .bind("entryId", entryId)
    .map(ByteArrayMapper.FIRST)
    .fold(
      new ArrayList<>(),
      (List<LogType> list, byte[] bytes, FoldController control, StatementContext ctx) -> {
       try {
        list.add(jsonMapper.readValue(bytes, logType));
        return list;
       }
       catch (IOException e) {
        log.makeAlert(e, "Failed to deserialize log")
          .addData("entryId", entryId)
          .addData("payload", StringUtils.fromUtf8(bytes))
          .emit();
        throw new SQLException(e);
       }
      }
    );
 }
}

代码示例来源:origin: apache/incubator-druid

.fold(
  Maps.newLinkedHashMap(),
  new Folder3<Map<Long, LockType>, Pair<Long, LockType>>()

代码示例来源:origin: apache/incubator-druid

.bind("end", interval.getEnd().toString())
.map(ByteArrayMapper.FIRST)
.fold(
  new ArrayList<>(),
  new Folder3<List<DataSegment>, byte[]>()

代码示例来源:origin: com.ning.billing/killbill-osgi-bundles-analytics

public <ContainerType> ContainerType list(Class<ContainerType> containerType)
{
  ContainerBuilder<ContainerType> builder = getContainerMapperRegistry().createBuilderFor(containerType);
  return fold(builder, new Folder3<ContainerBuilder<ContainerType>, ResultType>()
  {
    public ContainerBuilder<ContainerType> fold(ContainerBuilder<ContainerType> accumulator,
                          ResultType rs,
                          FoldController ctl,
                          StatementContext ctx) throws SQLException
    {
      accumulator.add(rs);
      return accumulator;
    }
  }).build();
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Override
public <ContainerType> ContainerType list(Class<ContainerType> containerType)
{
  ContainerBuilder<ContainerType> builder = getContainerMapperRegistry().createBuilderFor(containerType);
  return fold(builder, new Folder3<ContainerBuilder<ContainerType>, ResultType>()
  {
    @Override
    public ContainerBuilder<ContainerType> fold(ContainerBuilder<ContainerType> accumulator,
                          ResultType rs,
                          FoldController ctl,
                          StatementContext ctx) throws SQLException
    {
      accumulator.add(rs);
      return accumulator;
    }
  }).build();
}

代码示例来源:origin: com.ning.billing/killbill-osgi-bundles-analytics

public <T> T first(Class<T> containerType)
{
  addStatementCustomizer(StatementCustomizers.MAX_ROW_ONE);
  ContainerBuilder builder = getContainerMapperRegistry().createBuilderFor(containerType);
  return (T) this.fold(builder, new Folder3<ContainerBuilder, ResultType>()
  {
    public ContainerBuilder fold(ContainerBuilder accumulator, ResultType rs, FoldController control, StatementContext ctx) throws SQLException
    {
      accumulator.add(rs);
      control.abort();
      return accumulator;
    }
  }).build();
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Override
public <T> T first(Class<T> containerType)
{
  // Kill Bill specific: assume our queries will always either use LIMIT 1 or will return exactly one row (see ResultReturnThing)
  // This saves a roundtrip (set @@SQL_SELECT_LIMIT=1)
  //addStatementCustomizer(StatementCustomizers.MAX_ROW_ONE);
  ContainerBuilder builder = getContainerMapperRegistry().createBuilderFor(containerType);
  return (T) this.fold(builder, new Folder3<ContainerBuilder, ResultType>()
  {
    @Override
    public ContainerBuilder fold(ContainerBuilder accumulator, ResultType rs, FoldController control, StatementContext ctx) throws SQLException
    {
      accumulator.add(rs);
      control.abort();
      return accumulator;
    }
  }).build();
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testFluentApi() throws Exception
{
  Map<String, Team> teams = handle.createQuery("select t.name as teamName, " +
                         "       t.mascot as mascot, " +
                         "       p.name as personName, " +
                         "       p.role as role " +
                         "from team t inner join person p on (t.name = p.team)")
                  .map(TeamPersonJoinRow.class)
                  .fold(Maps.<String, Team>newHashMap(), new TeamFolder());
  assertThat(teams, equalTo(expected));
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Test
public void testFluentApi() throws Exception
{
  Map<String, Team> teams = handle.createQuery("select t.name as teamName, " +
                         "       t.mascot as mascot, " +
                         "       p.name as personName, " +
                         "       p.role as role " +
                         "from team t inner join person p on (t.name = p.team)")
                  .map(TeamPersonJoinRow.class)
                  .fold(Maps.<String, Team>newHashMap(), new TeamFolder());
  assertThat(teams, equalTo(expected));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testFold() throws Exception
{
  h.prepareBatch("insert into something (id, name) values (:id, :name)")
   .add(1, "Brian")
   .add(2, "Keith")
   .execute();
  Map<String, Integer> rs = h.createQuery("select id, name from something")
                .fold(new HashMap<String, Integer>(), new Folder2<Map<String, Integer>>()
                {
                  @Override
                public Map<String, Integer> fold(Map<String, Integer> a, ResultSet rs, StatementContext context) throws SQLException
                  {
                    a.put(rs.getString("name"), rs.getInt("id"));
                    return a;
                  }
                });
  assertEquals(2, rs.size());
  assertEquals(Integer.valueOf(1), rs.get("Brian"));
  assertEquals(Integer.valueOf(2), rs.get("Keith"));
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Test
public void testFold() throws Exception
{
  h.prepareBatch("insert into something (id, name) values (:id, :name)")
   .add(1, "Brian")
   .add(2, "Keith")
   .execute();
  Map<String, Integer> rs = h.createQuery("select id, name from something")
                .fold(new HashMap<String, Integer>(), new Folder2<Map<String, Integer>>()
                {
                  @Override
                public Map<String, Integer> fold(Map<String, Integer> a, ResultSet rs, StatementContext context) throws SQLException
                  {
                    a.put(rs.getString("name"), rs.getInt("id"));
                    return a;
                  }
                });
  assertEquals(2, rs.size());
  assertEquals(Integer.valueOf(1), rs.get("Brian"));
  assertEquals(Integer.valueOf(2), rs.get("Keith"));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testFold() throws Exception
{
  DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID());
  Handle h = dbi.open();
  h.execute("create table something (id int primary key, name varchar(100))");
  h.execute("insert into something (id, name) values (7, 'Mark')");
  h.execute("insert into something (id, name) values (8, 'Tatu')");
  StringBuilder rs = h.createQuery("select name from something order by id")
    .mapTo(String.class)
    .fold(new StringBuilder(), new Folder2<StringBuilder>()
    {
      @Override
      public StringBuilder fold(StringBuilder acc, ResultSet rs, StatementContext ctx) throws SQLException
      {
        acc.append(rs.getString(1)).append(", ");
        return acc;
      }
    });
  rs.delete(rs.length() - 2, rs.length()); // trim the extra ", "
  assertThat(rs.toString(), equalTo("Mark, Tatu"));
  h.close();
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Test
public void testFold3() throws Exception
{
  h.prepareBatch("insert into something (id, name) values (:id, :name)")
   .add(1, "Brian")
   .add(2, "Keith")
   .execute();
  List<String> rs = h.createQuery("select name from something order by id")
            .map(StringMapper.FIRST)
            .fold(new ArrayList<String>(), new Folder3<List<String>, String>()
            {
              @Override
            public List<String> fold(List<String> a, String rs, FoldController ctl, StatementContext ctx) throws SQLException
              {
                a.add(rs);
                return a;
              }
            });
  assertEquals(2, rs.size());
  assertEquals(Arrays.asList("Brian", "Keith"), rs);
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testFold3() throws Exception
{
  h.prepareBatch("insert into something (id, name) values (:id, :name)")
   .add(1, "Brian")
   .add(2, "Keith")
   .execute();
  List<String> rs = h.createQuery("select name from something order by id")
            .mapTo(String.class)
            .fold(new ArrayList<String>(), new Folder3<List<String>, String>()
            {
              @Override
            public List<String> fold(List<String> a, String rs, FoldController ctl, StatementContext ctx) throws SQLException
              {
                a.add(rs);
                return a;
              }
            });
  assertEquals(2, rs.size());
  assertEquals(Arrays.asList("Brian", "Keith"), rs);
}

相关文章