/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ package apijson.orm; import java.io.BufferedReader; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import apijson.JSONResponse; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; /**executor for query(read) or update(write) MySQL database * @author Lemon */ public abstract class AbstractSQLExecutor implements SQLExecutor { private static final String TAG = "AbstractSQLExecutor"; private int generatedSQLCount; private int cachedSQLCount; private int executedSQLCount; public AbstractSQLExecutor() { generatedSQLCount = 0; cachedSQLCount = 0; executedSQLCount = 0; } @Override public int getGeneratedSQLCount() { return generatedSQLCount; } @Override public int getCachedSQLCount() { return cachedSQLCount; } @Override public int getExecutedSQLCount() { return executedSQLCount; } /** * 缓存map */ protected Map> cacheMap = new HashMap<>(); /**保存缓存 * @param sql * @param list * @param isStatic */ @Override public synchronized void putCache(String sql, List list, int type) { if (sql == null || list == null) { //空map有效,说明查询过sql了 || list.isEmpty()) { Log.i(TAG, "saveList sql == null || list == null >> return;"); return; } cacheMap.put(sql, list); } /**移除缓存 * @param sql * @param isStatic */ @Override public synchronized void removeCache(String sql, int type) { if (sql == null) { Log.i(TAG, "removeList sql == null >> return;"); return; } cacheMap.remove(sql); } @Override public List getCache(String sql, int type) { return cacheMap.get(sql); } /**获取缓存 * @param sql * @param position * @param type * @return */ @Override public JSONObject getCacheItem(String sql, int position, int type) { List list = getCache(sql, type); //只要map不为null,则如果 list.get(position) == null,则返回 {} ,避免再次SQL查询 if (list == null) { return null; } JSONObject result = position >= list.size() ? null : list.get(position); return result != null ? result : new JSONObject(); } @Override public ResultSet executeQuery(@NotNull Statement statement, String sql) throws Exception { executedSQLCount ++; return statement.executeQuery(sql); } @Override public int executeUpdate(@NotNull Statement statement, String sql) throws Exception { executedSQLCount ++; return statement.executeUpdate(sql); } @Override public ResultSet execute(@NotNull Statement statement, String sql) throws Exception { executedSQLCount ++; statement.execute(sql); return statement.getResultSet(); } /**执行SQL * @param config * @return * @throws Exception */ @Override public JSONObject execute(@NotNull SQLConfig config, boolean unknowType) throws Exception { boolean prepared = config.isPrepared(); final String sql = config.getSQL(false); config.setPrepared(prepared); if (StringUtil.isEmpty(sql, true)) { Log.e(TAG, "select StringUtil.isEmpty(sql, true) >> return null;"); return null; } final int position = config.getPosition(); JSONObject result; if (config.isExplain() == false) { generatedSQLCount ++; } long startTime = System.currentTimeMillis(); Log.d(TAG, "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + "\n已生成 " + generatedSQLCount + " 条 SQL" + "\nselect startTime = " + startTime + "\ndatabase = " + StringUtil.getString(config.getDatabase()) + "; schema = " + StringUtil.getString(config.getSchema()) + "; sql = \n" + sql + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); ResultSet rs = null; if (unknowType) { Statement statement = getStatement(config); rs = execute(statement, sql); result = new JSONObject(true); int updateCount = statement.getUpdateCount(); result.put(JSONResponse.KEY_COUNT, updateCount); result.put("update", updateCount >= 0); //导致后面 rs.getMetaData() 报错 Operation not allowed after ResultSet closed result.put("moreResults", statement.getMoreResults()); } else { switch (config.getMethod()) { case HEAD: case HEADS: rs = executeQuery(config); executedSQLCount ++; result = rs.next() ? AbstractParser.newSuccessResult() : AbstractParser.newErrorResult(new SQLException("数据库错误, rs.next() 失败!")); result.put(JSONResponse.KEY_COUNT, rs.getLong(1)); rs.close(); return result; case POST: case PUT: case DELETE: executedSQLCount ++; int updateCount = executeUpdate(config); result = AbstractParser.newResult(updateCount > 0 ? JSONResponse.CODE_SUCCESS : JSONResponse.CODE_NOT_FOUND , updateCount > 0 ? JSONResponse.MSG_SUCCEED : "没权限访问或对象不存在!"); //id,id{}至少一个会有,一定会返回,不用抛异常来阻止关联写操作时前面错误导致后面无条件执行! result.put(JSONResponse.KEY_COUNT, updateCount);//返回修改的记录数 if (config.getId() != null) { result.put(config.getIdKey(), config.getId()); } else { result.put(config.getIdKey() + "[]", config.getWhere(config.getIdKey() + "{}", true)); } return result; case GET: case GETS: result = getCacheItem(sql, position, config.getCache()); Log.i(TAG, ">>> select result = getCache('" + sql + "', " + position + ") = " + result); if (result != null) { cachedSQLCount ++; Log.d(TAG, "\n\n select result != null >> return result;" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n"); return result; } rs = executeQuery(config); //FIXME SQL Server 是一次返回两个结果集,包括查询结果和执行计划,需要 moreResults if (config.isExplain() == false) { //只有 SELECT 才能 EXPLAIN executedSQLCount ++; } break; default://OPTIONS, TRACE等 Log.e(TAG, "select sql = " + sql + " ; method = " + config.getMethod() + " >> return null;"); return null; } } // final boolean cache = config.getCount() != 1; List resultList = new ArrayList<>(); // Log.d(TAG, "select cache = " + cache + "; resultList" + (resultList == null ? "=" : "!=") + "null"); int index = -1; ResultSetMetaData rsmd = rs.getMetaData(); final int length = rsmd.getColumnCount(); //