Search in sources :

Example 1 with QueryInfo

use of com.rdbcache.queries.QueryInfo in project rdbcache by rdbcache.

the class Request method processOptions.

private static QueryInfo processOptions(Context context, KeyInfo keyInfo, Map<String, String[]> params, Optional<String> opt1, Optional<String> opt2) {
    // {expire, table}
    String[] opts = { null, null };
    if (opt1 != null && opt1.isPresent()) {
        assignOption(context, opt1.get(), opts);
    }
    if (opt2 != null && opt2.isPresent()) {
        assignOption(context, opt2.get(), opts);
    }
    QueryInfo queryInfo = null;
    if (keyInfo.getIsNew()) {
        if (opts[1] != null) {
            keyInfo.setTable(opts[1]);
        }
        if (opts[0] != null) {
            keyInfo.setExpire(opts[0]);
        }
        if (params != null && params.size() > 0) {
            queryInfo = new QueryInfo(keyInfo.getTable(), params);
            keyInfo.setQuery(queryInfo);
        }
    } else {
        if (opts[0] != null && !opts[0].equals(keyInfo.getExpire())) {
            keyInfo.setExpire(opts[0]);
            keyInfo.setIsNew(true);
        }
        if (opts[1] != null && !opts[1].equals(keyInfo.getTable())) {
            throw new BadRequestException(context, "can not change table name for an existing key");
        }
        if (params != null && params.size() > 0) {
            queryInfo = new QueryInfo(keyInfo.getTable(), params);
            if (keyInfo.getQueryKey() == null || !keyInfo.getQueryKey().equals(queryInfo.getKey())) {
                throw new BadRequestException(context, "can not modify condition for an existing key");
            }
        }
    }
    return queryInfo;
}
Also used : BadRequestException(com.rdbcache.exceptions.BadRequestException) QueryInfo(com.rdbcache.queries.QueryInfo)

Example 2 with QueryInfo

use of com.rdbcache.queries.QueryInfo in project rdbcache by rdbcache.

the class DbaseRepoImpl method kvFind.

private boolean kvFind(Context context, KvPairs pairs, AnyKey anyKey) {
    LOGGER.trace("kvFind: " + pairs.printKey() + anyKey.print());
    KeyInfo keyInfo = anyKey.getKeyInfo();
    if (pairs.size() == 1) {
        KvPair pair = pairs.getPair();
        String key = pair.getId();
        StopWatch stopWatch = context.startStopWatch("dbase", "kvPairRepo.findOne");
        Optional<KvPair> opt = AppCtx.getKvPairRepo().findById(new KvIdType(key, "data"));
        if (stopWatch != null)
            stopWatch.stopNow();
        if (!opt.isPresent()) {
            LOGGER.trace("kvFind: not found from default table for " + key);
            return false;
        }
        KvPair dbPair = opt.get();
        setUseDefaultTable(keyInfo);
        pair.setData(dbPair.getData());
        LOGGER.trace("kvFind(1) Ok - found from default table for " + key);
        return true;
    } else {
        QueryInfo queryInfo = keyInfo.getQuery();
        if (queryInfo == null) {
            // no queryKey means no query
            return false;
        }
        Map<String, Condition> conditions = queryInfo.getConditions();
        if (// must have condtion
        conditions == null || // only 1 condition allowed
        conditions.size() != 1 || !conditions.containsKey("key")) {
            // only condition with key allowed
            return false;
        }
        Condition condition = conditions.get("key");
        if (// must have condition
        condition == null || // only 1 condition
        condition.size() != 1 || !condition.containsKey("=")) {
            // only = allowed
            return false;
        }
        List<String> keys = condition.get("=");
        if (keys == null || keys.size() == 0) {
            return false;
        }
        List<KvIdType> idTypes = new ArrayList<KvIdType>();
        for (String key : keys) {
            KvIdType idType = new KvIdType(key, "data");
            idTypes.add(idType);
        }
        StopWatch stopWatch = context.startStopWatch("dbase", "kvPairRepo.findAll");
        Iterable<KvPair> dbPairs = AppCtx.getKvPairRepo().findAllById(idTypes);
        if (stopWatch != null)
            stopWatch.stopNow();
        if (dbPairs == null && !dbPairs.iterator().hasNext()) {
            LOGGER.trace("kvFind(" + anyKey.size() + ") failed to find from default table");
            return false;
        }
        if (queryInfo != null) {
            keyInfo.setQuery(null);
            Utils.getExcutorService().submit(() -> {
                Thread.yield();
                AppCtx.getDbaseOps().saveQuery(context, queryInfo);
            });
        }
        anyKey.clear();
        int i = 0;
        for (KvPair dbPair : dbPairs) {
            pairs.add(dbPair);
            anyKey.getAny(i++);
        }
        LOGGER.trace("kvFind(" + anyKey.size() + ") Ok - found from default table");
        return true;
    }
}
Also used : Condition(com.rdbcache.queries.Condition) QueryInfo(com.rdbcache.queries.QueryInfo)

Example 3 with QueryInfo

use of com.rdbcache.queries.QueryInfo in project rdbcache by rdbcache.

the class KeyInfoTest method objectToMap4.

@Test
public void objectToMap4() {
    Map<String, Object> map1 = Utils.toMap("{\"expire\":\"30\",\"table\":\"user_table\",\"clause\":" + "\"id = ?\",\"params\":[12466],\"query\":{\"table\":\"user_table\",\"conditions\":{\"id\":" + "{\"=\":[\"12466\"]}}},\"query_key\":\"28f0a2d90b3c9d340e853b838d27845c\",\"is_new\":" + "false,\"expire_old\":\"180\",\"created_at\":1522367412704}");
    KeyInfo keyInfo1 = Utils.toPojo(map1, KeyInfo.class);
    QueryInfo queryInfo = new QueryInfo("user_table");
    String[] params = { "12466" };
    Condition condition = new Condition("=", params);
    Map<String, Condition> conditions = new LinkedHashMap<>();
    conditions.put("id", condition);
    queryInfo.setConditions(conditions);
    keyInfo1.setQuery(queryInfo);
    Map<String, Object> map2 = Utils.toMap(keyInfo1);
    KeyInfo keyInfo2 = Utils.toPojo(map2, KeyInfo.class);
    // System.out.println(Utils.toJsonMap(map2));
    assertEquals(keyInfo1, keyInfo2);
    assertEquals(map1, map2);
}
Also used : Condition(com.rdbcache.queries.Condition) QueryInfo(com.rdbcache.queries.QueryInfo) Test(org.junit.Test)

Example 4 with QueryInfo

use of com.rdbcache.queries.QueryInfo in project rdbcache by rdbcache.

the class RdbcacheApis method select_post.

/**
 * select_post post multiple items
 *
 * To select one or more entries based on query string.
 * It queries database and return immediately, and asynchronously saves the data to redis
 *
 * @param request HttpServletRequest
 * @param opt1 String, can be expire or table
 * @param opt2 String, can be expire or table, but not otp1
 * @param keys List, list of keys for returned entries
 * @return ResponseEntity
 */
@RequestMapping(value = { "/rdbcache/v1/select", "/rdbcache/v1/select/{opt1}", "/rdbcache/v1/select/{opt1}/{opt2}" }, method = RequestMethod.POST)
public ResponseEntity<?> select_post(HttpServletRequest request, @PathVariable Optional<String> opt1, @PathVariable Optional<String> opt2, @RequestBody ArrayList<String> keys) {
    Context context = new Context(true, true);
    KvPairs pairs = new KvPairs(keys);
    AnyKey anyKey = Request.process(context, request, pairs, opt1, opt2);
    LOGGER.trace(anyKey.print() + " pairs(" + pairs.size() + "): " + pairs.printKey());
    KeyInfo keyInfo = anyKey.getKeyInfo();
    if (keyInfo.getQuery() == null && pairs.size() == 0) {
        QueryInfo query = new QueryInfo(keyInfo.getTable());
        query.setLimit(1024);
        keyInfo.setQuery(query);
        String msg = "no query string found, max rows limit is forced to 1024";
        LOGGER.info(msg);
        context.logTraceMessage(msg);
    }
    if (!AppCtx.getDbaseRepo().find(context, pairs, anyKey)) {
        LOGGER.debug("no record(s) found from database");
    } else {
        AppCtx.getAsyncOps().doSaveToRedis(context, pairs, anyKey);
    }
    return Response.send(context, pairs);
}
Also used : KeyInfo(com.rdbcache.models.KeyInfo) QueryInfo(com.rdbcache.queries.QueryInfo)

Example 5 with QueryInfo

use of com.rdbcache.queries.QueryInfo in project rdbcache by rdbcache.

the class RdbcacheApis method select_get.

/**
 * select_get get multiple items
 *
 * To select one or more entries based on query string.
 * It queries database and return immediately, and asynchronously saves the data to redis
 *
 * @param request HttpServletRequest
 * @param opt1 String, can be expire or table
 * @param opt2 String, can be expire or table, but not otp1
 * @return ResponseEntity
 */
@RequestMapping(value = { "/rdbcache/v1/select", "/rdbcache/v1/select/{opt1}", "/rdbcache/v1/select/{opt1}/{opt2}" }, method = RequestMethod.GET)
public ResponseEntity<?> select_get(HttpServletRequest request, @PathVariable Optional<String> opt1, @PathVariable Optional<String> opt2) {
    Context context = new Context(true, true);
    KvPairs pairs = new KvPairs();
    AnyKey anyKey = Request.process(context, request, pairs, opt1, opt2);
    LOGGER.trace(anyKey.print() + " pairs(" + pairs.size() + "): " + pairs.printKey());
    KeyInfo keyInfo = anyKey.getKeyInfo();
    if (keyInfo.getQuery() == null && pairs.size() == 0) {
        QueryInfo query = new QueryInfo(keyInfo.getTable());
        query.setLimit(1024);
        keyInfo.setQuery(query);
        String msg = "no query string found, max rows limit is forced to 1024";
        LOGGER.info(msg);
        context.logTraceMessage(msg);
    }
    if (!AppCtx.getDbaseRepo().find(context, pairs, anyKey)) {
        LOGGER.debug("no record(s) found from database");
    } else {
        AppCtx.getAsyncOps().doSaveToRedis(context, pairs, anyKey);
    }
    return Response.send(context, pairs);
}
Also used : KeyInfo(com.rdbcache.models.KeyInfo) QueryInfo(com.rdbcache.queries.QueryInfo)

Aggregations

QueryInfo (com.rdbcache.queries.QueryInfo)5 KeyInfo (com.rdbcache.models.KeyInfo)2 Condition (com.rdbcache.queries.Condition)2 BadRequestException (com.rdbcache.exceptions.BadRequestException)1 Test (org.junit.Test)1