Search in sources :

Example 1 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class EntitySqlMapListHandler method replaceStarStarToColumn.

/**
 * Replace .** to all fields, replace .## to all PKey and Fkey fields only,
 * for example:
 *
 * <pre>
 * u.**  ==> u.id as u_id, u.userName as u_userName, u.address as u_address...
 * u.##  ==> u.id as u_id
 * </pre>
 */
private static String replaceStarStarToColumn(String sql, String alias, String tableName, TableModel[] models) {
    String result = sql;
    if (sql.contains(alias + ".**")) {
        StringBuilder sb = new StringBuilder();
        if (models != null && models.length > 0) {
            for (TableModel tb : models) {
                if (tableName.equalsIgnoreCase(tb.getTableName())) {
                    if (StrUtils.isEmpty(tb.getAlias()))
                        tb.setAlias(alias);
                    else {
                        if (!alias.equalsIgnoreCase(tb.getAlias()))
                            throw new SqlBoxException("Alias '" + alias + "' not same as tableModel's alias");
                    }
                    for (ColumnModel col : tb.getColumns()) {
                        if (!col.getTransientable())
                            sb.append(alias).append(".").append(col.getColumnName()).append(" as ").append(alias).append("_").append(col.getColumnName()).append(", ");
                    }
                    break;
                }
            }
        }
        if (sb.length() == 0)
            throw new SqlBoxException("In SQL '" + sql + "', Can not find columns in table '" + tableName + "'");
        sb.setLength(sb.length() - 2);
        result = StrUtils.replaceFirst(sql, alias + ".**", sb.toString());
        return result;
    }
    if (sql.contains(alias + ".##")) {
        // Pkey and Fkey only
        StringBuilder sb = new StringBuilder();
        if (models != null && models.length > 0) {
            for (TableModel tb : models) {
                if (tableName.equalsIgnoreCase(tb.getTableName())) {
                    if (StrUtils.isEmpty(tb.getAlias()))
                        tb.setAlias(alias);
                    else {
                        if (!alias.equalsIgnoreCase(tb.getAlias()))
                            throw new SqlBoxException("Alias '" + alias + "' not same as tableModel's alias");
                    }
                    for (ColumnModel col : tb.getColumns()) {
                        boolean found = false;
                        if (!col.getTransientable()) {
                            if (col.getPkey())
                                found = true;
                            else {
                                for (FKeyModel tableModel : tb.getFkeyConstraints()) {
                                    if (tableModel.getColumnNames().contains(col.getColumnName())) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (found)
                            sb.append(alias).append(".").append(col.getColumnName()).append(" as ").append(alias).append("_").append(col.getColumnName()).append(", ");
                    }
                    break;
                }
            }
        }
        if (sb.length() == 0)
            throw new SqlBoxException("In SQL '" + sql + "', Can not find key columns in table '" + tableName + "'");
        sb.setLength(sb.length() - 2);
        result = StrUtils.replaceFirst(result, alias + ".##", sb.toString());
    }
    return result;
}
Also used : SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel) FKeyModel(com.github.drinkjava2.jdialects.model.FKeyModel)

Example 2 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class ActiveRecordUtils method getPreparedSQLNoParamsFromSrcCode.

private static PreparedSQL getPreparedSQLNoParamsFromSrcCode(String callerClassName, String callerMethodName, Method callerMethod) {
    // key is only inside used by cache
    String key = callerClassName + "@#$^!" + callerMethodName;
    PreparedSQL result = methodSQLCache.get(key);
    if (result != null)
        return result;
    else
        result = new PreparedSQL();
    Annotation[] annos = callerMethod.getAnnotations();
    Sql sqlAnno = null;
    Class<?>[] handlerClasses = null;
    for (Annotation anno : annos) {
        if (Sql.class.equals(anno.annotationType()))
            sqlAnno = (Sql) anno;
        if (Handler.class.equals(anno.annotationType())) {
            handlerClasses = ((Handler) anno).value();
        }
    }
    String sql = null;
    if (sqlAnno != null)
        sql = sqlAnno.value()[0];
    else {
        String src = null;
        try {
            src = TextUtils.getJavaSourceCodeUTF8(callerClassName);
        } catch (Exception e) {
            throw new SqlBoxException("Method '" + callerMethodName + "' in '" + callerClassName + "' have no Sql annotation or text.");
        }
        sql = StrUtils.substringAfter(src, callerMethodName + "(");
        sql = StrUtils.substringBetween(sql, "/*-", "*/");
    }
    if (sql != null)
        sql = sql.trim();
    result.setSql(sql);
    result.setHandlerClasses(handlerClasses);
    methodSQLCache.put(key, result);
    return result;
}
Also used : PreparedSQL(com.github.drinkjava2.jdbpro.inline.PreparedSQL) Annotation(java.lang.annotation.Annotation) Sql(com.github.drinkjava2.jsqlbox.annotation.Sql)

Example 3 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class ActiveRecordUtils method doGuessSQL.

protected static String doGuessSQL(ActiveRecord ac) {
    // NOSONAR
    int callerPos = 0;
    StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
    for (StackTraceElement stack : stacks) {
        callerPos++;
        if ("com.github.drinkjava2.jsqlbox.ActiveRecord".equals(stack.getClassName()) && "guessSQL".equals(stack.getMethodName()))
            break;
    }
    String callerClassName = stacks[callerPos].getClassName();
    String callerMethodName = stacks[callerPos].getMethodName();
    Class<?> callerClass = ClassCacheUtils.checkClassExist(callerClassName);
    if (callerClass == null)
        throw new SqlBoxException("Can not find class '" + callerClassName + "'");
    Method callerMethod = ClassCacheUtils.checkMethodExist(callerClass, callerMethodName);
    if (callerMethod == null)
        throw new SqlBoxException("Can not find method '" + callerMethodName + "' in '" + callerClassName + "'");
    PreparedSQL sp = getPreparedSQLNoParamsFromSrcCode(callerClassName, callerMethodName, callerMethod);
    return sp.getSql();
}
Also used : PreparedSQL(com.github.drinkjava2.jdbpro.inline.PreparedSQL) Method(java.lang.reflect.Method)

Example 4 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class SqlBoxUtils method createSqlBox.

/**
 * Create a SqlBox by given entity or entityClass
 */
public static SqlBox createSqlBox(SqlBoxContext ctx, Class<?> entityOrBoxClass) {
    Class<?> boxClass = null;
    if (entityOrBoxClass == null)
        throw new SqlBoxException("Bean Or SqlBox class can not be null");
    if (SqlBox.class.isAssignableFrom(entityOrBoxClass))
        boxClass = entityOrBoxClass;
    if (boxClass == null)
        boxClass = ClassCacheUtils.checkClassExist(entityOrBoxClass.getName() + SqlBoxContext.getGlobalsqlboxsuffix());
    if (boxClass == null)
        boxClass = ClassCacheUtils.checkClassExist(entityOrBoxClass.getName() + "$" + entityOrBoxClass.getSimpleName() + SqlBoxContext.getGlobalsqlboxsuffix());
    if (boxClass != null && !SqlBox.class.isAssignableFrom((Class<?>) boxClass))
        boxClass = null;
    SqlBox box = null;
    if (boxClass == null) {
        box = new SqlBox();
        box.setTableModel(TableModelUtils.entity2Model(entityOrBoxClass));
        box.setEntityClass(entityOrBoxClass);
    } else {
        try {
            box = (SqlBox) boxClass.newInstance();
            TableModel model = box.getTableModel();
            if (model == null) {
                model = TableModelUtils.entity2Model(entityOrBoxClass);
                box.setTableModel(model);
            }
            Method configMethod = null;
            try {
                // NOSONAR
                configMethod = boxClass.getMethod("config", TableModel.class);
            } catch (Exception e) {
            // NOSONAR
            }
            if (configMethod != null)
                configMethod.invoke(box, model);
        } catch (Exception e) {
            throw new SqlBoxException("Can not create SqlBox instance: " + entityOrBoxClass, e);
        }
    }
    if (box.getContext() == null)
        box.setContext(ctx);
    return box;
}
Also used : Method(java.lang.reflect.Method) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 5 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class BeetlSqlTempalte method doRender.

private static PreparedSQL doRender(SQLManager sm, String sqlId, Object paras) {
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("_root", paras);
    SQLScript script = sm.getScript(sqlId);
    SQLResult result = null;
    try {
        // run method in SQLScript is protected, have to make it accessible
        Method method = SQLScript.class.getDeclaredMethod("run", Map.class);
        ReflectionUtils.makeAccessible(method);
        result = (SQLResult) method.invoke(script, param);
    } catch (Exception e) {
        throw new SqlBoxException("Can not access method 'run' in class 'org.beetl.sql.core.SQLScript'");
    }
    PreparedSQL sp = new PreparedSQL();
    sp.setSql(result.jdbcSql);
    List<SQLParameter> sqlparam = result.jdbcPara;
    Object[] params = new Object[sqlparam.size()];
    for (int i = 0; i < sqlparam.size(); i++) {
        params[i] = sqlparam.get(i).value;
    }
    sp.setParams(params);
    return sp;
}
Also used : PreparedSQL(com.github.drinkjava2.jdbpro.inline.PreparedSQL) HashMap(java.util.HashMap) SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) SQLParameter(org.beetl.sql.core.engine.SQLParameter) SQLScript(org.beetl.sql.core.SQLScript) Method(java.lang.reflect.Method) SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) SQLResult(org.beetl.sql.core.SQLResult)

Aggregations

Method (java.lang.reflect.Method)9 TableModel (com.github.drinkjava2.jdialects.model.TableModel)8 ColumnModel (com.github.drinkjava2.jdialects.model.ColumnModel)6 SqlBoxException (com.github.drinkjava2.jsqlbox.SqlBoxException)6 PreparedSQL (com.github.drinkjava2.jdbpro.inline.PreparedSQL)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)3 IOException (java.io.IOException)2 Type (com.github.drinkjava2.jdialects.Type)1 GenerationType (com.github.drinkjava2.jdialects.annotation.jpa.GenerationType)1 IdGenerator (com.github.drinkjava2.jdialects.id.IdGenerator)1 IdentityIdGenerator (com.github.drinkjava2.jdialects.id.IdentityIdGenerator)1 FKeyModel (com.github.drinkjava2.jdialects.model.FKeyModel)1 Sql (com.github.drinkjava2.jsqlbox.annotation.Sql)1 EntityListHandler (com.github.drinkjava2.jsqlbox.handler.EntityListHandler)1 File (java.io.File)1 FileReader (java.io.FileReader)1 Annotation (java.lang.annotation.Annotation)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 SQLException (java.sql.SQLException)1