execute a SQL Statement against CFML Scopes

@param pc PageContext of the Request
@param sql
@param maxrows
@return result
@throws PageException
507904
public Query execute(Vector statements, PageContext pc, SQL sql, int maxrows) throws PageException {
	// parse sql
	if (statements.size() != 1) throw new DatabaseException("only one SQL Statement allowed at time", null, null, null);
	ZQuery query = (ZQuery) statements.get(0);

	// single table
	if (query.getFrom().size() == 1) {
	    return testExecute(pc, sql, getSingleTable(pc, query), query, maxrows);

	}
	// multiple table
	throw new DatabaseException("can only work with single tables yet", null, null, null);

    }
57659
public static Object call(PageContext pc, Object coll, Collection.Key methodName, Object[] args, short[] types, String[] strTypes) throws PageException {

	// look for members
	short type;
	String strType;
	Map<Key, FunctionLibFunction> members = null;
	for (int i = 0; i < types.length; i++) {
	    type = types[i];
	    strType = strTypes[i];
	    members = getMembers(pc, type);
	    FunctionLibFunction member = members.get(methodName);
	    if (member != null) {
		List<FunctionLibFunctionArg> _args = member.getArg();
		if (args.length < _args.size()) {
		    ArrayList<Ref> refs = new ArrayList<Ref>();

		    int pos = member.getMemberPosition();
		    FunctionLibFunctionArg flfa;
		    Iterator<FunctionLibFunctionArg> it = _args.iterator();
		    int glbIndex = 0, argIndex = -1;
		    while (it.hasNext()) {
			glbIndex++;
			flfa = it.next();
			if (glbIndex == pos) {
			    refs.add(new Casting(strType, type, coll));
			}
			else if (args.length > ++argIndex) { // careful, argIndex is only incremented when condition above is false
			    refs.add(new Casting(flfa.getTypeAsString(), flfa.getType(), args[argIndex]));
			}
		    }
		    return new BIFCall(coll, member, refs.toArray(new Ref[refs.size()])).getValue(pc);
		}

	    }
	}

	// do reflection
	if (pc.getConfig().getSecurityManager().getAccess(lucee.runtime.security.SecurityManager.TYPE_DIRECT_JAVA_ACCESS) == lucee.runtime.security.SecurityManager.VALUE_YES) {
	    if (!(coll instanceof Undefined)) {
		Object res = callMethod(coll, methodName, args);
		if (res != DEFAULT) return res;
	    }
	}

	// merge
	if (types.length > 1) {
	    Map<Key, FunctionLibFunction> tmp;
	    members = null;
	    for (int i = 0; i < types.length; i++) {
		tmp = getMembers(pc, types[i]);
		if (members == null) members = tmp;
		else {
		    Iterator<Entry<Key, FunctionLibFunction>> it = tmp.entrySet().iterator();
		    Entry<Key, FunctionLibFunction> e;
		    while (it.hasNext()) {
			e = it.next();
			members.put(e.getKey(), e.getValue());
		    }
		}
	    }
	}
	Set<Key> set = members.keySet();
	String msg = ExceptionUtil.similarKeyMessage(set.toArray(new Key[set.size()]), methodName.getString(), "function", "functions", "Object", true);
	throw new ExpressionException(msg);
	// throw new ExpressionException("No matching function member ["+methodName+"] found, available
	// function members are ["+
	// lucee.runtime.type.util.ListUtil.sort(CollectionUtil.getKeyList(members.keySet().iterator(),
	// ","),"textnocase","asc",",")+"]");
    }
138407
protected Object interpretPart(PageContext pc, ParserString cfml) throws PageException {
	this.cfml = cfml;
	init(pc);

	cfml.removeSpace();
	return assignOp().getValue(pc);
    }
629842
protected void executeQueryPrologue(boolean isBatch) throws SQLException {
    executing = true;
    if (closed) {
      throw new SQLException("execute() is called on closed statement");
    }
    protocol.prolog(maxRows, protocol.getProxy() != null, connection, this);
    if (queryTimeout != 0 && (!canUseServerTimeout || isBatch)) {
      setTimerTask(isBatch);
    }
  }
268083
public ResultSetAndStatement executeSQL(
        final String sql,
        ClassDescriptor cld,
        ValueContainer[] values,
        boolean scrollable)
        throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled()) logger.debug("executeSQL: " + sql);
        final boolean isStoredprocedure = isStoredProcedure(sql);
        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try
        {
            stmt = sm.getPreparedStatement(cld, sql,
                    scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);
            if (isStoredprocedure)
            {
                // Query implemented as a stored procedure, which must return a result set.
                // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
                getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
                sm.bindValues(stmt, values, 2);
                stmt.execute();
                rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
            }
            else
            {
                sm.bindValues(stmt, values, 1);
                rs = stmt.executeQuery();
            }

            // as we return the resultset for further operations, we cannot release the statement yet.
            // that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)
            return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()
            {
                public Query getQueryInstance()
                {
                    return null;
                }

                public int getColumnIndex(FieldDescriptor fld)
                {
                    return JdbcType.MIN_INT;
                }

                public String getStatement()
                {
                    return sql;
                }
            });
        }
        catch (PersistenceBrokerException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            logger.error("PersistenceBrokerException during the execution of the SQL query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);
        }
    }
124749
boolean executeInternal(String sql,
                          Map<String, ParameterBindingDTO> parameterBindings)
  throws SQLException
  {
    raiseSQLExceptionIfStatementIsClosed();
    connection.injectedDelay();

    logger.debug("execute: {}", sql);

    String trimmedSql = sql.trim();

    if (trimmedSql.length() >= 20
        && trimmedSql.toLowerCase().startsWith("set-sf-property"))
    {
      // deprecated: sfsql
      executeSetProperty(sql);
      return false;
    }

    SFBaseResultSet sfResultSet;
    try
    {
      sfResultSet = sfStatement.execute(sql, parameterBindings,
                                        SFStatement.CallingMethod.EXECUTE);
      sfResultSet.setSession(this.connection.getSfSession());
      if (resultSet != null)
      {
        openResultSets.add(resultSet);
      }
      resultSet = new SnowflakeResultSetV1(sfResultSet, this);
      queryID = sfResultSet.getQueryId();

      // Legacy behavior treats update counts as result sets for single-
      // statement execute, so we only treat update counts as update counts
      // if JDBC_EXECUTE_RETURN_COUNT_FOR_DML is set, or if a statement
      // is multi-statement
      if (!sfResultSet.getStatementType().isGenerateResultSet() &&
          (connection.getSfSession().isExecuteReturnCountForDML() ||
           sfStatement.hasChildren()))
      {
        updateCount = ResultUtil.calculateUpdateCount(sfResultSet);
        if (resultSet != null)
        {
          openResultSets.add(resultSet);
        }
        resultSet = null;
        return false;
      }

      updateCount = NO_UPDATES;
      return true;
    }
    catch (SFException ex)
    {
      throw new SnowflakeSQLException(ex.getCause(),
                                      ex.getSqlState(), ex.getVendorCode(), ex.getParams());
    }
  }
536296
protected void executeStatements(TestContext context) {
        for (String stmt : statements) {
            try {
                final String toExecute = context.replaceDynamicContentInString(stmt.trim());

                if (log.isDebugEnabled()) {
                    log.debug("Executing PLSQL statement: " + toExecute);
                }

                getJdbcTemplate().execute(toExecute);

                log.info("PLSQL statement execution successful");
            } catch (DataAccessException e) {
                if (ignoreErrors) {
                    log.warn("Ignoring error while executing PLSQL statement: " + e.getMessage());
                    continue;
                } else {
                    throw new CitrusRuntimeException("Failed to execute PLSQL statement", e);
                }
            }
        }
    }
209138
public static void checkSQLRestriction(DatasourceConnection dc, SQL sql) throws PageException {
	Array sqlparts = ListUtil.listToArrayRemoveEmpty(SQLUtil.removeLiterals(sql.getSQLString()), " \t" + System.getProperty("line.separator"));

	// print.ln(List.toStringArray(sqlparts));
	DataSource ds = dc.getDatasource();
	if (!ds.hasAllow(DataSource.ALLOW_ALTER)) checkSQLRestriction(dc, "alter", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_CREATE)) checkSQLRestriction(dc, "create", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_DELETE)) checkSQLRestriction(dc, "delete", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_DROP)) checkSQLRestriction(dc, "drop", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_GRANT)) checkSQLRestriction(dc, "grant", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_INSERT)) checkSQLRestriction(dc, "insert", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_REVOKE)) checkSQLRestriction(dc, "revoke", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_SELECT)) checkSQLRestriction(dc, "select", sqlparts, sql);
	if (!ds.hasAllow(DataSource.ALLOW_UPDATE)) checkSQLRestriction(dc, "update", sqlparts, sql);
    }
5915
public QueryResults execute() throws JspCoreException, SQLException {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        ;
        QueryResults qs = null;
        // verify all parameters
        verify();

        // invoke the compute method of QueryResults passing it the SQL resultset
        // the QueryResults will get all the data from the result set and cache it in
        // its private datastructures
        try {
            conn = getJdbcConnection();
            //conn = DriverManager.getConnection(url,user,passwd);
            stmt = conn.createStatement();
            int mrows = getMaxRows();
            if (mrows > 0)
                stmt.setMaxRows(mrows);
            rs = stmt.executeQuery(getQueryString());
            qs = new QueryResults();
            qs.compute(rs);
        }
        catch (SQLException e) {
            //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.execute", "73", this);
            throw e;
        }
        finally { // always free up database resources
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        }
        setResults(qs);
        return qs;
    }
740599
@Override
  public final void executeQuery(final String pQuery) throws Exception {
    try {
      if (getLogger().getIsShowDebugMessagesFor(getClass())
        && getLogger().getDetailLevel() > 30000) {
        getLogger().debug(null, SrvDatabase.class, "try to execute query: "
          + pQuery);
      }
      this.sqliteDatabase.execSQL(pQuery);
    } catch (Exception ex) {
      String msg = ex.getMessage() + ", query:\n" + pQuery;
      ExceptionWithCode ewc = new ExceptionWithCode(SrvDatabase.SQL_EXEC_ERROR,
        msg);
      ewc.setStackTrace(ex.getStackTrace());
      throw ewc;
    }
  }
840141
public static Object call(PageContext pc) throws PageException {
	Component ac = pc.getActiveComponent();
	if (ac != null) {
	    return call(pc, ac);
	}

	return new StructImpl();
    }
171325
private static boolean _full(PageContext pc) {
	pc = ThreadLocalPageContext.get(pc);
	if (pc == null) return false;
	return pc.getCurrentTemplateDialect() != CFMLEngine.DIALECT_CFML || ((PageContextImpl) pc).getFullNullSupport();
    }
1225859
public void setQuery(String query) throws PageException {
	this.query = Caster.toQuery(pageContext.getVariable(query));
    }
1304157
private void doGetTLDs() throws PageException {
	lucee.runtime.type.Query qry = new QueryImpl(
		new String[] { "displayname", "namespace", "namespaceseparator", "shortname", "type", "description", "uri", "elclass", "elBundleName", "elBundleVersion",
			"source" },
		new String[] { "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar" }, 0, "tlds");

	int dialect = "lucee".equalsIgnoreCase(getString("dialect", "cfml")) ? CFMLEngine.DIALECT_LUCEE : CFMLEngine.DIALECT_CFML;

	TagLib[] libs = config.getTLDs(dialect);
	for (int i = 0; i < libs.length; i++) {
	    qry.addRow();
	    qry.setAt("displayname", i + 1, libs[i].getDisplayName());
	    qry.setAt("namespace", i + 1, libs[i].getNameSpace());
	    qry.setAt("namespaceseparator", i + 1, libs[i].getNameSpaceSeparator());
	    qry.setAt("shortname", i + 1, libs[i].getShortName());
	    qry.setAt("type", i + 1, libs[i].getType());
	    qry.setAt("description", i + 1, libs[i].getDescription());
	    qry.setAt("uri", i + 1, Caster.toString(libs[i].getUri()));
	    qry.setAt("elclass", i + 1, libs[i].getELClassDefinition().getClassName());
	    qry.setAt("elBundleName", i + 1, libs[i].getELClassDefinition().getName());
	    qry.setAt("elBundleVersion", i + 1, libs[i].getELClassDefinition().getVersionAsString());
	    qry.setAt("source", i + 1, StringUtil.emptyIfNull(libs[i].getSource()));
	}
	pageContext.setVariable(getString("admin", action, "returnVariable"), qry);
    }
602624
public static Object call(PageContext pc, Object[] objArr) throws PageException {
	if (objArr.length < 3) throw new ExpressionException("invalid call of a CFML Based built in function");

	// translate arguments
	String filename = Caster.toString((((FunctionValue) objArr[0]).getValue()));
	Collection.Key name = KeyImpl.toKey((((FunctionValue) objArr[1]).getValue()));
	boolean isweb = Caster.toBooleanValue((((FunctionValue) objArr[2]).getValue()));

	// function from archive may come without mapping definition
	int offset = 3;
	String mappingName = "mapping-function";
	// clearly no mapping definition
	if (objArr.length > 3 && objArr[3] instanceof FunctionValue) {
	    FunctionValue fv = (FunctionValue) objArr[3];
	    if (fv.getName().equals("__mapping")) {
		mappingName = Caster.toString(fv.getValue());
		offset = 4;
	    }
	}

	UDF udf = loadUDF(pc, filename, mappingName, name, isweb);
	Struct meta = udf.getMetaData(pc);
	boolean callerScopes = (meta == null) ? false : Caster.toBooleanValue(meta.get("callerScopes", Boolean.FALSE), false);
	boolean caller = meta == null ? false : Caster.toBooleanValue(meta.get(KeyConstants._caller, Boolean.FALSE), false);

	Struct namedArguments = null, cs = null;
	if (callerScopes) {

	    cs = new StructImpl();
	    if (pc.undefinedScope().getCheckArguments()) {
		cs.set(KeyConstants._local, pc.localScope().duplicate(false));
		cs.set(KeyConstants._arguments, pc.argumentsScope().duplicate(false));
	    }
	}

	Object[] arguments = null;
	if (objArr.length <= offset) arguments = ArrayUtil.OBJECT_EMPTY;
	else if (objArr[offset] instanceof FunctionValue) {
	    FunctionValue fv;
	    namedArguments = new StructImpl(Struct.TYPE_LINKED);
	    if (callerScopes) namedArguments.setEL(KeyConstants._caller, cs);
	    else if (caller) namedArguments.setEL(KeyConstants._caller, Duplicator.duplicate(pc.undefinedScope(), false));
	    for (int i = offset; i < objArr.length; i++) {
		fv = toFunctionValue(name, objArr[i]);
		namedArguments.set(fv.getName(), fv.getValue());
	    }
	}
	else {
	    int off = (caller || callerScopes ? 3 : 4);
	    arguments = new Object[objArr.length - off];
	    if (callerScopes) arguments[0] = cs;
	    else if (caller) arguments[0] = Duplicator.duplicate(pc.undefinedScope(), false);
	    for (int i = offset; i < objArr.length; i++) {
		arguments[i - off] = toObject(name, objArr[i]);
	    }
	}
	// execute UDF
	if (namedArguments == null) {
	    return ((UDFImpl) udf).call(pc, name, arguments, false);
	}

	return ((UDFImpl) udf).callWithNamedValues(pc, name, namedArguments, false);
    }
158253
@SuppressWarnings("resource")
    private CmsSqlConsoleResults executeQuery(String sentence, String poolName) throws SQLException {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;

        CmsSqlManager sqlManager = m_sqlManager;

        try {
            conn = sqlManager.getConnection(poolName);
            stmt = sqlManager.getPreparedStatementForSql(conn, sentence);
            res = stmt.executeQuery();

            // add headings
            ResultSetMetaData metadata = res.getMetaData();
            List<String> heading = new ArrayList<>();
            for (int i = 0; i < metadata.getColumnCount(); i++) {
                heading.add(metadata.getColumnName(i + 1));
            }
            List<List<Object>> data = new ArrayList<List<Object>>();

            // add contents
            while (res.next()) {
                List<Object> row = new ArrayList<Object>();
                for (int i = 0; i < metadata.getColumnCount(); i++) {
                    Object value = res.getObject(i + 1);
                    if ((value instanceof String)
                        || (value instanceof Integer)
                        || (value instanceof Long)
                        || (value instanceof Float)
                        || (value instanceof Double)) {
                        row.add(value);
                    } else if (value == null) {
                        row.add(null);
                    } else {
                        row.add(String.valueOf(value));
                    }
                }
                data.add(row);
            }
            return new CmsSqlConsoleResults(heading, data);
        } finally {
            sqlManager.closeAll(null, conn, stmt, res);
        }
    }
250711
private void doGetDatasourceSetting() throws PageException {
	Struct sct = new StructImpl();
	pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
	sct.set("psq", Caster.toBoolean(config.getPSQL()));
    }