Search in sources :

Example 6 with Bind

use of org.skife.jdbi.v2.sqlobject.Bind in project pac4j by pac4j.

the class DbProfileServiceTests method getData.

private List<Map<String, Object>> getData(final int id) {
    final DBI dbi = new DBI(ds);
    Handle h = null;
    try {
        h = dbi.open();
        return h.createQuery("select id,username,linkedid,password,serializedprofile from users where id = :id").bind("id", id).list(2);
    } finally {
        if (h != null) {
            h.close();
        }
    }
}
Also used : DBI(org.skife.jdbi.v2.DBI) Handle(org.skife.jdbi.v2.Handle)

Example 7 with Bind

use of org.skife.jdbi.v2.sqlobject.Bind in project syndesis by syndesisio.

the class SqlJsonDB method getAsStreamingOutput.

@Override
@SuppressWarnings({ "PMD.ExcessiveMethodLength", "PMD.NPathComplexity" })
public Consumer<OutputStream> getAsStreamingOutput(String path, GetOptions options) {
    GetOptions o;
    if (options != null) {
        o = options;
    } else {
        o = new GetOptions();
    }
    // Lets normalize the path a bit
    String baseDBPath = JsonRecordSupport.convertToDBPath(path);
    String like = baseDBPath + "%";
    GetOptions.Order order = o.order();
    if (order == null) {
        order = GetOptions.Order.ASC;
    }
    Consumer<OutputStream> result = null;
    final Handle h = dbi.open();
    try {
        StringBuilder sql = new StringBuilder(250);
        // Creating the iterator could fail with a runtime exception,
        ArrayList<Consumer<Query<Map<String, Object>>>> binds = new ArrayList<>();
        if (o.filter() == null) {
            sql.append("select path,value,ovalue from jsondb where path LIKE :like");
        } else {
            sql.append("SELECT path,value,ovalue FROM jsondb A INNER JOIN (");
            SqlExpressionBuilder.create(this, o.filter(), baseDBPath).build(sql, binds);
            sql.append(") B ON A.path LIKE B.match_path||'%'");
        }
        if (o.startAfter() != null) {
            String startAfter = validateKey(o.startAfter());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path <= :startAfter");
                binds.add(query -> {
                    String bindPath = baseDBPath + startAfter;
                    query.bind("startAfter", bindPath);
                });
            } else {
                sql.append(" and path >= :startAfter");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(startAfter);
                    query.bind("startAfter", bindPath);
                });
            }
        }
        if (o.startAt() != null) {
            String startAt = validateKey(o.startAt());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path < :startAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(startAt);
                    query.bind("startAt", bindPath);
                });
            } else {
                sql.append(" and path >= :startAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + startAt;
                    query.bind("startAt", bindPath);
                });
            }
        }
        if (o.endAt() != null) {
            String endAt = validateKey(o.endAt());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path > :endAt");
                binds.add(query -> {
                    String value = baseDBPath + endAt;
                    query.bind("endAt", value);
                });
            } else {
                sql.append(" and path < :endAt");
                binds.add(query -> {
                    String bindPath = baseDBPath + incrementKey(endAt);
                    query.bind("endAt", bindPath);
                });
            }
        }
        if (o.endBefore() != null) {
            String endBefore = validateKey(o.endBefore());
            if (o.order() == GetOptions.Order.DESC) {
                sql.append(" and path >= :endBefore");
                binds.add(query -> {
                    String value = baseDBPath + incrementKey(endBefore);
                    query.bind("endBefore", value);
                });
            } else {
                sql.append(" and path < :endBefore");
                binds.add(query -> {
                    String value = baseDBPath + endBefore;
                    query.bind("endBefore", value);
                });
            }
        }
        sql.append(" order by path ").append(order);
        Query<Map<String, Object>> query = h.createQuery(sql.toString()).bind("like", like);
        for (Consumer<Query<Map<String, Object>>> bind : binds) {
            bind.accept(query);
        }
        ResultIterator<JsonRecord> iterator = query.map(JsonRecordMapper.INSTANCE).iterator();
        try {
            // At this point we know if we can produce results..
            if (iterator.hasNext()) {
                result = output -> {
                    try (JsonRecordConsumer toJson = new JsonRecordConsumer(baseDBPath, output, o)) {
                        while (!toJson.isClosed() && iterator.hasNext()) {
                            toJson.accept(iterator.next());
                        }
                    } catch (IOException e) {
                        throw new JsonDBException(e);
                    } finally {
                        iterator.close();
                        h.close();
                    }
                };
            }
        } finally {
            // if we are producing results, then defer closing the iterator
            if (result == null) {
                iterator.close();
            }
        }
    } finally {
        // if we are producing results, then defer closing the handle
        if (result == null) {
            h.close();
        }
    }
    return result;
}
Also used : Query(org.skife.jdbi.v2.Query) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) JsonDBException(io.syndesis.server.jsondb.JsonDBException) IOException(java.io.IOException) GetOptions(io.syndesis.server.jsondb.GetOptions) Handle(org.skife.jdbi.v2.Handle) Consumer(java.util.function.Consumer) Map(java.util.Map)

Example 8 with Bind

use of org.skife.jdbi.v2.sqlobject.Bind in project SpinalTap by airbnb.

the class MysqlSchemaDatabase method fetchTableSchema.

Map<String, MysqlTableSchema> fetchTableSchema(@NotNull final String database) {
    List<ColumnInfo> allColumnInfo;
    try (Handle handle = jdbi.open()) {
        disableForeignKeyChecks(handle);
        allColumnInfo = MysqlSchemaUtil.LIST_COLUMNINFO_RETRYER.call(() -> handle.createQuery(ALL_TABLE_SCHEMA_QUERY).bind("db", getSchemaDatabaseName(source, database)).map(MysqlSchemaUtil.COLUMN_MAPPER).list());
    } catch (Exception ex) {
        log.error(String.format("Failed to fetch schema for database: %s", database), ex);
        Throwables.throwIfUnchecked(ex);
        throw new RuntimeException(ex);
    }
    Map<String, MysqlTableSchema> allTableSchemaMap = Maps.newHashMap();
    allColumnInfo.forEach(columnInfo -> {
        String table = columnInfo.getTable();
        allTableSchemaMap.computeIfAbsent(table, __ -> MysqlSchemaUtil.createTableSchema(source, database, table, "", Lists.newArrayList())).getColumnInfo().add(columnInfo);
    });
    return allTableSchemaMap;
}
Also used : Handle(org.skife.jdbi.v2.Handle)

Example 9 with Bind

use of org.skife.jdbi.v2.sqlobject.Bind in project SpinalTap by airbnb.

the class MysqlSchemaStore method get.

@Override
public MysqlTableSchema get(@NotNull final String database, @NotNull final String table, final int version) {
    try (Handle handle = jdbi.open()) {
        String schemaInfo = MysqlSchemaUtil.STRING_RETRYER.call(() -> handle.createQuery(String.format(GET_SCHEMA_BY_VERSION_QUERY, source)).bind("database", database).bind("table", table).bind("version", version).map(StringColumnMapper.INSTANCE).first());
        metrics.schemaStoreGetSuccess(database, table);
        return deserializeSchemaInfo(schemaInfo);
    } catch (Exception ex) {
        log.error(String.format("Failed to get schema of database: %s table: %s version: %d. Does it exist?", database, table, version), ex);
        metrics.schemaStoreGetFailure(database, table, ex);
        Throwables.throwIfUnchecked(ex);
        throw new RuntimeException(ex);
    }
}
Also used : Handle(org.skife.jdbi.v2.Handle)

Example 10 with Bind

use of org.skife.jdbi.v2.sqlobject.Bind in project killbill by killbill.

the class EntitySqlDaoWrapperInvocationHandler method retrieveEntityIdsFromArguments.

private List<String> retrieveEntityIdsFromArguments(final Method method, final Object[] args) {
    final Annotation[][] parameterAnnotations = getAnnotations(method);
    int i = -1;
    for (final Object arg : args) {
        i++;
        // This is true for e.g. create calls
        if (arg instanceof Entity) {
            return ImmutableList.<String>of(((Entity) arg).getId().toString());
        }
        // For Batch calls, the first argument will be of type List<Entity>
        if (arg instanceof Iterable) {
            final Builder<String> entityIds = extractEntityIdsFromBatchArgument((Iterable) arg);
            if (entityIds != null) {
                return entityIds.build();
            }
        }
        for (final Annotation annotation : parameterAnnotations[i]) {
            if (arg instanceof String && Bind.class.equals(annotation.annotationType()) && ("id").equals(((Bind) annotation).value())) {
                return ImmutableList.<String>of((String) arg);
            } else if (arg instanceof Collection && BindIn.class.equals(annotation.annotationType()) && ("ids").equals(((BindIn) annotation).value())) {
                return ImmutableList.<String>copyOf((Collection) arg);
            }
        }
    }
    return ImmutableList.<String>of();
}
Also used : Entity(org.killbill.billing.util.entity.Entity) Bind(org.skife.jdbi.v2.sqlobject.Bind) BindIn(org.skife.jdbi.v2.unstable.BindIn) Collection(java.util.Collection) Annotation(java.lang.annotation.Annotation)

Aggregations

Handle (org.skife.jdbi.v2.Handle)23 IOException (java.io.IOException)12 SQLException (java.sql.SQLException)7 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 List (java.util.List)6 DataSegment (org.apache.druid.timeline.DataSegment)5 CallbackFailedException (org.skife.jdbi.v2.exceptions.CallbackFailedException)5 Test (org.junit.Test)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ImmutableList (com.google.common.collect.ImmutableList)3 ResultSet (java.sql.ResultSet)3 Interval (org.joda.time.Interval)3 DBI (org.skife.jdbi.v2.DBI)3 IDBI (org.skife.jdbi.v2.IDBI)3 Query (org.skife.jdbi.v2.Query)3 StatementContext (org.skife.jdbi.v2.StatementContext)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 AbstractModule (com.google.inject.AbstractModule)2