zhongshu-comment 该放方法只用于解析in、not in括号中的列表，将括号中的多个值转为数组Object[]
@param targetList
@return
@throws SqlParseException
483129
private Object[] parseValue(List<SQLExpr> targetList) throws SqlParseException {
        Object[] value = new Object[targetList.size()];
        for (int i = 0; i < targetList.size(); i++) {
            value[i] = parseValue(targetList.get(i));
        }
        return value;
    }
782433
@Override
  public List<String> parse() throws ParseException {

    if (expression == null)
      throw new ParseException("The expression is null", -1);

    if (logger.isDebugEnabled())
      logger.debug("Expression: " + expression);

    // expression is empty, nothing we can do
    if (expression.length() < 1)
      return null;

    // no question marks, nothing to do
    if (!expression.contains("?")) {
      return null;
    }

    // upper case the expression, to make things easier
    expression = expression.toUpperCase();

    List<String> colList = new ArrayList<>();

    if (expression.startsWith("INSERT")) {
      // expression is in the format of:  insert into table(col1, col2...) values(val1, val2...)
      // so we'll use the parens () to parse

      int colParenStart = expression.indexOf("(");
      if (colParenStart == -1)
        throw new ParseException("Unable to locate starting parenthesis for the column names.", -1);

      int colParenEnd = expression.indexOf(")", colParenStart);
      if (colParenEnd == -1)
        throw new ParseException("Unable to locate ending parenthesis for the column names.", -1);

      int valParenStart = expression.indexOf("(", colParenEnd);
      if (valParenStart == -1)
        throw new ParseException("Unable to locate starting parenthesis for the column values.", -1);

      // use the last close paren, this will make weird inner select stuff work,
      // but it won't be able to guess the inner select values
      int valParenEnd = expression.lastIndexOf(")");
      if (valParenEnd == -1)
        throw new ParseException("Unable to locate ending parenthesis for the column values.", -1);

      String[] cols = expression.substring(colParenStart + 1, colParenEnd).split(",");
      String[] vals = expression.substring(valParenStart + 1, valParenEnd).split(",");

      // if cols or vals is null, it means we couldn't find any
      if (cols == null || vals == null)
        return null;

      if (logger.isDebugEnabled()) {
        logger.debug("Found cols: " + cols.length);
        logger.debug("Found vals: " + vals.length);
      }

      if (cols.length != vals.length)
        throw new ParseException("You seem to have " + cols.length + " columns, and " + vals.length + " values.\n\nThose numbers should be equal.", -1);

      // filter out columns that we're not providing values for
      for (int i = 0; i < vals.length; i++) {
        String val = vals[i];
        if (val.trim().equals("?")) {
          // just a ?, use the col
          colList.add(cols[i].trim());
        } else if (val.contains("?")) {
          // more than just a ?, parse the val
          ExpressionParser qp = new BoundExpressionParser();
          qp.setExpression(val);
          colList.addAll(qp.parse());
        }
      }
    } else {
      // expression is in the format of:  ...col1 = ? , col2 = ?...
      // so we'll have to move left to right from the ? looking for the field name

      int startIdx = 0;
      Collection<Integer> indexes = getArgumentIndexes();
      for (int qIdx : indexes) {
        String chunk = expression.substring(startIdx, qIdx);

        if (logger.isDebugEnabled())
          logger.debug("Chunk [" + chunk + "]");

        int idx = chunk.length() - 1;
        int fieldStartIdx = -1;
        int fieldEndIdx = -1;

        boolean found = false;
        boolean inFunction = false;
        while (!found && (idx >= 0)) {
          char c = chunk.charAt(idx);

          if (fieldEndIdx == -1) {
            // if the character is a ( this might be a function like UPPER(), try to parse that out
            if (!inFunction && c == '(') {
              inFunction = true;
            } else if (inFunction && COMPARE_CHARS.indexOf(c) != -1) {
              inFunction = false;
            }

            // till we find the first char of the end of the field name, ignore compare chars
            if (!inFunction && COMPARE_CHARS.indexOf(c) == -1) {
              // found a char, must be the end of the field name
              fieldEndIdx = idx;
            }
          } else {
            // if we find a separator, we've reached the beginning of the field name
            if (SEPARATOR_CHARS.indexOf(c) >= 0) {
              fieldStartIdx = idx + 1;
              found = true;
            }
          }
          idx--;
        }
        if (found) {
          String col = chunk.substring(fieldStartIdx, fieldEndIdx + 1);
          colList.add(col);
        }

        // move the starting index to where the ? was
        startIdx = qIdx + 1;
      }
    }

    return colList;
  }
353502
public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
		List<T> result = new ArrayList<T>();
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = getconnnection();
			ps = con.prepareStatement(sql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject((i + 1), args[i]);
				}
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			while (rs.next()) {
				T obj = clz.newInstance();
				for (int i = 1; i <= columnCount; i++) {
					String columnName = rsmd.getColumnName(i);
					String methodName = "set" + columnName.substring(0, 1).toUpperCase()
							+ columnName.substring(1, columnName.length());
					Method method[] = clz.getMethods();
					for (Method meth : method) {
						if (methodName.equals(meth.getName())) {
							meth.invoke(obj, rs.getObject(i));
						}
					}
				}
				result.add(obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} finally {
			close(rs, ps, con);
		}
		return result;
	}
435155
public Set<String> getInvokedTables() throws ParseException {

	// Read all SQL statements from input
	ZStatement st;
	Set<String> tables = new HashSet<String>();

	while ((st = parser.readStatement()) != null) {
	    this.sql = st.toString();
	    if (st instanceof ZQuery) { // An SQL query: query the DB
		getInvokedTables((ZQuery) st, tables);
	    }
	    break;
	}
	return tables;
    }
1017072
public void batchUpdate(String sql,List<Object[]> paramsList){
		
		BatchUpdateSetter batchUpdateSetter = new BatchUpdateSetter(paramsList);
		
		getProxy().batchUpdate(sql, batchUpdateSetter);
	}
109160
@Override
    public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
    {
        checkParameterBounds(parameterIndex);
        switch(targetSqlType)
        {
            case Types.TINYINT:
                setByte(parameterIndex, ((Byte)x).byteValue());
                break;
            case Types.SMALLINT:
                setShort(parameterIndex, ((Short)x).shortValue());
                break;
            case Types.INTEGER:
                setInt(parameterIndex, ((Integer)x).intValue());
                break;
            case Types.BIGINT:
                setLong(parameterIndex, ((Long)x).longValue());
                break;
            case Types.DOUBLE:
                setDouble(parameterIndex, ((Double)x).doubleValue());
                break;
            case Types.DECIMAL:
                setBigDecimal(parameterIndex, (BigDecimal)x);
                break;
            case Types.TIMESTAMP:
                setTimestamp(parameterIndex, (Timestamp)x);
                break;
            case Types.VARBINARY:
            case Types.VARCHAR:
            case Types.NVARCHAR:
                setString(parameterIndex, (String)x);
                break;
            case Types.OTHER:
                setObject(parameterIndex, x);
                break;
            default:
                throw SQLError.get(SQLError.ILLEGAL_ARGUMENT);
        }
    }
1124250
@Override
    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
        Statement appliedStatement = base;
        for (MethodRule rule : methodRuleChain) {
            appliedStatement = rule.apply(appliedStatement, method, target);
        }

        return statement(appliedStatement, target);

    }
635396
private ImmutableList<TargetAtom> prepareTargetQuery(MapItem predicateSubjectMap, List<MapItem> predicateObjectMapsList) {
		// Create the body of the CQ
		ImmutableList.Builder<TargetAtom> bodyBuilder = ImmutableList.builder();

		// Store concept in the body, if any
		ImmutableTerm subjectTerm = createSubjectTerm(predicateSubjectMap);
		if (!predicateSubjectMap.getPredicateIRI().equals(OWL.THING)) {
			TargetAtom concept = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateSubjectMap.getPredicateIRI());
			bodyBuilder.add(concept);
		}

		// Store attributes and roles in the body
		//List<Term> distinguishVariables = new ArrayList<Term>();
		for (MapItem predicateObjectMap : predicateObjectMapsList) {
			if (predicateObjectMap.isObjectMap()) { // if an attribute
				ImmutableTerm objectTerm = createObjectTerm(getColumnName(predicateObjectMap), predicateObjectMap.getDataType());
				TargetAtom attribute = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectTerm);
				bodyBuilder.add(attribute);
				//distinguishVariables.add(objectTerm);
			} else if (predicateObjectMap.isRefObjectMap()) { // if a role
				ImmutableFunctionalTerm objectRefTerm = createRefObjectTerm(predicateObjectMap);
				TargetAtom role = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectRefTerm);
				bodyBuilder.add(role);
			}
		}
		// Create the head
		//int arity = distinguishVariables.size();
		//Function head = termFactory.getFunction(termFactory.getTermType(OBDALibConstants.QUERY_HEAD, arity), distinguishVariables);

		// Create and return the conjunctive query
		return bodyBuilder.build();
	}
308995
public void setFields(List<Field> fields) throws SqlParseException {
		/*
		zhongshu-comment select * from tbl_a;
		select * 这种sql语句的select.getFields().size()为0
		 */
		if (select.getFields().size() > 0) {
			ArrayList<String> includeFields = new ArrayList<String>();
			ArrayList<String> excludeFields = new ArrayList<String>();

			for (Field field : fields) {
				if (field instanceof MethodField) { //zhongshu-comment MethodField是Field的子类，而且Field也就只有MethodField这一个子类了
					MethodField method = (MethodField) field;
					if (method.getName().toLowerCase().equals("script")) {
						/*
						zhongshu-comment scripted_field only allows script(name,script) or script(name,lang,script)
						script类型的MethodField是不会加到include和exclude中的
						 */
						handleScriptField(method);
					} else if (method.getName().equalsIgnoreCase("include")) {
					    String f;
						for (KVValue kvValue : method.getParams()) {
							//zhongshu-comment select a,b,c 中的a、b、c字段add到includeFields中
                            f = kvValue.value.toString();
                            fieldNames.add(f);
                            includeFields.add(f);
						}
					} else if (method.getName().equalsIgnoreCase("exclude")) {
						for (KVValue kvValue : method.getParams()) {
							excludeFields.add(kvValue.value.toString()) ;
						}
					}
				} else if (field != null) {
                    fieldNames.add(field.getName());
					includeFields.add(field.getName());
				}
			}

			request.setFetchSource(
					includeFields.toArray(new String[includeFields.size()]),
					excludeFields.toArray(new String[excludeFields.size()])
			);
		}
	}
479787
public <T> List<T> selectList(String sql, Class<T> resultType) {
        String msId;
        if (resultType == null) {
            msId = msUtils.select(sql);
        } else {
            msId = msUtils.select(sql, resultType);
        }
        return sqlSession.selectList(msId);
    }
159626
public <T> List<List<T>> queryTypedResults(String sql, String[] args,
			Integer limit) {
		return db.queryTypedResults(sql, args, limit);
	}
679591
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException{
		//dynamic change catalog name
		sql = changeCatalog(sql);
		try{
			return jdbcTemplate.query(sql, rowMapper);
		}catch(DataAccessException e){
			logger.error("Error SQL: " + sql);
			throw e;
		}
	}
1305392
public List queryMultiObject(Collection queryParams, String sqlquery) throws Exception {
		Debug.logVerbose("[JdonFramework]--> enter queryMultiObject ", module);
		Connection c = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List list = new ArrayList();
		try {
			c = dataSource.getConnection();
			ps = c.prepareStatement(sqlquery, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			Debug.logVerbose("[JdonFramework]" + sqlquery, module);
			jdbcUtil.setQueryParams(queryParams, ps);

			rs = ps.executeQuery();
			list = jdbcUtil.extract(rs);
		} catch (SQLException se) {
			throw new SQLException("SQLException: " + se.getMessage());
		} catch (Exception ex) {
			Debug.logError(ex, module);
			throw new Exception(ex);
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException quiet) {
				}
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException quiet) {
				}
			if (c != null)
				try {
					c.close();
				} catch (SQLException quiet) {
				}
		}
		return list;
	}
899998
@SuppressWarnings("unchecked")
    public <N extends Object> List<N> findOneColumn(String sql, List<?> params, final int mapperColumnIndex) {

        if (sql == null) {
            recordLog(" param sql is null!");
        }

        // 查询
        return findBySQL(sql, params, new RowMapper<N>() {
            public N mapRow(ResultSet rs, int count) throws SQLException {
                return (N) (rs.getObject(mapperColumnIndex));
            }
        });
    }
808019
public static List<Object[]> queryObjectArrays(String sql, Object[] params)
      throws YankSQLException {

    return queryObjectArrays(YankPoolManager.DEFAULT_POOL_NAME, sql, params);
  }
943801
public static <E, S> List<E> copy(List<S> sourceList, Class<E> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            return Collections.emptyList();
        }
        List<E> list = new ArrayList<>(sourceList.size());

        if (!(sourceList instanceof ArrayList)) {
            sourceList = new ArrayList<>(sourceList);
        }

        for (S source : sourceList) {
            E e = copy(source, targetClass);
            if (e != null) {
                list.add(e);
            }
        }
        return list;
    }
351211
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws SQLException{
		if (logger.isDebugEnabled()) {
			logger.debug("Executing SQL statement [" + sql + "]");
		}
		
		Connection connection = null;
		Statement stm = null;
		ResultSet rs = null;
		
		ArrayList<T> result = new ArrayList<T>();
		
		try{
			connection = ds.getConnection();
			stm = connection.createStatement();			
			rs = stm.executeQuery(sql);
			
			while(rs.next()){
				result.add( rowMapper.map(rs) );
			}
			
		} catch (SQLException e) {
			throw e;
		}finally{
			if(rs!=null) rs.close();
			if(stm!=null) stm.close();
			if(connection!=null) connection.close();			
		}
		
		return result;
	}