Get a string containing a SQL statement and any parameters for a given
AdHocPlannedStatement. Used for debugging and logging.
481855
public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) {
        final int MAX_PARAM_LINE_CHARS = 120;

        StringBuilder sb = new StringBuilder();
        String sql = new String(statement.sql, Charsets.UTF_8);
        sb.append(sql);

        Object[] params = paramsForStatement(statement, userparams);
        // convert params to strings of a certain max length
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];

            String paramLineStr = String.format("    Param %d: %s", i, param.toString());
            // trim param line if it's silly long
            if (paramLineStr.length() > MAX_PARAM_LINE_CHARS) {
                paramLineStr = paramLineStr.substring(0, MAX_PARAM_LINE_CHARS - 3);
                paramLineStr += "...";
            }

            sb.append('\n').append(paramLineStr);
        }

        return sb.toString();
    }
347456
public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,
                                                  boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)
            throws PersistenceBrokerException
    {
        try
        {
            return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
302034
private Object getParameterValue(ControlBeanContext context, Method method, Object[] args) {
        Object value;
        try {
            value = context.getParameterValue(method, _nameQualifiers[0], args);
        } catch (IllegalArgumentException iae) {
            throw new ControlException("Invalid argument name in SQL statement: " + _nameQualifiers[0], iae);
        }

        for (int i = 1; i < _nameQualifiers.length; i++) {
            // handle maps, properties, and fields...
            value = extractValue(value, _nameQualifiers[i - 1], _nameQualifiers[i]);
        }
        return value;
    }
1372729
public void getSQLFromField(PreparedStatement statement, int iType, int iParamColumn) throws SQLException
    {
        if (this.isNull())
            statement.setNull(iParamColumn, Types.BIT);
        else
        {
            String strBitSupported = DBConstants.TRUE;
            if (this.getRecord() != null)
                if (this.getRecord().getTable() != null)
                    if (this.getRecord().getTable().getDatabase().getProperties() != null)
                strBitSupported = (String)this.getRecord().getTable().getDatabase().getProperties().get(SQLParams.BIT_TYPE_SUPPORTED);
            if (DBConstants.TRUE.equals(strBitSupported))
                statement.setBoolean(iParamColumn, this.getState());
            else
                statement.setByte(iParamColumn, (this.getState() ? (byte)1 : (byte)0));
        }
    }
255381
def check_string(sql_string, add_semicolon=False):
    
    prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon)
    success, msg = ecpg.check_syntax(prepped_sql)
    return success, msg
120984
private String readClobAsString(Clob logClob) throws SQLException {
    if (logClob == null) {
      return StringUtils.EMPTY;
    }
    long length = logClob.length();
    return logClob.getSubString(1, (int) length);
  }
542740
@Override
	public Map<String, Object> getOutParams(final CallableStatement callableStatement) throws SQLException {
		Map<String, Object> out = new HashMap<>();
		Parameter[] bindParameters = getBindParameters();
		int parameterIndex = 1;
		for (Parameter parameter : bindParameters) {
			if (parameter instanceof OutParameter) {
				String key = parameter.getParameterName();
				out.put(key, getSqlFilterManager().doOutParameter(key, callableStatement.getObject(parameterIndex)));
			}
			parameterIndex++;
		}

		LOG.debug("Stored procedure out parameter[{}]", out);
		return out;
	}
352377
public static AdHocPlannedStatement compileAdHocSQL(PlannerTool plannerTool,
                                                        String sqlStatement,
                                                        boolean inferPartitioning,
                                                        Object userPartitionKey,
                                                        ExplainMode explainMode,
                                                        boolean isLargeQuery,
                                                        boolean isSwapTables,
                                                        Object[] userParamSet)
                                                                throws AdHocPlanningException
    {
        assert(plannerTool != null);
        assert(sqlStatement != null);
        final PlannerTool ptool = plannerTool;

        // Take advantage of the planner optimization for inferring single partition work
        // when the batch has one statement.
        StatementPartitioning partitioning = null;

        if (inferPartitioning) {
            partitioning = StatementPartitioning.inferPartitioning();
        }
        else if (userPartitionKey == null) {
            partitioning = StatementPartitioning.forceMP();
        }
        else {
            partitioning = StatementPartitioning.forceSP();
        }

        try {
            return ptool.planSql(sqlStatement,
                                 partitioning,
                                 explainMode != ExplainMode.NONE,
                                 userParamSet,
                                 isSwapTables,
                                 isLargeQuery);
        }
        catch (Exception e) {
            throw new AdHocPlanningException(e.getMessage());
        }
        catch (StackOverflowError error) {
            // Overly long predicate expressions can cause a
            // StackOverflowError in various code paths that may be
            // covered by different StackOverflowError/Error/Throwable
            // catch blocks. The factors that determine which code path
            // and catch block get activated appears to be platform
            // sensitive for reasons we do not entirely understand.
            // To generate a deterministic error message regardless of
            // these factors, purposely defer StackOverflowError handling
            // for as long as possible, so that it can be handled
            // consistently by a minimum number of high level callers like
            // this one.
            // This eliminates the need to synchronize error message text
            // in multiple catch blocks, which becomes a problem when some
            // catch blocks lead to re-wrapping of exceptions which tends
            // to adorn the final error text in ways that are hard to track
            // and replicate.
            // Deferring StackOverflowError handling MAY mean ADDING
            // explicit StackOverflowError catch blocks that re-throw
            // the error to bypass more generic catch blocks
            // for Error or Throwable on the same try block.
            throw new AdHocPlanningException("Encountered stack overflow error. " +
                    "Try reducing the number of predicate expressions in the query.");
        }
        catch (AssertionError ae) {
            String msg = "An unexpected internal error occurred when planning a statement issued via @AdHoc.  "
                    + "Please contact VoltDB at support@voltdb.com with your log files.";
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);
            ae.printStackTrace(writer);
            String stackTrace = stringWriter.toString();

            adhocLog.error(msg + "\n" + stackTrace);
            throw new AdHocPlanningException(msg);
        }
    }
940212
CallableStatement getCallableStatement(final SqlContext sqlContext) throws SQLException {
		Connection conn = null;
		if (sqlContext.getDbAlias() != null) {
			conn = getConnection(sqlContext.getDbAlias());
		} else {
			conn = getConnection();
		}
		if (conn == null) {
			throw new IllegalArgumentException(sqlContext.getDbAlias());
		}

		CallableStatement stmt = sqlFilterManager.doCallableStatement(
				sqlContext,
				conn.prepareCall(sqlContext.getExecutableSql(), sqlContext.getResultSetType(),
						sqlContext.getResultSetConcurrency()));
		return stmt;
	}
187306
protected PreparedStatement getPreparedStatement(final SqlContext sqlContext) throws SQLException {
		PreparedStatement stmt = ((LocalTransactionManager) transactionManager).getPreparedStatement(sqlContext);
		// プロパティ設定
		applyProperties(stmt);
		return stmt;
	}
1344131
public static String fillLogParams(String sql, Map<Object, Object> logParams) {
		StringBuilder result = new StringBuilder();
		Map<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams);

		Iterator<Object> it = tmpLogParam.values().iterator();
		boolean inQuote = false;
		boolean inQuote2 = false;
		char[] sqlChar = sql != null ? sql.toCharArray() : new char[]{};

		for (int i=0; i < sqlChar.length; i++){
			if (sqlChar[i] == '\''){
				inQuote = !inQuote;
			}
			if (sqlChar[i] == '"'){
				inQuote2 = !inQuote2;
			}

			if (sqlChar[i] == '?' && !(inQuote || inQuote2)){
				if (it.hasNext()){
					result.append(prettyPrint(it.next()));
				} else {
					result.append('?');
				}
			} else {
				result.append(sqlChar[i]);
			}
		}


		return result.toString();
	}
923871
public static ParsedSql parseSqlStatement(final String sql) {
        Assert.notNull(sql, "SQL must not be null");

        Set<String> namedParameters = new HashSet<>();
        String sqlToUse = sql;
        List<ParameterHolder> parameterList = new ArrayList<>();

        char[] statement = sql.toCharArray();
        int namedParameterCount = 0;
        int unnamedParameterCount = 0;
        int totalParameterCount = 0;

        int escapes = 0;
        int i = 0;
        while (i < statement.length) {
            int skipToPosition;
            while (i < statement.length) {
                skipToPosition = skipCommentsAndQuotes(statement, i);
                if (i == skipToPosition) {
                    break;
                } else {
                    i = skipToPosition;
                }
            }
            if (i >= statement.length) {
                break;
            }
            char c = statement[i];
            if (c == ':' || c == '&') {
                int j = i + 1;
                if (j < statement.length && statement[j] == ':' && c == ':') {
                    // Postgres-style "::" casting operator should be skipped
                    i = i + 2;
                    continue;
                }
                String parameter;
                if (j < statement.length && c == ':' && statement[j] == '{') {
                    // :{x} style parameter
                    while (j < statement.length && !('}' == statement[j])) {
                        j++;
                        if (':' == statement[j] || '{' == statement[j]) {
                            throw new CommonRuntimeException("Parameter name contains invalid character '" +
                                    statement[j] + "' at position " + i + " in statement: " + sql);
                        }
                    }
                    if (j >= statement.length) {
                        throw new CommonRuntimeException(
                                "Non-terminated named parameter declaration at position " + i + " in statement: " + sql);
                    }
                    if (j - i > 3) {
                        parameter = sql.substring(i + 2, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j + 1, parameter);
                    }
                    j++;
                } else {
                    while (j < statement.length && !isParameterSeparator(statement[j])) {
                        j++;
                    }
                    if (j - i > 1) {
                        parameter = sql.substring(i + 1, j);
                        namedParameterCount = addNewNamedParameter(namedParameters, namedParameterCount, parameter);
                        totalParameterCount = addNamedParameter(parameterList, totalParameterCount, escapes, i, j, parameter);
                    }
                }
                i = j - 1;
            } else {
                if (c == '\\') {
                    int j = i + 1;
                    if (j < statement.length && statement[j] == ':') {
                        // escaped ":" should be skipped
                        sqlToUse = sqlToUse.substring(0, i - escapes) + sqlToUse.substring(i - escapes + 1);
                        escapes++;
                        i = i + 2;
                        continue;
                    }
                }
                if (c == '?') {
                    int j = i + 1;
                    if (j < statement.length && (statement[j] == '?' || statement[j] == '|' || statement[j] == '&')) {
                        // Postgres-style "??", "?|", "?&" operator should be skipped
                        i = i + 2;
                        continue;
                    }
                    unnamedParameterCount++;
                    totalParameterCount++;
                }
            }
            i++;
        }

        ParsedSql parsedSql = new ParsedSql(sqlToUse);
        parsedSql.setParameterList(parameterList);
        parsedSql.setNamedParameterCount(namedParameterCount);
        parsedSql.setUnnamedParameterCount(unnamedParameterCount);
        parsedSql.setTotalParameterCount(totalParameterCount);
        return parsedSql;
    }
674950
private <L extends Collection<JQLPlaceHolder>> L extractPlaceHoldersFromVariableStatement(final JQLContext jqlContext, String jql, final L result) {
		final One<Boolean> valid = new One<>();

		if (!StringUtils.hasText(jql))
			return result;

		valid.value0 = false;

		analyzeVariableStatementInternal(jqlContext, jql, new JqlBaseListener() {

			@Override
			public void enterBind_parameter(Bind_parameterContext ctx) {
				String parameter;
				if (ctx.bind_parameter_name() != null) {
					parameter = ctx.bind_parameter_name().getText();
				} else {
					parameter = ctx.getText();
				}
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, parameter));
			}

			@Override
			public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
				result.add(new JQLPlaceHolder(JQLPlaceHolderType.DYNAMIC_SQL, ctx.bind_parameter_name().getText()));
			}

		});
		return result;
	}
367334
public static String getSQLTypeString(int sqlType) {
        switch (sqlType) {
            case Types.ARRAY:
                return "ARRAY (" + sqlType + ')'; 

            case Types.BIGINT:
                return "BIGINT (" + sqlType + ')'; 

            case Types.BINARY:
                return "BINARY (" + sqlType + ')'; 

            case Types.BIT:
                return "BIT (" + sqlType + ')'; 

            case Types.BLOB:
                return "BLOB (" + sqlType + ')'; 

            case Types.BOOLEAN: 
                return "BOOLEAN (" + sqlType + ')'; 

            case Types.CHAR:
                return "CHAR (" + sqlType + ')'; 

            case Types.CLOB:
                return "CLOB (" + sqlType + ')'; 

            case Types.DATALINK: 
                return "DATALINK (" + sqlType + ')'; 

            case Types.DATE:
                return "DATE (" + sqlType + ')'; 

            case Types.DECIMAL:
                return "DECIMAL (" + sqlType + ')'; 

            case Types.DISTINCT:
                return "DISTINCT (" + sqlType + ')'; 

            case Types.DOUBLE:
                return "DOUBLE (" + sqlType + ')'; 

            case Types.FLOAT:
                return "FLOAT (" + sqlType + ')'; 

            case Types.INTEGER:
                return "INTEGER (" + sqlType + ')'; 

            case Types.JAVA_OBJECT:
                return "JAVA OBJECT (" + sqlType + ')'; 

            case Types.LONGNVARCHAR: 
                return "LONGNVARCHAR (" + sqlType + ')'; 

            case Types.LONGVARBINARY:
                return "LONGVARBINARY (" + sqlType + ')'; 

            case Types.LONGVARCHAR:
                return "LONGVARCHAR (" + sqlType + ')'; 

            case Types.NCHAR: 
                return "NCHAR (" + sqlType + ')'; 

            case Types.NCLOB: 
                return "NCLOB (" + sqlType + ')'; 

            case Types.NULL:
                return "NULL (" + sqlType + ')'; 

            case Types.NUMERIC:
                return "NUMERIC (" + sqlType + ')'; 

            case Types.NVARCHAR: 
                return "NVARCHAR (" + sqlType + ')'; 

            case Types.OTHER:
                return "OTHER (" + sqlType + ')'; 

            case Types.REAL:
                return "REAL (" + sqlType + ')'; 

            case Types.REF:
                return "REF (" + sqlType + ')'; 

            case Types.ROWID: 
                return "ROWID (" + sqlType + ')'; 

            case Types.SMALLINT:
                return "SMALLINT (" + sqlType + ')'; 

            case Types.SQLXML: 
                return "SQLXML (" + sqlType + ')'; 

            case Types.STRUCT:
                return "STRUCT (" + sqlType + ')'; 

            case Types.TIME:
                return "TIME (" + sqlType + ')'; 

            case Types.TIMESTAMP:
                return "TIMESTAMP (" + sqlType + ')'; 

            case Types.TINYINT:
                return "TINYINT (" + sqlType + ')'; 

            case Types.VARBINARY:
                return "VARBINARY (" + sqlType + ')'; 

            case Types.VARCHAR:
                return "VARCHAR (" + sqlType + ')'; 
        }

        return "UNKNOWN SQL TYPE (" + sqlType + ')'; 
    }
354417
protected Collection<String> getParameters(final CreateSpatialIndexStatement statement) {
      final Collection<String> parameters = new ArrayList<String>();
      if (StringUtils.trimToNull(statement.getGeometryType()) != null) {
         final String gType = getGtype(statement.getGeometryType().trim());
         if (gType != null) {
            parameters.add("layer_gtype=" + gType);
         }
      }
      if (StringUtils.trimToNull(statement.getTablespace()) != null) {
         parameters.add("tablespace=" + statement.getTablespace().trim());
      }
      return parameters;
   }
633743
static int countQuestionMarkParameters(String sql) {
        // was originally using regular expressions, but they didn't work well
        // for ignoring parameter-like strings inside quotes.
        int count = 0;
        int length = sql.length();
        boolean inSingleQuote = false;
        boolean inDoubleQuote = false;
        for (int i = 0; i < length; i++) {
            char c = sql.charAt(i);
            if (inSingleQuote) {
                if (c == '\'') {
                    inSingleQuote = false;
                }
            } else if (inDoubleQuote) {
                if (c == '"') {
                    inDoubleQuote = false;
                }
            } else {
                if (c == '\'') {
                    inSingleQuote = true;
                } else if (c == '"') {
                    inDoubleQuote = true;
                } else if (c == '?') {
                    count++;
                }
            }
        }
        return count;
    }
1062637
public static String stringForQuery(SQLiteStatement prog, String[] selectionArgs) {
        prog.bindAllArgsAsStrings(selectionArgs);
        return prog.simpleQueryForString();
    }