Search in sources :

Example 16 with KeyInfo

use of doitincloud.rdbcache.models.KeyInfo in project rdbcache by rdbcache.

the class Query method executeInsert.

public boolean executeInsert(boolean enableLocal, boolean enableRedis) {
    params = new ArrayList<>();
    boolean allOk = true;
    for (int i = 0; i < pairs.size(); i++) {
        KvPair pair = pairs.get(i);
        KeyInfo keyInfo = anyKey.getAny(i);
        String table = keyInfo.getTable();
        Map<String, Object> map = pair.getData();
        String autoIncKey = AppCtx.getDbaseOps().getTableAutoIncColumn(context, table);
        boolean cacheUpdate = false;
        if (!map.containsKey(autoIncKey) && keyInfo.getParams() != null && keyInfo.getParams().size() == 1) {
            String stdClause = "(" + autoIncKey + " = ?)";
            if (stdClause.equals(keyInfo.getClause())) {
                map.put(autoIncKey, keyInfo.getParams().get(0));
                cacheUpdate = true;
            }
        }
        Map<String, Object> columns = keyInfo.getColumns();
        AppCtx.getDbaseOps().convertDbMap(columns, map);
        String fields = "", values = "";
        params.clear();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.add(entry.getValue());
            if (fields.length() != 0) {
                fields += ", ";
                values += ", ";
            }
            fields += entry.getKey();
            values += "?";
        }
        sql = "insert into " + table + " (" + fields + ") values (" + values + ")";
        LOGGER.trace("sql: " + sql);
        LOGGER.trace("params: " + params.toString());
        int rowCount = 0;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.update");
        try {
            rowCount = jdbcTemplate.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps;
                    ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    int i = 1;
                    for (Object param : params) {
                        ps.setObject(i++, param);
                    }
                    return ps;
                }
            }, keyHolder);
            if (stopWatch != null)
                stopWatch.stopNow();
        } catch (Exception e) {
            if (stopWatch != null)
                stopWatch.stopNow();
            allOk = false;
            String msg = e.getCause().getMessage();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
        }
        if (rowCount > 0) {
            if (autoIncKey != null && keyHolder.getKey() != null) {
                String keyValue = String.valueOf(keyHolder.getKey());
                map.put(autoIncKey, keyValue);
                cacheUpdate = true;
            }
            if (cacheUpdate) {
                if (enableLocal) {
                    AppCtx.getCacheOps().putData(pair, keyInfo);
                }
                if (enableRedis) {
                    AppCtx.getRedisRepo().save(context, new KvPairs(pair), new AnyKey(keyInfo));
                }
            }
            if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
                String msg = "executeInsert failed when prepareStandardClauseParams for " + pair.getId();
                LOGGER.error(msg);
                context.logTraceMessage(msg);
                if (context.isSync()) {
                    throw new ServerErrorException(context, msg);
                }
            }
            LOGGER.trace("inserted " + pair.getId() + " into " + table);
        } else {
            allOk = false;
            LOGGER.warn("failed to insert " + pair.getId() + " into " + table);
        }
    }
    return allOk;
}
Also used : AnyKey(doitincloud.rdbcache.supports.AnyKey) KvPair(doitincloud.rdbcache.models.KvPair) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KvPairs(doitincloud.rdbcache.supports.KvPairs) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) SQLException(java.sql.SQLException) ServerErrorException(doitincloud.commons.exceptions.ServerErrorException) StopWatch(doitincloud.rdbcache.models.StopWatch) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) KeyInfo(doitincloud.rdbcache.models.KeyInfo) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) ServerErrorException(doitincloud.commons.exceptions.ServerErrorException)

Example 17 with KeyInfo

use of doitincloud.rdbcache.models.KeyInfo in project rdbcache by rdbcache.

the class Query method waitForParamsUpdate.

// it could be the data is just inserted, not synchronized yet
// max wait for 30 seconds
private void waitForParamsUpdate(KvIdType idType, KeyInfo keyInfo) {
    if (keyInfo.hasParams()) {
        return;
    }
    for (int j = 0; j < 300; j++) {
        KeyInfo cachedKeyInfo = AppCtx.getCacheOps().getKeyInfo(idType);
        if (cachedKeyInfo.hasParams()) {
            keyInfo.setClause(cachedKeyInfo.getClause());
            keyInfo.setParams(cachedKeyInfo.getParams());
            return;
        }
        // allow time to synchronize data
        try {
            LOGGER.trace("waitForParamsUpdate 100 ms ...");
            Thread.sleep(100);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
    LOGGER.warn("failed on waitForParamsUpdate");
}
Also used : KeyInfo(doitincloud.rdbcache.models.KeyInfo)

Example 18 with KeyInfo

use of doitincloud.rdbcache.models.KeyInfo in project rdbcache by rdbcache.

the class Query method ifUpdateOk.

public boolean ifUpdateOk() {
    Assert.isTrue(anyKey.size() == pairs.size(), anyKey.size() + " != " + pairs.size() + ", update only supports anyKey size == pairs size");
    KeyInfo keyInfo = anyKey.getKeyInfo();
    String table = keyInfo.getTable();
    if (table == null) {
        return false;
    }
    String queryKey = keyInfo.getQueryKey();
    if (queryKey == null) {
        return false;
    }
    return true;
}
Also used : KeyInfo(doitincloud.rdbcache.models.KeyInfo)

Example 19 with KeyInfo

use of doitincloud.rdbcache.models.KeyInfo in project rdbcache by rdbcache.

the class UtilsTest method toPojoTest.

@Test
public void toPojoTest() {
    KeyInfo keyInfo1 = new KeyInfo();
    keyInfo1.setExpire("100");
    keyInfo1.setTable("table");
    Map<String, Object> map = Utils.toMap(keyInfo1);
    KeyInfo keyInfo2 = Utils.toPojo(map, KeyInfo.class);
    assertEquals(keyInfo1, keyInfo2);
}
Also used : KeyInfo(doitincloud.rdbcache.models.KeyInfo) Test(org.junit.Test)

Example 20 with KeyInfo

use of doitincloud.rdbcache.models.KeyInfo in project rdbcache by rdbcache.

the class UtilsTest method toMapTestWithPojo.

@Test
public void toMapTestWithPojo() {
    KeyInfo keyInfo = new KeyInfo();
    keyInfo.setExpire("100");
    keyInfo.setTable("table");
    keyInfo.cleanup();
    Map<String, Object> map = Utils.toMap(keyInfo);
    // System.out.println(Utils.toJsonMap(map));
    assertNotNull(map.get("created_at"));
    map.remove("created_at");
    String json = "{\"expire\":\"100\",\"table\":\"table\",\"clause\":\"\",\"query_key\":\"\",\"is_new\":false}";
    Map<String, Object> newMap = Utils.toMap(json);
    assertEquals(map, newMap);
}
Also used : KeyInfo(doitincloud.rdbcache.models.KeyInfo) Test(org.junit.Test)

Aggregations

KeyInfo (doitincloud.rdbcache.models.KeyInfo)50 KvPair (doitincloud.rdbcache.models.KvPair)29 AnyKey (doitincloud.rdbcache.supports.AnyKey)21 Context (doitincloud.rdbcache.supports.Context)17 KvPairs (doitincloud.rdbcache.supports.KvPairs)17 Test (org.junit.Test)13 ServerErrorException (doitincloud.commons.exceptions.ServerErrorException)9 StopWatch (doitincloud.rdbcache.models.StopWatch)8 BadRequestException (doitincloud.commons.exceptions.BadRequestException)7 SQLException (java.sql.SQLException)4 QueryInfo (doitincloud.rdbcache.queries.QueryInfo)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 MockServletContext (org.springframework.mock.web.MockServletContext)2 NotFoundException (doitincloud.commons.exceptions.NotFoundException)1 CacheOps (doitincloud.rdbcache.services.CacheOps)1 DbaseOps (doitincloud.rdbcache.services.DbaseOps)1 ExpireDbOps (doitincloud.rdbcache.supports.ExpireDbOps)1