diff --git a/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtils.java b/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtils.java index 6794db2310471be9d866b27ddadca5241218f8da..6c1312a2c47f4fb102a06bad21c7644374f408de 100644 --- a/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtils.java +++ b/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtils.java @@ -16,8 +16,11 @@ import java.io.File; import java.io.FileWriter; import java.sql.Connection; import java.sql.SQLException; +import java.util.Collection; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import javax.sql.DataSource; import com.github.drinkjava2.jdialects.model.TableModel; @@ -25,11 +28,20 @@ import com.github.drinkjava2.jdialects.model.TableModel; /** * This utility tool to translate Entity class / Database metaData / Excel(will * add in future) file to TableModel - * + * * @author Yong Zhu * @since 1.0.5 */ public abstract class TableModelUtils {// NOSONAR + public static final String OPT_LINK_STYLE = "linkStyle"; + public static final String OPT_FIELD_FLAGS = "fieldFlags"; + public static final String OPT_PACKAGE_NAME = "packageName"; + public static final String OPT_IMPORTS = "imports"; + public static final String OPT_CLASS_DEFINITION = "classDefinition"; + public static final String OPT_ACTIVE_ENTITY = "activeEntity"; + public static final String OPT_ACTIVE_RECORD = "activeRecord"; + public static final String OPT_PUBLIC_FIELD = "enablePublicField"; + public static final String OPT_FILTER_MODELS = "filterModels"; /** * Convert tableName to entity class, note: before use this method @@ -70,7 +82,7 @@ public abstract class TableModelUtils {// NOSONAR /** * Read database structure and write them to Java entity class source code - * + * * @param ds * The DataSource instance * @param dialect @@ -81,14 +93,30 @@ public abstract class TableModelUtils {// NOSONAR * see TableModelUtilsOfJavaSrc.modelToJavaSourceCode() method */ public static void db2JavaSrcFiles(DataSource ds, Dialect dialect, String outputfolder, - Map setting) { + Map setting) { Connection conn = null; try { conn = ds.getConnection(); TableModel[] models = db2Models(conn, dialect); + File dir = new File(outputfolder); + if (!dir.exists()) { + dir.mkdirs(); + } + Collection filterModels = (Collection)setting.get(OPT_FILTER_MODELS); + if (filterModels != null) { + Set t = new HashSet<>(); + for(String s : filterModels) { + t.add(s.trim().toLowerCase()); + } + filterModels = t; + } for (TableModel model : models) { - File writename = new File( - outputfolder + "/" + TableModelUtilsOfJavaSrc.getClassNameFromTableModel(model) + ".java"); + String tableName = model.getTableName(); + if (filterModels != null && filterModels.contains(tableName.toLowerCase())) { + continue; + } + File writename = new File(dir, TableModelUtilsOfJavaSrc.getClassNameFromTableModel(model) + ".java"); + writename.createNewFile();// NOSONAR BufferedWriter out = new BufferedWriter(new FileWriter(writename)); String javaSrc = model2JavaSrc(model, setting); @@ -108,7 +136,7 @@ public abstract class TableModelUtils {// NOSONAR /** * Convert a TablemModel instance to Java entity class source code - * + * * @param model * The TableModel instance * @param setting diff --git a/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtilsOfJavaSrc.java b/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtilsOfJavaSrc.java index 431750d7232978908fde77224d0a69d70bc326dc..62191a49b575f08edfbda2a5bb2ec2e93fe6a9ef 100644 --- a/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtilsOfJavaSrc.java +++ b/core/src/main/java/com/github/drinkjava2/jdialects/TableModelUtilsOfJavaSrc.java @@ -11,15 +11,20 @@ */ package com.github.drinkjava2.jdialects; +import static com.github.drinkjava2.jdialects.StrUtils.clearQuote; + +import com.github.drinkjava2.jdialects.springsrc.utils.StringUtils; +import java.util.HashSet; import java.util.Map; import com.github.drinkjava2.jdialects.model.ColumnModel; import com.github.drinkjava2.jdialects.model.FKeyModel; import com.github.drinkjava2.jdialects.model.TableModel; +import java.util.Set; /** * The tool to convert TableModel to Java source code - * + * * @author Yong Zhu * @since 2.0.4 */ @@ -31,25 +36,38 @@ public abstract class TableModelUtilsOfJavaSrc {// NOSONAR * USER_NAME -> userName
* User_naMe -> userName
* UserName -> userName
- * USERNAME -> uSERNAME
+ * USERNAME -> username
* userName -> userName
* username -> username
*/ private static String transColumnNameToFieldName(String colName) { - if (StrUtils.isEmpty(colName)) + if (StrUtils.isEmpty(colName)) { return colName; - if (!colName.contains("_")) - return StrUtils.toLowerCaseFirstOne(colName); + } + + String rawColName = clearQuote(colName); + if (!colName.contains("_")) { + //return StrUtils.toLowerCaseFirstOne(colName); + if (rawColName.toUpperCase().equals(rawColName)) { + // 全大写 + return rawColName.toLowerCase(); + } else { + return StrUtils.toLowerCaseFirstOne(rawColName); + } + } + StringBuilder sb = new StringBuilder(); - char[] chars = colName.toLowerCase().toCharArray(); + char[] chars = rawColName.toLowerCase().toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; - if (c == '_') + if (c == '_') { continue; - if ((i > 0) && (chars[i - 1]) == '_' && sb.length() > 0) + } + if ((i > 0) && (chars[i - 1]) == '_' && sb.length() > 0) { sb.append(Character.toUpperCase(c)); - else + } else { sb.append(c); + } } return sb.toString(); } @@ -59,19 +77,25 @@ public abstract class TableModelUtilsOfJavaSrc {// NOSONAR * user_name -> UserName
* USER_NAME -> UserName
* User_naMe -> UserName
- * UserName -> UserName
- * USERNAME -> USERNAME
- * userName -> UserName
- * username -> Username
+ * UserName -> UserName
+ * USERNAME -> Username
+ * userName -> UserName
+ * username -> Username
*/ public static String getClassNameFromTableModel(TableModel model) { DialectException.assureNotNull(model, "TableModel can not be null"); String className; - if (model.getEntityClass() != null) + if (model.getEntityClass() != null) { className = model.getEntityClass().getSimpleName(); - else { + } else { DialectException.assureNotEmpty(model.getTableName(), "TableName can not be empty in TableModel"); - className = StrUtils.toUpperCaseFirstOne(transColumnNameToFieldName(model.getTableName())); + String tableName = transColumnNameToFieldName(model.getTableName()); + + if (tableName.toUpperCase().equals(tableName)) { + // 全大写 + tableName = tableName.toLowerCase(); + } + className = StrUtils.toUpperCaseFirstOne(tableName); } DialectException.assureNotEmpty(className, "TableName can not be empty in TableModel"); return className; @@ -79,39 +103,94 @@ public abstract class TableModelUtilsOfJavaSrc {// NOSONAR /** * Convert a TablemModel instance to Java entity class source code - * + * * @param model * The TableModel instance * @param setting * The setting options, for example: - * + * *
 	 *            Map setting = new HashMap();
-	 *            setting.put("linkStyle", false);
-	 *            setting.put("activeRecord", false);
-	 *            setting.put("activeEntity", true);
-	 *            setting.put("packageName", "somepackage");
-	 *            setting.put("fieldFlags", true);
+	 *            setting.put(TableModelUtils.OPT_LINK_STYLE, false);
+	 *            setting.put(TableModelUtils.OPT_ACTIVE_RECORD, false);
+	 *            setting.put(TableModelUtils.OPT_ACTIVE_ENTITY, true);
+	 *            setting.put(TableModelUtils.OPT_PACKAGE_NAME, "somepackage");
+	 *            setting.put(TableModelUtils.OPT_FIELD_FLAGS, true);
+	 *            setting.put(TableModelUtils.OPT_ENABLE_JAVA8, true);
+	 *            setting.put(TableModelUtils.OPT_IMPORTS, "some imports");
+	 *            setting.put(TableModelUtils.OPT_CLASS_DEFINITION, "public class $1 extends ActiveRecord<$1>");
 	 *            
- * + * * @return Java Bean source code of entity */ public static String modelToJavaSourceCode(TableModel model, Map setting) { - boolean linkStyle = Boolean.TRUE.equals(setting.get("linkStyle")); - boolean fieldFlags = Boolean.TRUE.equals(setting.get("fieldFlags")); - String classDefinition = (String) setting.get("classDefinition"); - String packageName = (String) setting.get("packageName"); - String imports = (String) setting.get("imports"); // head StringBuilder body = new StringBuilder(); - if (!StrUtils.isEmpty(packageName)) - body.append("package ").append(packageName).append(";\n"); - if (!StrUtils.isEmpty(imports)) - body.append(imports); - body.append("\n"); + generatePackage(setting, body); + generateImports(setting, body); // @table String className = getClassNameFromTableModel(model); + int fkeyCount = generateAnnotationForClass(model, body, className); + + // class + generateClassBegin(setting, body, className); + generateStaticFields(model, setting, body, className); + generateFields(model, setting,fkeyCount, body); + generateGetterAndSetter(model, setting, className, body); + generateClassEnd(body); + + return body.toString(); + } + + private static void generateStaticFields(TableModel model, + Map setting, + StringBuilder body, String className) + { + boolean fieldFlags = Boolean.TRUE.equals(setting.get(TableModelUtils.OPT_FIELD_FLAGS)); + StringBuilder fieldSB = new StringBuilder(); + // fieldStaticNames + // 不知道为什么有些表的column 定义信息是重复的,我不是DBA不清楚原因。 + // 也需要还有什么废弃的标志,但前面的处理没有过滤,这里先临时处理一下。 + Set processed = new HashSet<>(); + if (fieldFlags) { + fieldSB.append("\tpublic static final String TABLE_NAME = \"").append(model.getTableName()).append("\";\n\n"); + for (ColumnModel col : model.getColumns()) { + String columnName = col.getColumnName(); + if (processed.contains(columnName)) { + continue; + } + String rawColName = clearQuote(columnName); + processed.add(columnName); + + fieldSB.append("\tpublic static final String ") + .append(rawColName.toUpperCase()).append(" = \"") + .append(columnName).append("\";\n\n"); + } + } + body.append(fieldSB.toString()).append("\n\n"); + } + + private static void generateClassEnd(StringBuilder body) + { + body.append("}\n"); + } + + private static void generateClassBegin(Map setting, + StringBuilder body, + String className) + { + String classDefinition = (String) setting.get(TableModelUtils.OPT_CLASS_DEFINITION); + body.append(StrUtils.replace(classDefinition, "$1", className)).append(" {\n\n"); + } + + private static int generateAnnotationForClass(TableModel model, + StringBuilder body, + String className) + { + if (!StringUtils.isEmpty(model.getComment())) { + body.append("/**\n * ").append(model.getComment()).append("\n */\n"); + } if (!className.equals(model.getTableName())) { body.append("@Table").append("(name=\"").append(model.getTableName()).append("\")\n"); } @@ -119,17 +198,21 @@ public abstract class TableModelUtilsOfJavaSrc {// NOSONAR // Compound FKEY int fkeyCount = 0; for (FKeyModel fkey : model.getFkeyConstraints()) { - if (fkey.getColumnNames().size() <= 1)// Not compound Fkey + if (fkey.getColumnNames().size() <= 1)/* Not compound Fkey*/ { continue; + } body.append("@FKey"); - if (fkeyCount > 0) + if (fkeyCount > 0) { body.append(fkeyCount); + } body.append("("); fkeyCount++; - if (!StrUtils.isEmpty(fkey.getFkeyName())) + if (!StrUtils.isEmpty(fkey.getFkeyName())) { body.append("name=\"").append(fkey.getFkeyName()).append("\", "); - if (!fkey.getDdl()) + } + if (!fkey.getDdl()) { body.append("ddl=false, "); + } String fkeyCols = StrUtils.listToString(fkey.getColumnNames()); fkeyCols = StrUtils.replace(fkeyCols, ",", "\",\""); String refCols = StrUtils.arrayToString(fkey.getRefTableAndColumns()); @@ -137,97 +220,177 @@ public abstract class TableModelUtilsOfJavaSrc {// NOSONAR body.append("columns={\"").append(fkeyCols).append("\"}, refs={\"").append(refCols).append("\"}"); body.append(")\n"); } + return fkeyCount; + } - // class - body.append(StrUtils.replace(classDefinition, "$1", className)).append(" {\n\n"); + private static void generatePackage(Map setting, StringBuilder body) + { + String packageName = (String) setting.get(TableModelUtils.OPT_PACKAGE_NAME); + if (!StrUtils.isEmpty(packageName)) { + body.append("package ").append(packageName).append(";\n"); + } + body.append("\n"); + } + + private static void generateImports(Map setting, StringBuilder body) + { + String imports = (String) setting.get(TableModelUtils.OPT_IMPORTS); + body.append("import static com.github.drinkjava2.jsqlbox.JAVA8.*;\n"); + body.append("import static com.github.drinkjava2.jsqlbox.JSQLBOX.*;\n"); + body.append("import com.github.drinkjava2.jdbpro.JDBPRO.*;\n"); + body.append("import com.github.drinkjava2.jdbpro.SqlItem;\n"); + body.append("\n"); - // Fields + if (!StrUtils.isEmpty(imports)) { + body.append(imports); + } + body.append("\n"); + } + + + private static void generateFields(TableModel model, + Map setting, + int fkeyCount, + StringBuilder body) + { + boolean enablePublicField = Boolean.TRUE.equals(setting.get(TableModelUtils.OPT_PUBLIC_FIELD)); StringBuilder pkeySB = new StringBuilder(); StringBuilder normalSB = new StringBuilder(); - StringBuilder sb = null; + // 不知道为什么有些表的column 定义信息是重复的,我不是DBA不清楚原因。 + // 也需要还有什么废弃的标志,但前面的处理没有过滤,这里先临时处理一下。 + Set processed = new HashSet<>(); + StringBuilder sb; for (ColumnModel col : model.getColumns()) { + String columnName = col.getColumnName(); + if (processed.contains(columnName)) { + continue; + } + processed.add(columnName); Class javaType = TypeUtils.dialectTypeToJavaType(col.getColumnType()); - if (javaType == null) + + if (javaType == null) { continue; + } + sb = col.getPkey() ? pkeySB : normalSB; + + if (!StringUtils.isEmpty(col.getComment())) { + sb.append("\t/**\n\t * ").append(col.getComment()).append("\n\t */\n"); + } + String fieldName = col.getEntityField(); - if (StrUtils.isEmpty(fieldName)) - fieldName = transColumnNameToFieldName(col.getColumnName()); - // fieldStaticNames - if (fieldFlags) - sb.append(" public static final String " + fieldName.toUpperCase() + " = \"" + col.getColumnName() - + "\";\n"); + + if (StrUtils.isEmpty(fieldName)) { + fieldName = transColumnNameToFieldName(columnName); + } + // @Id - if (col.getPkey()) - sb.append(" @Id\n"); + if (col.getPkey()) { + sb.append("\t@Id\n"); + } // @Column boolean isStr = Type.VARCHAR.equals(col.getColumnType()) || Type.CHAR.equals(col.getColumnType()); - if (fieldFlags || !fieldName.equalsIgnoreCase(col.getColumnName()) || (isStr && 250 != col.getLength())) { - sb.append(" @Column("); - if (fieldFlags) - sb.append("name=").append(fieldName.toUpperCase()).append(", "); - else if (!fieldName.equalsIgnoreCase(col.getColumnName())) - sb.append("name=\"").append(col.getColumnName()).append("\", "); - - if (isStr && 250 != col.getLength()) + // 好魔幻的数字 + boolean lenNotEq250 = 250 != col.getLength(); + if (!fieldName.equalsIgnoreCase(columnName) || (isStr && lenNotEq250)) { + sb.append("\t@Column("); + sb.append("name=\"").append(columnName).append("\", "); + + if (isStr && lenNotEq250) { sb.append("length=").append(col.getLength()).append(", "); + } sb.setLength(sb.length() - 2); sb.append(")\n"); } // @SingleFKey for (FKeyModel fkey : model.getFkeyConstraints()) { - if (fkey.getColumnNames().size() != 1)// Not compound Fkey + /* Not compound Fkey*/ + if (fkey.getColumnNames().size() != 1) { continue; - if (!col.getColumnName().equalsIgnoreCase(fkey.getColumnNames().get(0))) + } + if (!columnName.equalsIgnoreCase(fkey.getColumnNames().get(0))) { continue; - sb.append(" @SingleFKey"); + } + sb.append("\t@SingleFKey"); sb.append("("); fkeyCount++; - if (!StrUtils.isEmpty(fkey.getFkeyName())) + if (!StrUtils.isEmpty(fkey.getFkeyName())) { sb.append("name=\"").append(fkey.getFkeyName()).append("\", "); - if (!fkey.getDdl()) + } + if (!fkey.getDdl()) { sb.append("ddl=false, "); + } String refCols = StrUtils.arrayToString(fkey.getRefTableAndColumns()); refCols = StrUtils.replace(refCols, ",", "\",\""); sb.append("refs={\"").append(refCols).append("\"}"); sb.append(")\n"); } - sb.append(" private ").append(javaType.getSimpleName()).append(" ").append(fieldName).append(";\n\n"); + String accessModifier = "private"; + if(enablePublicField) { + accessModifier = "public"; + } + sb.append("\t").append(accessModifier).append(' ') + .append(javaType.getSimpleName()).append(' ') + .append(fieldName).append(";\n\n"); } - body.append(pkeySB.toString()).append(normalSB.toString()); - pkeySB.setLength(0); - normalSB.setLength(0); + body.append(pkeySB.toString()).append("\n\n") + .append(normalSB.toString()).append("\n\n"); + } + + + private static void generateGetterAndSetter(TableModel model, + Map setting, + String className, + StringBuilder body) + { + boolean linkStyle = Boolean.TRUE.equals(setting.get(TableModelUtils.OPT_LINK_STYLE)); + StringBuilder pkeySB = new StringBuilder(); + StringBuilder normalSB = new StringBuilder(); + // 不知道为什么有些表的column 定义信息是重复的,我不是DBA不清楚原因。 + // 也需要还有什么废弃的标志,但前面的处理没有过滤,这里先临时处理一下。 + Set processed = new HashSet<>(); + StringBuilder sb; for (ColumnModel col : model.getColumns()) { + if (processed.contains(col.getColumnName())) { + continue; + } + + processed.add(col.getColumnName()); // getter Class javaType = TypeUtils.dialectTypeToJavaType(col.getColumnType()); - if (javaType == null) + + if (javaType == null) { continue; + } + sb = col.getPkey() ? pkeySB : normalSB; String fieldName = col.getEntityField(); - if (StrUtils.isEmpty(fieldName)) + if (StrUtils.isEmpty(fieldName)) { fieldName = transColumnNameToFieldName(col.getColumnName()); + } String getFieldName = "get" + StrUtils.toUpperCaseFirstOne(fieldName); - sb.append(" public ").append(javaType.getSimpleName()).append(" ").append(getFieldName).append("(){\n"); - sb.append(" return ").append(fieldName).append(";\n"); - sb.append(" }\n\n"); + sb.append("\tpublic ").append(javaType.getSimpleName()).append(" ").append(getFieldName).append("(){\n"); + sb.append("\t\treturn ").append(fieldName).append(";\n"); + sb.append("\t}\n\n"); // settter String setFieldName = "set" + StrUtils.toUpperCaseFirstOne(fieldName); - sb.append(" public ").append(linkStyle ? className : "void").append(" ").append(setFieldName).append("(") - .append(javaType.getSimpleName()).append(" ").append(fieldName).append("){\n"); - sb.append(" this.").append(fieldName).append("=").append(fieldName).append(";\n"); - if (linkStyle) - sb.append(" return this;\n"); - sb.append(" }\n\n"); + if (linkStyle) { + sb.append("\tpublic ").append(className).append(" ").append(setFieldName).append("(") + .append(javaType.getSimpleName()).append(" ").append(fieldName).append("){\n"); + sb.append("\t\tthis.").append(fieldName).append("=").append(fieldName).append(";\n"); + sb.append("\t\treturn this;\n"); + } else { + sb.append("\tpublic ").append("void").append(" ").append(setFieldName).append("(") + .append(javaType.getSimpleName()).append(" ").append(fieldName).append("){\n"); + sb.append("\t\tthis.").append(fieldName).append("=").append(fieldName).append(";\n"); + } + sb.append("\t}\n\n"); } body.append(pkeySB.toString()).append(normalSB.toString()); - - body.append("}"); - - return body.toString(); } } diff --git a/core/src/main/java/com/github/drinkjava2/jdialects/TypeUtils.java b/core/src/main/java/com/github/drinkjava2/jdialects/TypeUtils.java index 9d55a361a79147eef46085e21ac9144f59b24d55..4e997f85f470a19d2e5220dd2e44d1116cead8f3 100644 --- a/core/src/main/java/com/github/drinkjava2/jdialects/TypeUtils.java +++ b/core/src/main/java/com/github/drinkjava2/jdialects/TypeUtils.java @@ -99,6 +99,8 @@ public abstract class TypeUtils {// NOSONAR /* JAVA8_END */ TYPE_TO_JAVA_MAP.put(Type.NUMERIC, BigDecimal.class); + // 这一句是多余的,,会被 TYPE_TO_JAVA_MAP.put(Type.BIGINT, Long.class) 覆盖 + // 目前64位机器,BIGINT 就是 Long, 有必要吗? TYPE_TO_JAVA_MAP.put(Type.BIGINT, BigInteger.class); TYPE_TO_JAVA_MAP.put(Type.BOOLEAN, Boolean.class); TYPE_TO_JAVA_MAP.put(Type.TINYINT, Byte.class); @@ -108,7 +110,9 @@ public abstract class TypeUtils {// NOSONAR TYPE_TO_JAVA_MAP.put(Type.BINARY, java.sql.Blob.class); TYPE_TO_JAVA_MAP.put(Type.BIT, Boolean.class); TYPE_TO_JAVA_MAP.put(Type.BLOB, java.sql.Blob.class); - TYPE_TO_JAVA_MAP.put(Type.CHAR, Character.class); + // 这里没有考虑长度,会有问题,还是影射成 String + // TYPE_TO_JAVA_MAP.put(Type.CHAR, Character.class); + TYPE_TO_JAVA_MAP.put(Type.CHAR, String.class); TYPE_TO_JAVA_MAP.put(Type.CLOB, java.sql.Clob.class); TYPE_TO_JAVA_MAP.put(Type.DECIMAL, BigDecimal.class); TYPE_TO_JAVA_MAP.put(Type.DOUBLE, Double.class); @@ -384,6 +388,7 @@ public abstract class TypeUtils {// NOSONAR return c; } } else if (vType == String.class) { + // FIXME: 这里应当考虑长度。 if (javaType == char.class || javaType == Character.class) { return ((String) value).length() > 0 ? ((String) value).charAt(0) : '\u0000'; } diff --git a/core/src/main/java/com/github/drinkjava2/jsqlbox/DB.java b/core/src/main/java/com/github/drinkjava2/jsqlbox/DB.java index 9900387be2ed123cb445dc2551f8a5b8614c5b6b..39845856ac221d08065726c17ee00655721e9044 100644 --- a/core/src/main/java/com/github/drinkjava2/jsqlbox/DB.java +++ b/core/src/main/java/com/github/drinkjava2/jsqlbox/DB.java @@ -11,6 +11,7 @@ */ package com.github.drinkjava2.jsqlbox; +import com.github.drinkjava2.jdbpro.PreparedSQL; import java.sql.Connection; import java.util.List; import java.util.Map; @@ -164,7 +165,8 @@ public abstract class DB extends JDBPRO {// NOSONAR public static T iInsert(Object... items) {return gctx().iInsert(items);} public static T iExecute(Object... items) {return gctx().iExecute(items); } public static List iQueryForEntityList(Object... items) {return gctx().iQueryForEntityList(items);} - + public static PreparedSQL iPrepare(Object... items) { return gctx().iPrepare(items); } + public static T nQuery(Connection conn, ResultSetHandler rsh, String sql, Object... items) {return gctx().nQuery(conn, rsh, sql, items);} public static T nQueryForObject(Connection conn, String sql, Object... items) {return gctx().nQueryForObject(conn, sql, items);} public static String nQueryForString(Connection conn, String sql, Object... items) {return gctx().nQueryForString(conn, sql, items);} diff --git a/core/src/main/java/com/github/drinkjava2/jsqlbox/DbContext.java b/core/src/main/java/com/github/drinkjava2/jsqlbox/DbContext.java index f97cada7aef721903a3a8774f24a81a04334930c..7435aba133dd4f09bdef2ed96e6bd98683bd4000 100644 --- a/core/src/main/java/com/github/drinkjava2/jsqlbox/DbContext.java +++ b/core/src/main/java/com/github/drinkjava2/jsqlbox/DbContext.java @@ -143,8 +143,9 @@ public class DbContext extends DbPro {// NOSONAR public Object getCurrentAuditor() { DbException.assureNotNull(auditorGetter, "Can not call getCurrentAuditor() when auditorGetter is null."); Object result = null; - if (methodOfGetCurrentAuditor == null) + if (methodOfGetCurrentAuditor == null) { methodOfGetCurrentAuditor = ClassUtils.getMethod(auditorGetter.getClass(), "getCurrentAuditor"); + } try { result = methodOfGetCurrentAuditor.invoke(auditorGetter); } catch (Exception e) { @@ -158,17 +159,19 @@ public class DbContext extends DbPro {// NOSONAR */ @Override protected boolean dealOneSqlItem(boolean iXxxStyle, PreparedSQL ps, Object item) {// NOSONAR - if (super.dealOneSqlItem(iXxxStyle, ps, item)) + if (super.dealOneSqlItem(iXxxStyle, ps, item)) { return true; // if super class DbPro can deal it, let it do + } if (item instanceof SqlOption) { - if (SqlOption.IGNORE_EMPTY.equals(item)) + if (SqlOption.IGNORE_EMPTY.equals(item)) { ps.setIgnoreEmpty(true); - else if (SqlOption.IGNORE_NULL.equals(item)) + } else if (SqlOption.IGNORE_NULL.equals(item)) { ps.setIgnoreNull(true); - else if (SqlOption.AUTO_SQL.equals(item)) + } else if (SqlOption.AUTO_SQL.equals(item)) { DbContextUtils.appendLeftJoinSQL(ps); - else + } else { return false; + } } else if (item instanceof TableModel) { ps.addModel(item); DbContextUtils.createLastAutoAliasName(ps); @@ -179,95 +182,113 @@ public class DbContext extends DbPro {// NOSONAR } else if (item instanceof SqlItem) { SqlItem sqItem = (SqlItem) item; SqlOption sqlItemType = sqItem.getType(); - if (SqlOption.SHARD_TABLE.equals(sqlItemType)) + if (SqlOption.SHARD_TABLE.equals(sqlItemType)) { handleShardTable(ps, sqItem); - else if (SqlOption.SHARD_DATABASE.equals(sqlItemType)) + } else if (SqlOption.SHARD_DATABASE.equals(sqlItemType)) { handleShardDatabase(ps, sqItem); - else if (SqlOption.GIVE.equals(sqlItemType)) { + } else if (SqlOption.GIVE.equals(sqlItemType)) { Object[] o = ((SqlItem) item).getParameters(); String[] s = new String[o.length]; - for (int i = 0; i < o.length; i++) + for (int i = 0; i < o.length; i++) { s[i] = (String) o[i]; + } ps.addGives(s); } else if (SqlOption.GIVE_BOTH.equals(sqlItemType)) { Object[] a = ((SqlItem) item).getParameters(); ps.addGives(new String[] { (String) a[0], (String) a[1] }); ps.addGives(new String[] { (String) a[1], (String) a[0] }); } else if (SqlOption.ALIAS.equals(sqlItemType)) { - if (sqItem.getParameters().length == 0) + if (sqItem.getParameters().length == 0) { throw new DbException("alias method need parameter"); + } ps.setLastAliases((String[]) sqItem.getParameters());// NOSONAR } else if (SqlOption.TAIL.equals(sqlItemType)) { return true; // do nothing - } else + } else { return false; + } } else if (item instanceof EntityNet) { ps.setEntityNet((EntityNet) item); ps.addHandler(new EntityNetHandler()); - } else + } else { return false; + } return true; } /** Get the sharded table name by given shard values */ public String getShardedTB(Object entityOrClass, Object... shardvalues) { String table = DbContextUtils.getShardedTB(this, entityOrClass, shardvalues); - if (table == null) - throw new DbException("No found ShardingTool can handle target '" + entityOrClass + "' "); + if (table == null) { + throw new DbException( + "No found ShardingTool can handle target '" + entityOrClass + "' "); + } return table; } /** Get the sharded DB(=DbContext) instance by given shard values */ public DbContext getShardedDB(Object entityOrClass, Object... shardvalues) { DbContext ctx = DbContextUtils.getShardedDB(this, entityOrClass, shardvalues); - if (ctx == null) - throw new DbException("Not found ShardingTool can handle entity '" + entityOrClass + "' "); + if (ctx == null) { + throw new DbException( + "Not found ShardingTool can handle entity '" + entityOrClass + "' "); + } return ctx; } protected String handleShardTable(PreparedSQL predSQL, SqlItem item) { Object[] params = item.getParameters(); String table = null; - if (predSQL.getModels() == null || predSQL.getModels().length == 0) + if (predSQL.getModels() == null || predSQL.getModels().length == 0) { throw new DbException("ShardTable not found model setting"); + } TableModel model = (TableModel) predSQL.getModels()[0]; - if (params.length == 1) + if (params.length == 1) { table = DbContextUtils.getShardedTB(this, model, params[0]); - else if (params.length == 2) + } else if (params.length == 2) { table = DbContextUtils.getShardedTB(this, model, params[0], params[1]); - else + } else { throw new DbException("ShardTable need 1 or 2 parameters"); - if (table == null) + } + if (table == null) { throw new DbException("No ShardTable Tool found."); - else + } else { predSQL.addSql(table); + } return table; } protected DbPro handleShardDatabase(PreparedSQL predSQL, SqlItem item) { Object[] params = item.getParameters(); DbContext ctx = null; - if (predSQL.getModels() == null || predSQL.getModels().length == 0) + if (predSQL.getModels() == null || predSQL.getModels().length == 0) { return this; + } TableModel model = (TableModel) predSQL.getModels()[0]; - if (params.length == 1) + if (params.length == 1) { ctx = DbContextUtils.getShardedDB(this, model, params[0]); - else if (params.length == 2) + } else if (params.length == 2) { ctx = DbContextUtils.getShardedDB(this, model, params[0], params[1]); - else + } else { throw new DbException("ShardDatabase need 1 or 2 parameters"); - if (ctx == null) + } + if (ctx == null) { throw new DbException("No ShardDatabase Tool found."); - else + } else { predSQL.setSwitchTo(ctx); + } return ctx; } private static void checkOnlyOneRowAffected(int result, String curdType) { - if (result <= 0) - throw new DbException("No record found in database when do '" + curdType + "' operation."); - if (result > 1) - throw new DbException("Affect more than 1 row record in database when do '" + curdType + "' operation."); + if (result <= 0) { + throw new DbException( + "No record found in database when do '" + curdType + "' operation."); + } + if (result > 1) { + throw new DbException("Affect more than 1 row record in database when do '" + curdType + + "' operation."); + } } /** Use i style to query for an entity list */ @@ -292,8 +313,9 @@ public class DbContext extends DbPro {// NOSONAR /** If dbModels not loaded, loaded from database */ public void ensureTailModelLoaded() { - if (tailModels != null) + if (tailModels != null) { return; + } reloadTailModels(); } @@ -319,12 +341,13 @@ public class DbContext extends DbPro {// NOSONAR } catch (SQLException e) { throw new DbException(e); } finally { - if (conn != null) + if (conn != null) { try { conn.close(); } catch (SQLException e) { DbException.eatException(e); } + } } } @@ -407,18 +430,24 @@ public class DbContext extends DbPro {// NOSONAR /** Load entity by given id, if not 1 row found, throw SqlBoxException */ public T eLoadById(Class entityClass, Object entityId, Object... optionItems) { T entity = DbContextUtils.entityLoadByIdTry(this, entityClass, entityId, optionItems); - if (entity == null) + if (entity == null) { throw new DbException("No record found in database when do 'LoadById' operation."); + } return entity; } /** Load one entity according SQL, if not found, return null */ public T eLoadBySQL(Object... optionItems) { List entities = iQueryForEntityList(optionItems); - if (entities == null || entities.isEmpty()) - throw new DbException("No record found in database when try to load entity."); - if (entities.size() > 1) - throw new DbException("More than 1 record found when try to load 1 entity."); + if (entities == null || entities.isEmpty()) { + // throw new DbException("No record found in database when try to load entity."); + System.err.println("WARNING: No record found in database when try to load entity."); + return null; + } + if (entities.size() > 1) { + // throw new DbException("More than 1 record found when try to load 1 entity."); + System.err.println("WARNING: More than 1 record found when try to load 1 entity."); + } return entities.get(0); } @@ -520,8 +549,9 @@ public class DbContext extends DbPro {// NOSONAR public String[] toCreateGtxLogDDL(Class... entityClasses) { assertDialectNotNull(); TableModel[] mds = new TableModel[entityClasses.length]; - for (int i = 0; i < entityClasses.length; i++) + for (int i = 0; i < entityClasses.length; i++) { mds[i] = GtxUtils.entity2GtxLogModel(entityClasses[i]); + } return dialect.toCreateDDL(mds); } @@ -539,13 +569,15 @@ public class DbContext extends DbPro {// NOSONAR /** Execute DDL stored in a String array */ public void executeDDL(String[] sqls) { - for (String sql : sqls) + for (String sql : sqls) { nExecute(sql); + } } private void assertDialectNotNull() { - if (dialect == null) + if (dialect == null) { throw new DbProException("Try use a dialect method but dialect is null"); + } } protected void getteSetters__________________________() {// NOSONAR diff --git a/core/src/main/java/com/github/drinkjava2/jsqlbox/JSQLBOX.java b/core/src/main/java/com/github/drinkjava2/jsqlbox/JSQLBOX.java index 713f28027633682fc7c519532e511533d8002656..20ed0fa574732a4ed14c88252c46f07c0d14b392 100644 --- a/core/src/main/java/com/github/drinkjava2/jsqlbox/JSQLBOX.java +++ b/core/src/main/java/com/github/drinkjava2/jsqlbox/JSQLBOX.java @@ -11,6 +11,8 @@ */ package com.github.drinkjava2.jsqlbox; +import com.github.drinkjava2.jdialects.springsrc.utils.StringUtils; + /** * JSQLBOX store some public static methods, usually used for static import to * simplify programming @@ -18,6 +20,686 @@ package com.github.drinkjava2.jsqlbox; * @author Yong Zhu * @since 1.0.8 */ -public abstract class JSQLBOX extends DB { - +public abstract class JSQLBOX extends DB { + public static final String EQ_P = " = ? "; + public static final String EQ = " = "; + public static final String LTEQ_P = " <= ? "; + public static final String LTEQ = " <= "; + public static final String GTEQ_P = " >= ? "; + public static final String GTEQ = " >= "; + public static final String NOTEQ = " != "; + public static final String NOTEQ_P = " != ? "; + public static final String IS_NULL = " IS NULL "; + public static final String IS_NOT_NULL = " IS NOT NULL "; + public static final String NOT_IN = " NOT IN "; + public static final String ORDER_BY = " ORDER BY "; + public static final String LIMIT_1 = " LIMIT 1"; + public static final String SELECT_STAR = " SELECT * "; + public static final String DELETE_FROM = " DELETE FROM "; + public static final String INSERT_INTO = " INSERT INTO "; + // sql 关键字 + public static final String ABSOLUTE = " ABSOLUTE "; + public static final String ACCESS = " ACCESS "; + public static final String ACTION = " ACTION "; + public static final String ADA = " ADA "; + public static final String ADD = " ADD "; + public static final String ADMIN = " ADMIN "; + public static final String AFTER = " AFTER "; + public static final String AGGREGATE = " AGGREGATE "; + public static final String ALIAS = " ALIAS "; + public static final String ALL = " ALL "; + public static final String ALLOCATE = " ALLOCATE "; + public static final String ALTER = " ALTER "; + public static final String ANALYSE = " ANALYSE "; + public static final String ANALYZE = " ANALYZE "; + public static final String AND = " AND "; + public static final String ANY = " ANY "; + public static final String ARE = " ARE "; + public static final String ARRAY = " ARRAY "; + public static final String AS = " AS "; + public static final String ASC = " ASC "; + public static final String ASENSITIVE = " ASENSITIVE "; + public static final String ASSERTION = " ASSERTION "; + public static final String ASSIGNMENT = " ASSIGNMENT "; + public static final String ASYMMETRIC = " ASYMMETRIC "; + public static final String AT = " AT "; + public static final String ATOMIC = " ATOMIC "; + public static final String AUTHORIZATION = " AUTHORIZATION "; + public static final String AVG = " AVG "; + public static final String BACKWARD = " BACKWARD "; + public static final String BEFORE = " BEFORE "; + public static final String BEGIN = " BEGIN "; + public static final String BETWEEN = " BETWEEN "; + public static final String BINARY = " BINARY "; + public static final String BIT = " BIT "; + public static final String BITVAR = " BITVAR "; + public static final String BIT_LENGTH = " BIT_LENGTH "; + public static final String BLOB = " BLOB "; + public static final String BOOLEAN = " BOOLEAN "; + public static final String BOTH = " BOTH "; + public static final String BREADTH = " BREADTH "; + public static final String BY = " BY "; + public static final String C = " C "; + public static final String CACHE = " CACHE "; + public static final String CALL = " CALL "; + public static final String CALLED = " CALLED "; + public static final String CARDINALITY = " CARDINALITY "; + public static final String CASCADE = " CASCADE "; + public static final String CASCADED = " CASCADED "; + public static final String CASE = " CASE "; + public static final String CAST = " CAST "; + public static final String CATALOG = " CATALOG "; + public static final String CATALOG_NAME = " CATALOG_NAME "; + public static final String CHAIN = " CHAIN "; + public static final String CHAR = " CHAR "; + public static final String CHARACTER = " CHARACTER "; + public static final String CHARACTERISTICS = " CHARACTERISTICS "; + public static final String CHARACTER_LENGTH = " CHARACTER_LENGTH "; + public static final String CHARACTER_SET_CATALOG = " CHARACTER_SET_CATALOG "; + public static final String CHARACTER_SET_NAME = " CHARACTER_SET_NAME "; + public static final String CHARACTER_SET_SCHEMA = " CHARACTER_SET_SCHEMA "; + public static final String CHAR_LENGTH = " CHAR_LENGTH "; + public static final String CHECK = " CHECK "; + public static final String CHECKED = " CHECKED "; + public static final String CHECKPOINT = " CHECKPOINT "; + public static final String CLASS = " CLASS "; + public static final String CLASS_ORIGIN = " CLASS_ORIGIN "; + public static final String CLOB = " CLOB "; + public static final String CLOSE = " CLOSE "; + public static final String CLUSTER = " CLUSTER "; + public static final String COALESCE = " COALESCE "; + public static final String COBOL = " COBOL "; + public static final String COLLATE = " COLLATE "; + public static final String COLLATION = " COLLATION "; + public static final String COLLATION_CATALOG = " COLLATION_CATALOG "; + public static final String COLLATION_NAME = " COLLATION_NAME "; + public static final String COLLATION_SCHEMA = " COLLATION_SCHEMA "; + public static final String COLUMN = " COLUMN "; + public static final String COLUMN_NAME = " COLUMN_NAME "; + public static final String COMMAND_FUNCTION = " COMMAND_FUNCTION "; + public static final String COMMAND_FUNCTION_CODE = " COMMAND_FUNCTION_CODE "; + public static final String COMMENT = " COMMENT "; + public static final String COMMIT = " COMMIT "; + public static final String COMMITTED = " COMMITTED "; + public static final String COMPLETION = " COMPLETION "; + public static final String CONDITION_NUMBER = " CONDITION_NUMBER "; + public static final String CONNECT = " CONNECT "; + public static final String CONNECTION = " CONNECTION "; + public static final String CONNECTION_NAME = " CONNECTION_NAME "; + public static final String CONSTRAINT = " CONSTRAINT "; + public static final String CONSTRAINTS = " CONSTRAINTS "; + public static final String CONSTRAINT_CATALOG = " CONSTRAINT_CATALOG "; + public static final String CONSTRAINT_NAME = " CONSTRAINT_NAME "; + public static final String CONSTRAINT_SCHEMA = " CONSTRAINT_SCHEMA "; + public static final String CONSTRUCTOR = " CONSTRUCTOR "; + public static final String CONTAINS = " CONTAINS "; + public static final String CONTINUE = " CONTINUE "; + public static final String CONVERT = " CONVERT "; + public static final String COPY = " COPY "; + public static final String CORRESPONDING = " CORRESPONDING "; + public static final String COUNT = " COUNT "; + public static final String CREATE = " CREATE "; + public static final String CREATEDB = " CREATEDB "; + public static final String CREATEUSER = " CREATEUSER "; + public static final String CROSS = " CROSS "; + public static final String CUBE = " CUBE "; + public static final String CURRENT = " CURRENT "; + public static final String CURRENT_DATE = " CURRENT_DATE "; + public static final String CURRENT_PATH = " CURRENT_PATH "; + public static final String CURRENT_ROLE = " CURRENT_ROLE "; + public static final String CURRENT_TIME = " CURRENT_TIME "; + public static final String CURRENT_TIMESTAMP = " CURRENT_TIMESTAMP "; + public static final String CURRENT_USER = " CURRENT_USER "; + public static final String CURSOR = " CURSOR "; + public static final String CURSOR_NAME = " CURSOR_NAME "; + public static final String CYCLE = " CYCLE "; + public static final String DATA = " DATA "; + public static final String DATABASE = " DATABASE "; + public static final String DATE = " DATE "; + public static final String DATETIME_INTERVAL_CODE = " DATETIME_INTERVAL_CODE "; + public static final String DATETIME_INTERVAL_PRECISION = " DATETIME_INTERVAL_PRECISION "; + public static final String DAY = " DAY "; + public static final String DEALLOCATE = " DEALLOCATE "; + public static final String DEC = " DEC "; + public static final String DECIMAL = " DECIMAL "; + public static final String DECLARE = " DECLARE "; + public static final String DEFAULT = " DEFAULT "; + public static final String DEFERRABLE = " DEFERRABLE "; + public static final String DEFERRED = " DEFERRED "; + public static final String DEFINED = " DEFINED "; + public static final String DEFINER = " DEFINER "; + public static final String DELETE = " DELETE "; + public static final String DELIMITERS = " DELIMITERS "; + public static final String DEPTH = " DEPTH "; + public static final String DEREF = " DEREF "; + public static final String DESC = " DESC "; + public static final String DESCRIBE = " DESCRIBE "; + public static final String DESCRIPTOR = " DESCRIPTOR "; + public static final String DESTROY = " DESTROY "; + public static final String DESTRUCTOR = " DESTRUCTOR "; + public static final String DETERMINISTIC = " DETERMINISTIC "; + public static final String DIAGNOSTICS = " DIAGNOSTICS "; + public static final String DICTIONARY = " DICTIONARY "; + public static final String DISCONNECT = " DISCONNECT "; + public static final String DISPATCH = " DISPATCH "; + public static final String DISTINCT = " DISTINCT "; + public static final String DO = " DO "; + public static final String DOMAIN = " DOMAIN "; + public static final String DOUBLE = " DOUBLE "; + public static final String DROP = " DROP "; + public static final String DYNAMIC = " DYNAMIC "; + public static final String DYNAMIC_FUNCTION = " DYNAMIC_FUNCTION "; + public static final String DYNAMIC_FUNCTION_CODE = " DYNAMIC_FUNCTION_CODE "; + public static final String EACH = " EACH "; + public static final String ELSE = " ELSE "; + public static final String ENCODING = " ENCODING "; + public static final String ENCRYPTED = " ENCRYPTED "; + public static final String END = " END "; + public static final String END_EXEC = " END-EXEC "; + public static final String EQUALS = " EQUALS "; + public static final String ESCAPE = " ESCAPE "; + public static final String EVERY = " EVERY "; + public static final String EXCEPT = " EXCEPT "; + public static final String EXCEPTION = " EXCEPTION "; + public static final String EXCLUSIVE = " EXCLUSIVE "; + public static final String EXEC = " EXEC "; + public static final String EXECUTE = " EXECUTE "; + public static final String EXISTING = " EXISTING "; + public static final String EXISTS = " EXISTS "; + public static final String EXPLAIN = " EXPLAIN "; + public static final String EXTERNAL = " EXTERNAL "; + public static final String EXTRACT = " EXTRACT "; + public static final String FALSE = " FALSE "; + public static final String FETCH = " FETCH "; + public static final String FINAL = " FINAL "; + public static final String FIRST = " FIRST "; + public static final String FLOAT = " FLOAT "; + public static final String FOR = " FOR "; + public static final String FORCE = " FORCE "; + public static final String FOREIGN = " FOREIGN "; + public static final String FORTRAN = " FORTRAN "; + public static final String FORWARD = " FORWARD "; + public static final String FOUND = " FOUND "; + public static final String FREE = " FREE "; + public static final String FREEZE = " FREEZE "; + public static final String FROM = " FROM "; + public static final String FULL = " FULL "; + public static final String FUNCTION = " FUNCTION "; + public static final String G = " G "; + public static final String GENERAL = " GENERAL "; + public static final String GENERATED = " GENERATED "; + public static final String GET = " GET "; + public static final String GLOBAL = " GLOBAL "; + public static final String GO = " GO "; + public static final String GOTO = " GOTO "; + public static final String GRANT = " GRANT "; + public static final String GRANTED = " GRANTED "; + public static final String GROUP = " GROUP "; + public static final String GROUPING = " GROUPING "; + public static final String HANDLER = " HANDLER "; + public static final String HAVING = " HAVING "; + public static final String HIERARCHY = " HIERARCHY "; + public static final String HOLD = " HOLD "; + public static final String HOST = " HOST "; + public static final String HOUR = " HOUR "; + public static final String IDENTITY = " IDENTITY "; + public static final String IGNORE = " IGNORE "; + public static final String ILIKE = " ILIKE "; + public static final String IMMEDIATE = " IMMEDIATE "; + public static final String IMPLEMENTATION = " IMPLEMENTATION "; + public static final String IN = " IN "; + public static final String INCREMENT = " INCREMENT "; + public static final String INDEX = " INDEX "; + public static final String INDICATOR = " INDICATOR "; + public static final String INFIX = " INFIX "; + public static final String INHERITS = " INHERITS "; + public static final String INITIALIZE = " INITIALIZE "; + public static final String INITIALLY = " INITIALLY "; + public static final String INNER = " INNER "; + public static final String INOUT = " INOUT "; + public static final String INPUT = " INPUT "; + public static final String INSENSITIVE = " INSENSITIVE "; + public static final String INSERT = " INSERT "; + public static final String INSTANCE = " INSTANCE "; + public static final String INSTANTIABLE = " INSTANTIABLE "; + public static final String INSTEAD = " INSTEAD "; + public static final String INT = " INT "; + public static final String INTEGER = " INTEGER "; + public static final String INTERSECT = " INTERSECT "; + public static final String INTERVAL = " INTERVAL "; + public static final String INTO = " INTO "; + public static final String INVOKER = " INVOKER "; + public static final String IS = " IS "; + public static final String ISNULL = " ISNULL "; + public static final String ISOLATION = " ISOLATION "; + public static final String ITERATE = " ITERATE "; + public static final String JOIN = " JOIN "; + public static final String K = " K "; + public static final String KEY = " KEY "; + public static final String KEY_MEMBER = " KEY_MEMBER "; + public static final String KEY_TYPE = " KEY_TYPE "; + public static final String LANCOMPILER = " LANCOMPILER "; + public static final String LANGUAGE = " LANGUAGE "; + public static final String LARGE = " LARGE "; + public static final String LAST = " LAST "; + public static final String LATERAL = " LATERAL "; + public static final String LEADING = " LEADING "; + public static final String LEFT = " LEFT "; + public static final String LENGTH = " LENGTH "; + public static final String LESS = " LESS "; + public static final String LEVEL = " LEVEL "; + public static final String LIKE = " LIKE "; + public static final String LIMIT = " LIMIT "; + public static final String LISTEN = " LISTEN "; + public static final String LOAD = " LOAD "; + public static final String LOCAL = " LOCAL "; + public static final String LOCALTIME = " LOCALTIME "; + public static final String LOCALTIMESTAMP = " LOCALTIMESTAMP "; + public static final String LOCATION = " LOCATION "; + public static final String LOCATOR = " LOCATOR "; + public static final String LOCK = " LOCK "; + public static final String LOWER = " LOWER "; + public static final String M = " M "; + public static final String MAP = " MAP "; + public static final String MATCH = " MATCH "; + public static final String MAX = " MAX "; + public static final String MAXVALUE = " MAXVALUE "; + public static final String MESSAGE_LENGTH = " MESSAGE_LENGTH "; + public static final String MESSAGE_OCTET_LENGTH = " MESSAGE_OCTET_LENGTH "; + public static final String MESSAGE_TEXT = " MESSAGE_TEXT "; + public static final String METHOD = " METHOD "; + public static final String MIN = " MIN "; + public static final String MINUTE = " MINUTE "; + public static final String MINVALUE = " MINVALUE "; + public static final String MOD = " MOD "; + public static final String MODE = " MODE "; + public static final String MODIFIES = " MODIFIES "; + public static final String MODIFY = " MODIFY "; + public static final String MODULE = " MODULE "; + public static final String MONTH = " MONTH "; + public static final String MORE = " MORE "; + public static final String MOVE = " MOVE "; + public static final String MUMPS = " MUMPS "; + public static final String NAME = " NAME "; + public static final String NAMES = " NAMES "; + public static final String NATIONAL = " NATIONAL "; + public static final String NATURAL = " NATURAL "; + public static final String NCHAR = " NCHAR "; + public static final String NCLOB = " NCLOB "; + public static final String NEW = " NEW "; + public static final String NEXT = " NEXT "; + public static final String NO = " NO "; + public static final String NOCREATEDB = " NOCREATEDB "; + public static final String NOCREATEUSER = " NOCREATEUSER "; + public static final String NONE = " NONE "; + public static final String NOT = " NOT "; + public static final String NOTHING = " NOTHING "; + public static final String NOTIFY = " NOTIFY "; + public static final String NOTNULL = " NOTNULL "; + public static final String NULL = " NULL "; + public static final String NULLABLE = " NULLABLE "; + public static final String NULLIF = " NULLIF "; + public static final String NUMBER = " NUMBER "; + public static final String NUMERIC = " NUMERIC "; + public static final String OBJECT = " OBJECT "; + public static final String OCTET_LENGTH = " OCTET_LENGTH "; + public static final String OF = " OF "; + public static final String OFF = " OFF "; + public static final String OFFSET = " OFFSET "; + public static final String OIDS = " OIDS "; + public static final String OLD = " OLD "; + public static final String ON = " ON "; + public static final String ONLY = " ONLY "; + public static final String OPEN = " OPEN "; + public static final String OPERATION = " OPERATION "; + public static final String OPERATOR = " OPERATOR "; + public static final String OPTION = " OPTION "; + public static final String OPTIONS = " OPTIONS "; + public static final String OR = " OR "; + public static final String ORDER = " ORDER "; + public static final String ORDINALITY = " ORDINALITY "; + public static final String OUT = " OUT "; + public static final String OUTER = " OUTER "; + public static final String OUTPUT = " OUTPUT "; + public static final String OVERLAPS = " OVERLAPS "; + public static final String OVERLAY = " OVERLAY "; + public static final String OVERRIDING = " OVERRIDING "; + public static final String OWNER = " OWNER "; + public static final String PAD = " PAD "; + public static final String PARAMETER = " PARAMETER "; + public static final String PARAMETERS = " PARAMETERS "; + public static final String PARAMETER_MODE = " PARAMETER_MODE "; + public static final String PARAMETER_NAME = " PARAMETER_NAME "; + public static final String PARAMETER_ORDINAL_POSITION = " PARAMETER_ORDINAL_POSITION "; + public static final String PARAMETER_SPECIFIC_CATALOG = " PARAMETER_SPECIFIC_CATALOG "; + public static final String PARAMETER_SPECIFIC_NAME = " PARAMETER_SPECIFIC_NAME "; + public static final String PARAMETER_SPECIFIC_SCHEMA = " PARAMETER_SPECIFIC_SCHEMA "; + public static final String PARTIAL = " PARTIAL "; + public static final String PASCAL = " PASCAL "; + public static final String PASSWORD = " PASSWORD "; + public static final String PATH = " PATH "; + public static final String PENDANT = " PENDANT "; + public static final String PLI = " PLI "; + public static final String POSITION = " POSITION "; + public static final String POSTFIX = " POSTFIX "; + public static final String PRECISION = " PRECISION "; + public static final String PREFIX = " PREFIX "; + public static final String PREORDER = " PREORDER "; + public static final String PREPARE = " PREPARE "; + public static final String PRESERVE = " PRESERVE "; + public static final String PRIMARY = " PRIMARY "; + public static final String PRIOR = " PRIOR "; + public static final String PRIVILEGES = " PRIVILEGES "; + public static final String PROCEDURAL = " PROCEDURAL "; + public static final String PROCEDURE = " PROCEDURE "; + public static final String PUBLIC = " PUBLIC "; + public static final String READ = " READ "; + public static final String READS = " READS "; + public static final String REAL = " REAL "; + public static final String RECURSIVE = " RECURSIVE "; + public static final String REF = " REF "; + public static final String REFERENCES = " REFERENCES "; + public static final String REFERENCING = " REFERENCING "; + public static final String REINDEX = " REINDEX "; + public static final String RELATIVE = " RELATIVE "; + public static final String RENAME = " RENAME "; + public static final String REPEATABLE = " REPEATABLE "; + public static final String REPLACE = " REPLACE "; + public static final String RESET = " RESET "; + public static final String RESTRICT = " RESTRICT "; + public static final String RESULT = " RESULT "; + public static final String RETURN = " RETURN "; + public static final String RETURNED_LENGTH = " RETURNED_LENGTH "; + public static final String RETURNED_OCTET_LENGTH = " RETURNED_OCTET_LENGTH "; + public static final String RETURNED_SQLSTATE = " RETURNED_SQLSTATE "; + public static final String RETURNS = " RETURNS "; + public static final String REVOKE = " REVOKE "; + public static final String RIGHT = " RIGHT "; + public static final String ROLE = " ROLE "; + public static final String ROLLBACK = " ROLLBACK "; + public static final String ROLLUP = " ROLLUP "; + public static final String ROUTINE = " ROUTINE "; + public static final String ROUTINE_CATALOG = " ROUTINE_CATALOG "; + public static final String ROUTINE_NAME = " ROUTINE_NAME "; + public static final String ROUTINE_SCHEMA = " ROUTINE_SCHEMA "; + public static final String ROW = " ROW "; + public static final String ROWS = " ROWS "; + public static final String ROW_COUNT = " ROW_COUNT "; + public static final String RULE = " RULE "; + public static final String SAVEPOINT = " SAVEPOINT "; + public static final String SCALE = " SCALE "; + public static final String SCHEMA = " SCHEMA "; + public static final String SCHEMA_NAME = " SCHEMA_NAME "; + public static final String SCOPE = " SCOPE "; + public static final String SCROLL = " SCROLL "; + public static final String SEARCH = " SEARCH "; + public static final String SECOND = " SECOND "; + public static final String SECTION = " SECTION "; + public static final String SECURITY = " SECURITY "; + public static final String SELECT = " SELECT "; + public static final String SELF = " SELF "; + public static final String SENSITIVE = " SENSITIVE "; + public static final String SEQUENCE = " SEQUENCE "; + public static final String SERIALIZABLE = " SERIALIZABLE "; + public static final String SERVER_NAME = " SERVER_NAME "; + public static final String SESSION = " SESSION "; + public static final String SESSION_USER = " SESSION_USER "; + public static final String SET = " SET "; + public static final String SETOF = " SETOF "; + public static final String SETS = " SETS "; + public static final String SHARE = " SHARE "; + public static final String SHOW = " SHOW "; + public static final String SIMILAR = " SIMILAR "; + public static final String SIMPLE = " SIMPLE "; + public static final String SIZE = " SIZE "; + public static final String SMALLINT = " SMALLINT "; + public static final String SOME = " SOME "; + public static final String SOURCE = " SOURCE "; + public static final String SPACE = " SPACE "; + public static final String SPECIFIC = " SPECIFIC "; + public static final String SPECIFICTYPE = " SPECIFICTYPE "; + public static final String SPECIFIC_NAME = " SPECIFIC_NAME "; + public static final String SQL = " SQL "; + public static final String SQLCODE = " SQLCODE "; + public static final String SQLERROR = " SQLERROR "; + public static final String SQLEXCEPTION = " SQLEXCEPTION "; + public static final String SQLSTATE = " SQLSTATE "; + public static final String SQLWARNING = " SQLWARNING "; + public static final String START = " START "; + public static final String STATE = " STATE "; + public static final String STATEMENT = " STATEMENT "; + public static final String STATIC = " STATIC "; + public static final String STATISTICS = " STATISTICS "; + public static final String STDIN = " STDIN "; + public static final String STDOUT = " STDOUT "; + public static final String STRUCTURE = " STRUCTURE "; + public static final String STYLE = " STYLE "; + public static final String SUBCLASS_ORIGIN = " SUBCLASS_ORIGIN "; + public static final String SUBLIST = " SUBLIST "; + public static final String SUBSTRING = " SUBSTRING "; + public static final String SUM = " SUM "; + public static final String SYMMETRIC = " SYMMETRIC "; + public static final String SYSID = " SYSID "; + public static final String SYSTEM = " SYSTEM "; + public static final String SYSTEM_USER = " SYSTEM_USER "; + public static final String TABLE = " TABLE "; + public static final String TEMP = " TEMP "; + public static final String TEMPLATE = " TEMPLATE "; + public static final String TEMPORARY = " TEMPORARY "; + public static final String TERMINATE = " TERMINATE "; + public static final String THAN = " THAN "; + public static final String THEN = " THEN "; + public static final String TIME = " TIME "; + public static final String TIMESTAMP = " TIMESTAMP "; + public static final String TIMEZONE_HOUR = " TIMEZONE_HOUR "; + public static final String TIMEZONE_MINUTE = " TIMEZONE_MINUTE "; + public static final String TO = " TO "; + public static final String TOAST = " TOAST "; + public static final String TRAILING = " TRAILING "; + public static final String TRANSACTION = " TRANSACTION "; + public static final String TRANSACTIONS_COMMITTED = " TRANSACTIONS_COMMITTED "; + public static final String TRANSACTIONS_ROLLED_BACK = " TRANSACTIONS_ROLLED_BACK "; + public static final String TRANSACTION_ACTIVE = " TRANSACTION_ACTIVE "; + public static final String TRANSFORM = " TRANSFORM "; + public static final String TRANSFORMS = " TRANSFORMS "; + public static final String TRANSLATE = " TRANSLATE "; + public static final String TRANSLATION = " TRANSLATION "; + public static final String TREAT = " TREAT "; + public static final String TRIGGER = " TRIGGER "; + public static final String TRIGGER_CATALOG = " TRIGGER_CATALOG "; + public static final String TRIGGER_NAME = " TRIGGER_NAME "; + public static final String TRIGGER_SCHEMA = " TRIGGER_SCHEMA "; + public static final String TRIM = " TRIM "; + public static final String TRUE = " TRUE "; + public static final String TRUNCATE = " TRUNCATE "; + public static final String TRUSTED = " TRUSTED "; + public static final String TYPE = " TYPE "; + public static final String UNCOMMITTED = " UNCOMMITTED "; + public static final String UNDER = " UNDER "; + public static final String UNENCRYPTED = " UNENCRYPTED "; + public static final String UNION = " UNION "; + public static final String UNIQUE = " UNIQUE "; + public static final String UNKNOWN = " UNKNOWN "; + public static final String UNLISTEN = " UNLISTEN "; + public static final String UNNAMED = " UNNAMED "; + public static final String UNNEST = " UNNEST "; + public static final String UNTIL = " UNTIL "; + public static final String UPDATE = " UPDATE "; + public static final String UPPER = " UPPER "; + public static final String USAGE = " USAGE "; + public static final String USER = " USER "; + public static final String USER_DEFINED_TYPE_CATALOG = " USER_DEFINED_TYPE_CATALOG "; + public static final String USER_DEFINED_TYPE_NAME = " USER_DEFINED_TYPE_NAME "; + public static final String USER_DEFINED_TYPE_SCHEMA = " USER_DEFINED_TYPE_SCHEMA "; + public static final String USING = " USING "; + public static final String VACUUM = " VACUUM "; + public static final String VALID = " VALID "; + public static final String VALUE = " VALUE "; + public static final String VALUES = " VALUES "; + public static final String VARCHAR = " VARCHAR "; + public static final String VARIABLE = " VARIABLE "; + public static final String VARYING = " VARYING "; + public static final String VERBOSE = " VERBOSE "; + public static final String VERSION = " VERSION "; + public static final String VIEW = " VIEW "; + public static final String WHEN = " WHEN "; + public static final String WHENEVER = " WHENEVER "; + public static final String WHERE = " WHERE "; + public static final String WITH = " WITH "; + public static final String WITHOUT = " WITHOUT "; + public static final String WORK = " WORK "; + public static final String WRITE = " WRITE "; + public static final String YEAR = " YEAR "; + public static final String ZONE = " ZONE "; + + // usefull function + public static String simpleReplaceDangerous(String str){ + str=str.replaceAll(";","") + .replaceAll("&","&") + .replaceAll("<","<") + .replaceAll(">",">") + .replaceAll("'","''") + .replaceAll("--","") + .replaceAll("/","") + .replaceAll("%",""); + return str; + } + public static final String array(String... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (String str : arr) { + if (StringUtils.isEmpty(str) ) { + builder.append("'',"); + } else { + builder.append("'").append(simpleReplaceDangerous(str)).append("',"); + } + } + if (builder.length() > 0) { + builder.setLength(builder.length() - 1); + } + + return "(" +builder.toString() + ")"; + } + + public static final String array(int... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (int i : arr) { + builder.append(i).append(','); + } + builder.setLength(builder.length() - 1); + return "(" +builder.toString() + ")"; + } + + public static final String array(Integer... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (Integer i : arr) { + if (i == null ) { + continue; + } + builder.append(i).append(','); + + } + if (builder.length() > 0) { + builder.setLength(builder.length() - 1); + } + + return "(" +builder.toString() + ")"; + } + + public static final String array(long... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (long i : arr) { + builder.append(i).append(','); + } + builder.setLength(builder.length() - 1); + return "(" +builder.toString() + ")"; + } + + public static final String array(Long... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (Long i : arr) { + if (i == null) { + continue; + } + builder.append(i).append(','); + } + if (builder.length() > 0) { + builder.setLength(builder.length() - 1); + } + return "(" +builder.toString() + ")"; + } + + public static final String array(short... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (short i : arr) { + builder.append(i).append(','); + } + builder.setLength(builder.length() - 1); + return "(" +builder.toString() + ")"; + } + + public static final String array(Short... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (Short i : arr) { + if (i == null) { + continue; + } + builder.append(i).append(','); + } + if (builder.length() > 0) { + builder.setLength(builder.length() - 1); + } + return "(" +builder.toString() + ")"; + } + + public static final String array(byte... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (byte i : arr) { + builder.append(i).append(','); + } + builder.setLength(builder.length() - 1); + return "(" +builder.toString() + ")"; + } + + public static final String array(Byte... arr) { + if (arr == null || arr.length == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(200); + for (Byte i : arr) { + if (i == null) { + continue; + } + builder.append(i).append(','); + } + if (builder.length() > 0) { + builder.setLength(builder.length() - 1); + } + return "(" +builder.toString() + ")"; + } + + } \ No newline at end of file