Search in sources :

Example 1 with FlyingModel

use of indi.mybatis.flying.models.FlyingModel in project mybatis.flying by limeng32.

the class CookOriginalSql method fetchFlyingFeature.

public static FlyingModel fetchFlyingFeature(String originalSql) {
    if (flyingModelCache.get(originalSql) != null) {
        return flyingModelCache.get(originalSql);
    }
    FlyingModel ret = new FlyingModel();
    String extension = null;
    if (null != originalSql && originalSql.startsWith(FLYING) && originalSql.indexOf(':') > -1) {
        String dataSourceIdAndConnectionCatalog = null;
        String s1 = null;
        if ((originalSql.startsWith(FLYING_LEFTBRACKET) || originalSql.startsWith(FLYING_QUESTIONMARK_LEFTBRACKET)) && originalSql.indexOf(')') > 0) {
            String s0 = originalSql.substring(0, originalSql.indexOf(')') + 1);
            dataSourceIdAndConnectionCatalog = s0.substring(s0.indexOf('(') + 1, s0.lastIndexOf(')'));
            s1 = originalSql.substring(0, originalSql.indexOf(':', originalSql.indexOf(')')));
        } else {
            s1 = originalSql.substring(0, originalSql.indexOf(':'));
        }
        if (FLYING.equals(s1) || FLYING_QUESTIONMARK.equals(s1) || s1.startsWith(FLYING_LEFTBRACKET) || originalSql.startsWith(FLYING_QUESTIONMARK_LEFTBRACKET)) {
            String s2 = null;
            if (s1.startsWith(FLYING_LEFTBRACKET) || originalSql.startsWith(FLYING_QUESTIONMARK_LEFTBRACKET)) {
                s2 = originalSql.substring(originalSql.indexOf(":", originalSql.indexOf(')')) + 1, originalSql.length());
            } else {
                s2 = originalSql.substring(originalSql.indexOf(':') + 1, originalSql.length());
            }
            String actionTypeStr = null;
            if (s2.indexOf(':') > -1) {
                actionTypeStr = s2.substring(0, s2.indexOf(':'));
            } else {
                actionTypeStr = s2;
            }
            if (actionTypeStr.endsWith(")") && actionTypeStr.indexOf('(') != -1) {
                extension = actionTypeStr.substring(actionTypeStr.lastIndexOf('(') + 1, actionTypeStr.length() - 1);
                actionTypeStr = actionTypeStr.substring(0, actionTypeStr.lastIndexOf('('));
            }
            ActionType actionType = ActionType.valueOf(actionTypeStr);
            if (actionType != null) {
                ret.setHasFlyingFeature(true);
                if (dataSourceIdAndConnectionCatalog != null && dataSourceIdAndConnectionCatalog.indexOf(':') != -1) {
                    ret.setDataSourceId(dataSourceIdAndConnectionCatalog.substring(0, dataSourceIdAndConnectionCatalog.indexOf(':')));
                    ret.setConnectionCatalog(dataSourceIdAndConnectionCatalog.substring(dataSourceIdAndConnectionCatalog.indexOf(':') + 1, dataSourceIdAndConnectionCatalog.length()));
                }
                ret.setActionType(actionType);
                if (s2.indexOf(':') > -1) {
                    String s3 = s2.substring(s2.indexOf(':') + 1, s2.length());
                    String ignoreTag = null;
                    if (s3.indexOf(':') > -1) {
                        ignoreTag = s3.substring(0, s3.indexOf(':'));
                    } else {
                        ignoreTag = s3;
                    }
                    ret.setIgnoreTag(ignoreTag);
                }
                if (ActionType.insert.equals(actionType) && extension != null) {
                    KeyGeneratorType keyGeneratorType = null;
                    if (extension.indexOf(".") == -1) {
                        try {
                            keyGeneratorType = KeyGeneratorType.valueOf(extension);
                        } catch (IllegalArgumentException e) {
                            logger.error(new StringBuffer(AutoMapperExceptionEnum.wrongKeyGeneratorType.description()).append(originalSql).append(" because of ").append(e).toString());
                        }
                        ret.setKeyGeneratorType(keyGeneratorType);
                        if (keyGeneratorType != null) {
                            KeyHandler keyHandler;
                            switch(keyGeneratorType) {
                                case uuid:
                                    keyHandler = UuidKeyHandler.getInstance();
                                    break;
                                case uuid_no_line:
                                    keyHandler = UuidWithoutLineKeyHandler.getInstance();
                                    break;
                                case millisecond:
                                    keyHandler = MilliSecondKeyHandler.getInstance();
                                    break;
                                case snowflake:
                                    keyHandler = SnowFlakeKeyHandler.getInstance();
                                    break;
                                default:
                                    keyHandler = null;
                                    break;
                            }
                            ret.setKeyHandler(keyHandler);
                        }
                    } else {
                        try {
                            @SuppressWarnings("unchecked") Class<? extends KeyHandler> clazz = (Class<? extends KeyHandler>) Class.forName(extension);
                            ret.setKeyGeneratorType(KeyGeneratorType.custom);
                            ret.setKeyHandler(clazz.newInstance());
                        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                            logger.error(new StringBuffer(AutoMapperExceptionEnum.wrongCustomKeyGenerator.description()).append(originalSql).append(" because of ").append(e).toString());
                        }
                    }
                }
                flyingModelCache.put(originalSql, ret);
                return ret;
            }
        }
    }
    ret.setHasFlyingFeature(false);
    flyingModelCache.put(originalSql, ret);
    return ret;
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) ActionType(indi.mybatis.flying.statics.ActionType) KeyGeneratorType(indi.mybatis.flying.statics.KeyGeneratorType) UuidKeyHandler(indi.mybatis.flying.handlers.UuidKeyHandler) SnowFlakeKeyHandler(indi.mybatis.flying.handlers.SnowFlakeKeyHandler) MilliSecondKeyHandler(indi.mybatis.flying.handlers.MilliSecondKeyHandler) UuidWithoutLineKeyHandler(indi.mybatis.flying.handlers.UuidWithoutLineKeyHandler) KeyHandler(indi.mybatis.flying.type.KeyHandler)

Example 2 with FlyingModel

use of indi.mybatis.flying.models.FlyingModel in project mybatis.flying by limeng32.

the class FlyingManager method fetchFlyingFeatureNew.

public static FlyingModel fetchFlyingFeatureNew(String originalSql, Configuration configuration, MappedStatement mappedStatement) {
    String id = mappedStatement.getId();
    if (flyingModelCache.get(id) != null) {
        return flyingModelCache.get(id);
    }
    // 在CookOriginalSql中采用迭代的方式获取configuration中其它的元素的引用
    FlyingModel ret = new FlyingModel();
    try {
        JSONObject json = JSONObject.parseObject(originalSql);
        buildFlyingModel(ret, json, originalSql, id, true, null, null);
        dealInnerPropertiesIteration(id, json, configuration, ret);
        flyingModelCache.put(id, ret);
        return ret;
    } catch (Exception e) {
        // make sonar happy
        return fetchFlyingFeature(originalSql, id);
    }
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) JSONObject(com.alibaba.fastjson.JSONObject)

Example 3 with FlyingModel

use of indi.mybatis.flying.models.FlyingModel in project mybatis.flying by limeng32.

the class AutoMapperInterceptor method intercept.

@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    MetaObject metaStatementHandler = getRealObj(statementHandler);
    String originalSql = (String) metaStatementHandler.getValue(DELEGATE_BOUNDSQL_SQL);
    Configuration configuration = (Configuration) metaStatementHandler.getValue(DELEGATE_CONFIGURATION);
    Object parameterObject = metaStatementHandler.getValue(DELEGATE_BOUNDSQL_PARAMETEROBJECT);
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue(DELEGATE_MAPPEDSTATEMENT);
    FlyingModel flyingModel = FlyingManager.fetchFlyingFeatureNew(originalSql, configuration, mappedStatement);
    if (flyingModel.isHasFlyingFeature()) {
        boolean needHandleLimiterAndSorter = false;
        String newSql = null;
        switch(flyingModel.getActionType()) {
            case COUNT:
                newSql = SqlBuilder.buildCountSql(parameterObject, flyingModel);
                break;
            case DELETE:
                newSql = SqlBuilder.buildDeleteSql(parameterObject);
                break;
            case INSERT:
                newSql = SqlBuilder.buildInsertSql(parameterObject, flyingModel);
                break;
            case INSERT_BATCH:
                newSql = SqlBuilder.buildInsertBatchSql(parameterObject, flyingModel);
                break;
            case SELECT:
                newSql = SqlBuilder.buildSelectSql(mappedStatement.getResultMaps().get(0).getType(), flyingModel);
                break;
            case SELECT_ALL:
                newSql = SqlBuilder.buildSelectAllSql(parameterObject, flyingModel);
                needHandleLimiterAndSorter = true;
                break;
            case SELECT_ONE:
                newSql = SqlBuilder.buildSelectOneSql(parameterObject, flyingModel);
                needHandleLimiterAndSorter = true;
                break;
            case UPDATE:
                newSql = SqlBuilder.buildUpdateSql(parameterObject, flyingModel);
                break;
            case UPDATE_BATCH:
                newSql = SqlBuilder.buildUpdateBatchSql(parameterObject, flyingModel);
                break;
            case UPDATE_PERSISTENT:
                newSql = SqlBuilder.buildUpdatePersistentSql(parameterObject, flyingModel);
                break;
            default:
                break;
        }
        if (!LogLevel.NONE.equals(logLevel)) {
            log(logger, logLevel, new StringBuilder("Auto generated sql: ").append(newSql).toString());
        }
        SqlSource sqlSource = buildSqlSource(configuration, newSql, parameterObject.getClass());
        List<ParameterMapping> parameterMappings = sqlSource.getBoundSql(parameterObject).getParameterMappings();
        String sqlToexecute = sqlSource.getBoundSql(parameterObject).getSql();
        metaStatementHandler.setValue(DELEGATE_BOUNDSQL_SQL, sqlToexecute);
        metaStatementHandler.setValue(DELEGATE_BOUNDSQL_PARAMETERMAPPINGS, parameterMappings);
        /* Start dealing with paging */
        if (needHandleLimiterAndSorter && (parameterObject instanceof Conditionable) && (invocation.getTarget() instanceof RoutingStatementHandler)) {
            Conditionable condition = (Conditionable) parameterObject;
            if (condition.getLimiter() != null) {
                BoundSql boundSql = statementHandler.getBoundSql();
                // The total count needs to be identified when encountering "selectAll"
                if (ActionType.SELECT_ALL.equals(flyingModel.getActionType())) {
                    Connection connection = (Connection) invocation.getArgs()[0];
                    String countSql = new StringBuilder("select count(0) from (").append(sqlToexecute).append(") myCount").toString();
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
                    setParameters(countStmt, mappedStatement, countBS, parameterObject);
                    ResultSet rs = countStmt.executeQuery();
                    try {
                        int count = 0;
                        if (rs.next()) {
                            count = rs.getInt(1);
                        }
                        condition.getLimiter().setTotalCount(count);
                    } finally {
                        rs.close();
                        countStmt.close();
                    }
                }
                sqlToexecute = generatePageSql(sqlToexecute, condition);
                metaStatementHandler.setValue(DELEGATE_BOUNDSQL_SQL, sqlToexecute);
            } else if (condition.getSorter() != null) {
                BoundSql boundSql = statementHandler.getBoundSql();
                String sql = boundSql.getSql();
                sqlToexecute = generatePageSql(sql, condition);
                metaStatementHandler.setValue(DELEGATE_BOUNDSQL_SQL, sqlToexecute);
            }
        }
        if (loggerDescriptionHandler != null) {
            LogLevel loggerLevel = loggerDescriptionHandler.getLogLevel(flyingModel.getId());
            if (!LogLevel.NONE.equals(loggerLevel)) {
                BoundSql boundSqlTemp = statementHandler.getBoundSql();
                String sqlTemp = boundSqlTemp.getSql();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("Method: ").append(flyingModel.getId()).append("\r\n");
                stringBuilder.append("Bound sql: ").append(sqlTemp).append("\r\n");
                if (ActionType.SELECT.equals(flyingModel.getActionType())) {
                    stringBuilder.append("Bound value: {").append(parameterMappings.get(0).getProperty()).append("=").append(parameterObject).append("};");
                } else {
                    MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
                    stringBuilder.append("Bound value: {");
                    boolean b = true;
                    for (ParameterMapping parameterMapping : parameterMappings) {
                        if (parameterMapping.getMode() != ParameterMode.OUT) {
                            Object value;
                            String propertyName = parameterMapping.getProperty();
                            value = metaObject == null ? null : metaObject.getValue(propertyName);
                            if (b) {
                                b = false;
                            } else {
                                stringBuilder.append(", ");
                            }
                            stringBuilder.append(propertyName).append("=").append(value);
                        }
                    }
                    stringBuilder.append("};");
                }
                log(logger, loggerLevel, stringBuilder.toString());
            }
        }
    } else if (loggerDescriptionHandler != null) {
        LogLevel loggerLevel = loggerDescriptionHandler.getLogLevel(mappedStatement.getId());
        if (!LogLevel.NONE.equals(loggerLevel)) {
            String sqlTemp = statementHandler.getBoundSql().getSql();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Method: ").append(mappedStatement.getId()).append("\r\n");
            stringBuilder.append("Bound sql: ").append(sqlTemp).append("\r\n");
            stringBuilder.append("Bound value: ").append(parameterObject).append(";");
            log(logger, loggerLevel, stringBuilder.toString());
        }
    }
    /* Pass to the next interceptor. */
    return invocation.proceed();
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) Conditionable(indi.mybatis.flying.models.Conditionable) SqlSource(org.apache.ibatis.mapping.SqlSource) Configuration(org.apache.ibatis.session.Configuration) MetaObject(org.apache.ibatis.reflection.MetaObject) RoutingStatementHandler(org.apache.ibatis.executor.statement.RoutingStatementHandler) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) LogLevel(indi.mybatis.flying.utils.LogLevel) ParameterMapping(org.apache.ibatis.mapping.ParameterMapping) BoundSql(org.apache.ibatis.mapping.BoundSql) StatementHandler(org.apache.ibatis.executor.statement.StatementHandler) RoutingStatementHandler(org.apache.ibatis.executor.statement.RoutingStatementHandler) ResultSet(java.sql.ResultSet) MetaObject(org.apache.ibatis.reflection.MetaObject) MappedStatement(org.apache.ibatis.mapping.MappedStatement)

Example 4 with FlyingModel

use of indi.mybatis.flying.models.FlyingModel in project mybatis.flying by limeng32.

the class PrefixTest method testSelect.

@Test
@DatabaseSetup(connection = "dataSource1", type = DatabaseOperation.CLEAN_INSERT, value = "/indi/mybatis/flying/test/prefixTest/testSelect.xml")
@ExpectedDatabase(connection = "dataSource1", override = false, assertionMode = DatabaseAssertionMode.NON_STRICT, value = "/indi/mybatis/flying/test/prefixTest/testSelect.result.xml")
@DatabaseTearDown(connection = "dataSource1", type = DatabaseOperation.DELETE_ALL, value = "/indi/mybatis/flying/test/prefixTest/testSelect.result.xml")
public void testSelect() {
    Map<String, String> map = new HashMap<>();
    map.put("id", "1");
    Account_ account = accountService.selectAsd(1);
    Assert.assertTrue(account.getActivated());
    Assert.assertEquals("bob", account.getName());
    Assert.assertEquals("bob@live.cn_", account.getEmail());
    Assert.assertNull(account.getPassword());
    Assert.assertEquals("a111", account.getActivateValue());
    Assert.assertEquals(11, account.getOpLock().intValue());
    Account_ ac = new Account_();
    ac.setName("carl");
    Permission pc = new Permission();
    pc.setName("carl");
    ac.setPermission(pc);
    Collection<Account_> accountC = accountService.selectAllPrefix(ac);
    System.out.println(JSONObject.toJSONString(accountC));
    Account_[] accounts = accountC.toArray(new Account_[accountC.size()]);
    Assert.assertEquals(3, accounts[0].getId().intValue());
    Assert.assertEquals(23, accounts[0].getPermission().getFakeId().intValue());
    Assert.assertEquals(3, accounts[0].getPermission().getId().intValue());
    Assert.assertEquals("carl", accounts[0].getPermission().getName());
    Assert.assertEquals(13, accounts[0].getRole().getId().intValue());
    Assert.assertEquals("role3", accounts[0].getRole().getName());
    Assert.assertEquals(113, accounts[0].getRoleDeputy().getId().intValue());
    Assert.assertEquals("roleDeputy3", accounts[0].getRoleDeputy().getName());
    Assert.assertEquals(4, accounts[1].getId().intValue());
    Assert.assertEquals(24, accounts[1].getPermission().getFakeId().intValue());
    Assert.assertEquals(4, accounts[1].getPermission().getId().intValue());
    Assert.assertEquals("carl", accounts[1].getPermission().getName());
    Assert.assertEquals(14, accounts[1].getRole().getId().intValue());
    Assert.assertEquals("role4", accounts[1].getRole().getName());
    Assert.assertEquals(114, accounts[1].getRoleDeputy().getId().intValue());
    Assert.assertEquals("roleDeputy4", accounts[1].getRoleDeputy().getName());
    accountMapper.selectGroupBy(new Account_());
    int c = accountService.countAsd(ac);
    Assert.assertEquals(2, c);
    FlyingModel fm = FlyingManager.getFlyingModelFromCache("indi.mybatis.flying.mapper.AccountMapper.selectAllPrefix");
    System.out.println("fm::" + JSONObject.toJSONString(fm));
    Assert.assertEquals("noPassword", fm.getIgnoreTag());
    Assert.assertEquals("use index(index1)", fm.getIndex());
    Assert.assertNull(fm.getPrefix());
    FlyingModel fm1 = fm.getProperties().get("permission");
    Assert.assertNull(fm1.getIgnoreTag());
    Assert.assertNull(fm1.getIndex());
    Assert.assertEquals("permission__", fm1.getPrefix());
    Assert.assertEquals("indi.mybatis.flying.mapper.PermissionMapper.select", fm1.getId());
    FlyingModel fm2 = fm.getProperties().get("role");
    Assert.assertNull(fm2.getIndex());
    Assert.assertEquals("indi.mybatis.flying.mapper.RoleMapper.select", fm2.getId());
    Assert.assertEquals("role__", fm2.getPrefix());
    FlyingModel fm3 = fm.getProperties().get("roleDeputy");
    Assert.assertNull(fm3.getIndex());
    Assert.assertEquals("roleDeputy__", fm3.getPrefix());
    FlyingModel fm10 = FlyingManager.getFlyingModelFromCache("indi.mybatis.flying.mapper.AccountMapper.selectGroupBy");
    Assert.assertNotNull(fm10);
    System.out.println("fm10::" + JSONObject.toJSONString(fm10));
    Assert.assertEquals(2, fm10.getGroupBy().size());
    Assert.assertEquals(2, fm10.getAggregate().size());
    Set<AggregateModel> am = fm10.getAggregate().get("opLock");
    Assert.assertEquals(2, am.size());
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) AggregateModel(indi.mybatis.flying.models.AggregateModel) HashMap(java.util.HashMap) Permission(indi.mybatis.flying.pojo.Permission) Account_(indi.mybatis.flying.pojo.Account_) ExpectedDatabase(com.github.springtestdbunit.annotation.ExpectedDatabase) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) DatabaseSetup(com.github.springtestdbunit.annotation.DatabaseSetup) DatabaseTearDown(com.github.springtestdbunit.annotation.DatabaseTearDown)

Example 5 with FlyingModel

use of indi.mybatis.flying.models.FlyingModel in project mybatis.flying by limeng32.

the class CookOriginalSqlTest method testCook4.

@Test
public void testCook4() {
    String sql = "flying(datasource1:testdb):insert(uuid):noPassword";
    FlyingModel flyingModel = fetchFlyingFeature(sql);
    Assert.assertTrue(flyingModel.isHasFlyingFeature());
    Assert.assertEquals(ActionType.INSERT, flyingModel.getActionType());
    Assert.assertEquals("noPassword", flyingModel.getIgnoreTag());
    Assert.assertEquals(KeyGeneratorType.UUID, flyingModel.getKeyGeneratorType());
    String sql2 = "flying?(datasource2):select:noPassword";
    FlyingModel flyingModel2 = fetchFlyingFeature(sql2);
    Assert.assertTrue(flyingModel2.isHasFlyingFeature());
    Assert.assertEquals(ActionType.SELECT, flyingModel2.getActionType());
    Assert.assertEquals("noPassword", flyingModel2.getIgnoreTag());
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) Test(org.junit.Test)

Aggregations

FlyingModel (indi.mybatis.flying.models.FlyingModel)12 Test (org.junit.Test)5 JSONObject (com.alibaba.fastjson.JSONObject)2 ActionType (indi.mybatis.flying.statics.ActionType)2 HashMap (java.util.HashMap)2 BoundSql (org.apache.ibatis.mapping.BoundSql)2 MappedStatement (org.apache.ibatis.mapping.MappedStatement)2 MetaObject (org.apache.ibatis.reflection.MetaObject)2 DatabaseSetup (com.github.springtestdbunit.annotation.DatabaseSetup)1 DatabaseTearDown (com.github.springtestdbunit.annotation.DatabaseTearDown)1 ExpectedDatabase (com.github.springtestdbunit.annotation.ExpectedDatabase)1 MilliSecondKeyHandler (indi.mybatis.flying.handlers.MilliSecondKeyHandler)1 SnowFlakeKeyHandler (indi.mybatis.flying.handlers.SnowFlakeKeyHandler)1 UuidKeyHandler (indi.mybatis.flying.handlers.UuidKeyHandler)1 UuidWithoutLineKeyHandler (indi.mybatis.flying.handlers.UuidWithoutLineKeyHandler)1 AggregateModel (indi.mybatis.flying.models.AggregateModel)1 Conditionable (indi.mybatis.flying.models.Conditionable)1 Account_ (indi.mybatis.flying.pojo.Account_)1 Permission (indi.mybatis.flying.pojo.Permission)1 KeyGeneratorType (indi.mybatis.flying.statics.KeyGeneratorType)1