Arrays.asList cannot be reliably used for SQL parameters on MyBatis < 3.3.0
492768
public static <T> List<T> asArrayList(T[] values) {
    ArrayList<T> result = new ArrayList<T>();
    Collections.addAll(result, values);

    return result;
  }
751188
@Override
	public int[] executeBatch(String sql, List<Object> list) {
		if (list.isEmpty() == true) {
			return new int[] {};
		}
		Iterator<Object> iterator = list.iterator();
		if (iterator.hasNext() == false) {
			return new int[] {};
		}
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			PropertyDesc.cacheModeOn();
			connection = getConnection();
			Object object = iterator.next();

			Map<String, ParameterValue> values = new HashMap<>();
			addValues(values, object);
			sql = getSql(sql, dialect);
			ps = createPreparedStatement(connection, sql, values, ExecuteType.UPDATE, dialect, null);
			PreparedStatementUtil.addBatch(ps, sqlLogRegistry);

			while (iterator.hasNext()) {
				object = iterator.next();

				Node node = parse(sql);
				values = new HashMap<>();
				addValues(values, object);
				CommandContext ctx = new CommandContext(dialect);
				ctx.addArgs(values);
				node.accept(ctx);
				List<Object> bindVariables = ctx.getBindVariables();
				List<Integer> bindVariableTypes = ctx.getBindVariableTypes();
				bindArgs(ps, bindVariables, bindVariableTypes, ExecuteType.UPDATE, dialect);
				PreparedStatementUtil.addBatch(ps, sqlLogRegistry);
			}
			return PreparedStatementUtil.executeBatch(ps, sqlLogRegistry);
		} finally {
			PropertyDesc.cacheModeOff();
			try {
				StatementUtil.close(ps);
			} finally {
				ConnectionUtil.close(connection);
			}
		}
	}
314281
@Override
	public SqlContext paramList(final String parameterName, final Supplier<List<?>> supplier) {
		return param(new Parameter(parameterName, supplier.get()));
	}
687080
public int execute(String sql, List<Object> params) {
        return this.execute(sql, params.toArray());
    }
808019
public static List<Object[]> queryObjectArrays(String sql, Object[] params)
      throws YankSQLException {

    return queryObjectArrays(YankPoolManager.DEFAULT_POOL_NAME, sql, params);
  }
333514
private void fillColumnValuesMap(List<Map<String, Object>> results, Map<String, List<String>> columnValuesMap) {
        for (Map<String, Object> row : results) {
            for (Entry<String, Object> column : row.entrySet()) {
                String columnValue;
                String columnName = column.getKey();
                if (!columnValuesMap.containsKey(columnName)) {
                    columnValuesMap.put(columnName, new ArrayList<String>());
                }

                if (column.getValue() instanceof byte[]) {
                    columnValue = Base64.encodeBase64String((byte[]) column.getValue());
                } else {
                    columnValue = column.getValue() == null ? null : column.getValue().toString();
                }

                columnValuesMap.get(columnName).add((columnValue));
            }
        }
    }

    /**
     * Gets the script validator implementation either autowired from application context
     * or if not set here a default implementation.
     */
    private SqlResultSetScriptValidator getScriptValidator() {
        if (validator != null) {
            return validator;
        } else {
            return new GroovySqlResultSetValidator();
        }
    }

    /**
     * Constructs a delimited string from multiple row values in result set in order to
     * set this expression as variable value.
     *
     * @param rowValues the list of values representing the allResultRows for a column in the result set.
     * @return the variable value as delimited string or single value.
     */
    private String constructVariableValue(List<String> rowValues) {
        if (CollectionUtils.isEmpty(rowValues)) {
            return "";
        } else if (rowValues.size() == 1) {
            return rowValues.get(0) == null ? NULL_VALUE : rowValues.get(0);
        } else {
            StringBuilder result = new StringBuilder();

            Iterator<String> it = rowValues.iterator();

            result.append(it.next());
            while (it.hasNext()) {
                String nextValue = it.next();
                result.append(";" + (nextValue == null ? NULL_VALUE : nextValue));
            }

            return result.toString();
        }
    }

    /**
     * Validates the database result set. At first script validation is done (if any was given).
     * Afterwards the control result set validation is performed.
     *
     * @param columnValuesMap map containing column names as keys and list of string as retrieved values from db
     * @param allResultRows list of all result rows retrieved from database
     * @return success flag
     * @throws UnknownElementException
     * @throws ValidationException
     */
    private void performValidation(final Map<String, List<String>> columnValuesMap,
            List<Map<String, Object>> allResultRows, TestContext context)
            throws UnknownElementException, ValidationException {
        // apply script validation if specified
        if (scriptValidationContext != null) {
            getScriptValidator().validateSqlResultSet(allResultRows, scriptValidationContext, context);
        }

        //now apply control set validation if specified
        if (CollectionUtils.isEmpty(controlResultSet)) {
            return;
        }
        performControlResultSetValidation(columnValuesMap, context);
        log.info("SQL query validation successful: All values OK");
    }

    private void performControlResultSetValidation(final Map<String, List<String>> columnValuesMap, TestContext context)
            throws CitrusRuntimeException {
        for (Entry<String, List<String>> controlEntry : controlResultSet.entrySet()) {
            String columnName = controlEntry.getKey();

            if (columnValuesMap.containsKey(columnName.toLowerCase())) {
                columnName = columnName.toLowerCase();
            } else if (columnValuesMap.containsKey(columnName.toUpperCase())) {
                columnName = columnName.toUpperCase();
            } else if (!columnValuesMap.containsKey(columnName)) {
                throw new CitrusRuntimeException("Could not find column '" + columnName + "' in SQL result set");
            }

            List<String> resultColumnValues = columnValuesMap.get(columnName);
            List<String> controlColumnValues = controlEntry.getValue();

            // first check size of column values (representing number of allResultRows in result set)
            if (resultColumnValues.size() != controlColumnValues.size()) {
                throw new CitrusRuntimeException("Validation failed for column: '" +  columnName + "' " +
                        "expected rows count: " + controlColumnValues.size() + " but was " + resultColumnValues.size());
            }

            Iterator<String> it = resultColumnValues.iterator();
            for (String controlValue : controlColumnValues) {
                String resultValue = it.next();
                //check if controlValue is variable or function (and resolve it)
                controlValue = context.replaceDynamicContentInString(controlValue);

                validateSingleValue(columnName, controlValue, resultValue, context);
            }
        }
    }

    /**
     * Does some simple validation on the SQL statement.
     * @param stmt The statement which is to be validated.
     */
    protected void validateSqlStatement(String stmt) {
        if (!stmt.toLowerCase().startsWith("select")) {
            throw new CitrusRuntimeException("Missing keyword SELECT in statement: " + stmt);
        }
    }

    protected void validateSingleValue(String columnName, String controlValue, String resultValue, TestContext context) {
        // check if value is ignored
        if (controlValue.equals(Citrus.IGNORE_PLACEHOLDER)) {
            if (log.isDebugEnabled()) {
                log.debug("Ignoring column value '" + columnName + "(resultValue)'");
            }
            return;
        }
        
        if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue)) {
            ValidationMatcherUtils.resolveValidationMatcher(columnName, resultValue, controlValue, context);
            return;
        }
        
        if (resultValue == null) {
            if (isCitrusNullValue(controlValue)) {
                if (log.isDebugEnabled()) {
                    log.debug("Validating database value for column: ''" +
                            columnName + "'' value as expected: NULL - value OK");
                }
                return;
            } else {
                throw new ValidationException("Validation failed for column: '" +  columnName + "'"
                        + "found value: NULL expected value: " + controlValue);
            }
        }

        if (resultValue.equals(controlValue)) {
            if (log.isDebugEnabled()) {
                log.debug("Validation successful for column: '" + columnName +
                        "' expected value: " + controlValue + " - value OK");
            }
        } else {
            throw new ValidationException("Validation failed for column: '" +  columnName + "'"
                    + " found value: '"
                    + resultValue
                    + "' expected value: "
                    + ((controlValue.length()==0) ? NULL_VALUE : controlValue));
        }
    }
1263089
public <E extends Object> int executeSQL(String sql, List<E> params) {
        if (params == null || params.size() == 0) {
            return jdbcTemplate.update(sql);
        } else {
            return jdbcTemplate.update(sql, params.toArray(new Object[params.size()]));
        }
    }
199785
private String buildAddSql(final JSONObject jsonObject, final List<Object> paramlist, final StringBuilder sql) throws Exception {
        String ret = null;

        if (!jsonObject.has(Keys.OBJECT_ID)) {
            if (!(KEY_GEN instanceof DBKeyGenerator)) {
                ret = (String) KEY_GEN.gen();
                jsonObject.put(Keys.OBJECT_ID, ret);
            }
        } else {
            ret = jsonObject.getString(Keys.OBJECT_ID);
        }

        setProperties(jsonObject, paramlist, sql);

        return ret;
    }
703642
public int[] execute(Iterable<String> sqls, int batchSize) throws SQLException {
		if (sqls == null) {
			return null;
		}
		
		List<int[]> tmpResultList = new ArrayList<int[]>();
		
		Statement stmt = null;
		try {
			int counter = 0;
			stmt = conn.createStatement();
			for (String sql : sqls) {
				stmt.addBatch(sql);
				counter ++;
				if (batchSize > 0 && counter % batchSize == 0) {
					tmpResultList.add(stmt.executeBatch());
				}
			}
			tmpResultList.add(stmt.executeBatch());

		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage());
			}
		}
		
		int[] result = new int[0];
		for (int[] tmpResult : tmpResultList) {
			int[] tmpArray = new int[result.length + tmpResult.length];
			
			System.arraycopy(result, 0, tmpArray, 0, result.length);
			System.arraycopy(tmpResult, 0, tmpArray, result.length, tmpResult.length);
			
			result = tmpArray;
		}

		return result;
	}
444563
function convertParamValues(parsedSql, values) {
    var ret = [];
    _.each(parsedSql.params, function(param) {
      if( !_.has(values, param.name) ) {
        throw new Error("No value found for parameter: " + param.name);
      }
      ret.push(values[param.name]);
    });
    return ret;
  }
1209756
static void setParameters(PreparedStatement ps, List<Parameter> params, boolean namesAllowed)
            throws SQLException {
        for (int i = 1; i <= params.size(); i++) {
            if (params.get(i - 1).hasName() && !namesAllowed)
                throw new SQLException("named parameter found but sql does not contain names");
            Object o = params.get(i - 1).value();
            try {
                if (o == null)
                    ps.setObject(i, null);
                else if (o == Database.NULL_CLOB)
                    ps.setNull(i, Types.CLOB);
                else if (o == Database.NULL_BLOB)
                    ps.setNull(i, Types.BLOB);
                else {
                    Class<?> cls = o.getClass();
                    if (Clob.class.isAssignableFrom(cls)) {
                        setClob(ps, i, o, cls);
                    } else if (Blob.class.isAssignableFrom(cls)) {
                        setBlob(ps, i, o, cls);
                    } else if (Calendar.class.isAssignableFrom(cls)) {
                        Calendar cal = (Calendar) o;
                        Timestamp t = new java.sql.Timestamp(cal.getTimeInMillis());
                        ps.setTimestamp(i, t, cal);
                    } else if (Time.class.isAssignableFrom(cls)) {
                        Calendar cal = Calendar.getInstance();
                        ps.setTime(i, (Time) o, cal);
                    } else if (Timestamp.class.isAssignableFrom(cls)) {
                        Calendar cal = Calendar.getInstance();
                        ps.setTimestamp(i, (Timestamp) o, cal);
                    } else if (java.sql.Date.class.isAssignableFrom(cls)) {
                        Calendar cal = Calendar.getInstance();
                        ps.setDate(i, (java.sql.Date) o, cal);
                    } else if (java.util.Date.class.isAssignableFrom(cls)) {
                        Calendar cal = Calendar.getInstance();
                        java.util.Date date = (java.util.Date) o;
                        ps.setTimestamp(i, new java.sql.Timestamp(date.getTime()), cal);
                    } else
                        ps.setObject(i, o);
                }
            } catch (SQLException e) {
                log.debug("{} when setting ps.setObject({},{})", e.getMessage(), i, o);
                throw e;
            }
        }
    }
121606
static function handleList( $parameters = array(), $asCount = false )
    {
        $parameters = array_merge( array( 'as_object' => true,
                                          'is_valid' => null,
                                          'offset' => false,
                                          'limit' => false,
                                          'only_published' => false ),
                                   $parameters );
        $asObject = $parameters['as_object'];
        $isValid = $parameters['is_valid'];
        $offset = $parameters['offset'];
        $limit = $parameters['limit'];
        $onlyPublished = $parameters['only_published'];
        $limitArray = null;
        if ( !$asCount and $offset !== false and $limit !== false )
            $limitArray = array( 'offset' => $offset,
                                 'length' => $limit );
        $conditions = array();
        if( $isValid === false ) $isValid = 0;
        if ( $isValid !== null )
        {
            $conditions['is_valid'] = $isValid;
        }
        if ( count( $conditions ) == 0 )
            $conditions = null;

        if ( $onlyPublished )  // Only fetch published urls
        {
            $conditionQuery = "";
            if ( $isValid !== null )
            {
                $isValid = (int) $isValid;
                $conditionQuery = " AND ezurl.is_valid=$isValid ";
            }
            $db = eZDB::instance();
            $cObjAttrVersionColumn = eZPersistentObject::getShortAttributeName( $db, eZURLObjectLink::definition(), 'contentobject_attribute_version' );

            if ( $asCount )
            {
                $urls = $db->arrayQuery( "SELECT count( DISTINCT ezurl.id ) AS count
                                            FROM
                                                 ezurl,
                                                 ezurl_object_link,
                                                 ezcontentobject_attribute,
                                                 ezcontentobject_version
                                            WHERE
                                                 ezurl.id                                     = ezurl_object_link.url_id
                                             AND ezurl_object_link.contentobject_attribute_id = ezcontentobject_attribute.id
                                             AND ezurl_object_link.$cObjAttrVersionColumn     = ezcontentobject_attribute.version
                                             AND ezcontentobject_attribute.contentobject_id   = ezcontentobject_version.contentobject_id
                                             AND ezcontentobject_attribute.version            = ezcontentobject_version.version
                                             AND ezcontentobject_version.status               = " . eZContentObjectVersion::STATUS_PUBLISHED . "
                                                 $conditionQuery" );
                return $urls[0]['count'];
            }
            else
            {
                $query = "SELECT DISTINCT ezurl.*
                            FROM
                                  ezurl,
                                  ezurl_object_link,
                                  ezcontentobject_attribute,
                                  ezcontentobject_version
                            WHERE
                                  ezurl.id                                     = ezurl_object_link.url_id
                              AND ezurl_object_link.contentobject_attribute_id = ezcontentobject_attribute.id
                              AND ezurl_object_link.$cObjAttrVersionColumn     = ezcontentobject_attribute.version
                              AND ezcontentobject_attribute.contentobject_id   = ezcontentobject_version.contentobject_id
                              AND ezcontentobject_attribute.version            = ezcontentobject_version.version
                              AND ezcontentobject_version.status               = " . eZContentObjectVersion::STATUS_PUBLISHED . "
                             $conditionQuery";

                if ( !$offset && !$limit )
                {
                    $urlArray = $db->arrayQuery( $query );
                }
                else
                {
                    $urlArray = $db->arrayQuery( $query, array( 'offset' => $offset,
                                                                 'limit'  => $limit ) );
                }
                if ( $asObject )
                {
                    $urls = array();
                    foreach ( $urlArray as $url )
                    {
                        $urls[] = new eZURL( $url );
                    }
                    return $urls;
                }
                else
                    $urls = $urlArray;
                return $urls;
            }
        }
        else
        {
            if ( $asCount )
            {
                $urls = eZPersistentObject::fetchObjectList( eZURL::definition(),
                                                             array(),
                                                             $conditions,
                                                             false,
                                                             null,
                                                             false,
                                                             false,
                                                             array( array( 'operation' => 'count( id )',
                                                                           'name' => 'count' ) ) );
                return $urls[0]['count'];
            }
            else
            {
                return eZPersistentObject::fetchObjectList( eZURL::definition(),
                                                            null, $conditions, null, $limitArray,
                                                            $asObject );
            }
        }
    }
278850
@SafeVarargs
    @NullSafe
    public static <T> List<T> asList(T... a) {
        return N.isNullOrEmpty(a) ? N.<T> emptyList() : Arrays.asList(a);
    }
810830
public int[] executeBatch() throws SQLException {
        final boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<int[]> callback = new SQLExecuteCallback<int[]>(getDatabaseType(), isExceptionThrown) {
            
            @Override
            protected int[] executeSQL(final RouteUnit routeUnit, final Statement statement, final ConnectionMode connectionMode) throws SQLException {
                return statement.executeBatch();
            }
        };
        List<int[]> results = executeCallback(callback);
        if (isAccumulate()) {
            return accumulate(results);
        } else {
            return results.get(0);
        }
    }
1032674
public Object[] executeMultiplePreparedStatements(String[] statements, Collection inParams) throws SQLException {
		Object[] result;
		if (statements.length == inParams.size()) {
			result = new Object[inParams.size()];
			Connection conn = null;

			conn = dataSource.getConnection();
			conn.setAutoCommit(false);

			try {
				Iterator inParamsIt = inParams.iterator();
				int count = 0;
				while (inParamsIt.hasNext()) {
					Object[] params = (Object[]) inParamsIt.next();
					result[count] = executePreparedStatement(statements[count], new StatementInput(params), false, conn);
					count++;
				}
				conn.commit();
			} catch (SQLException e) {
				throw e;
			} finally {
				if (conn != null) {
					conn.close();
				}
			}
		} else {
			throw new SQLException("number of arguments doesn't match");
		}
		return result;
	}
1079581
public static <T> QueryParameterValue array(T[] array, StandardSQLTypeName type) {
    List<QueryParameterValue> listValues = new ArrayList<>();
    for (T obj : array) {
      listValues.add(QueryParameterValue.of(obj, type));
    }
    return QueryParameterValue.newBuilder()
        .setArrayValues(listValues)
        .setType(StandardSQLTypeName.ARRAY)
        .setArrayType(type)
        .build();
  }
903785
private void executeBatch(Results results, final List<String> queries)
      throws SQLException {

    if (!options.useBatchMultiSend) {

      String sql = null;
      SQLException exception = null;

      for (int i = 0; i < queries.size() && !isInterrupted(); i++) {

        try {

          sql = queries.get(i);
          writer.startPacket(0);
          writer.write(COM_QUERY);
          writer.write(sql);
          writer.flush();
          getResult(results);

        } catch (SQLException sqlException) {
          if (exception == null) {
            exception = logQuery.exceptionWithQuery(sql, sqlException, explicitClosed);
            if (!options.continueBatchOnError) {
              throw exception;
            }
          }
        } catch (IOException e) {
          if (exception == null) {
            exception = handleIoException(e);
            if (!options.continueBatchOnError) {
              throw exception;
            }
          }
        }
      }
      stopIfInterrupted();

      if (exception != null) {
        throw exception;
      }
      return;
    }
    initializeBatchReader();
    new AbstractMultiSend(this, writer, results, queries) {

      @Override
      public void sendCmd(PacketOutputStream pos, Results results,
          List<ParameterHolder[]> parametersList, List<String> queries, int paramCount,
          BulkStatus status,
          PrepareResult prepareResult)
          throws IOException {

        String sql = queries.get(status.sendCmdCounter);
        pos.startPacket(0);
        pos.write(COM_QUERY);
        pos.write(sql);
        pos.flush();
      }

      @Override
      public SQLException handleResultException(SQLException qex, Results results,
          List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter,
          int sendCmdCounter, int paramCount, PrepareResult prepareResult) {

        String sql = queries.get(currentCounter + sendCmdCounter);
        return logQuery.exceptionWithQuery(sql, qex, explicitClosed);

      }

      @Override
      public int getParamCount() {
        return -1;
      }

      @Override
      public int getTotalExecutionNumber() {
        return queries.size();
      }

    }.executeBatch();

  }