Generates the SQL statement to drop the spatial index if it exists.

@param statement
the drop spatial index statement.
@param database
the database.
@return the drop spatial index statement, if the index exists.
552883
public Sql[] generateSqlIfExists(final DropSpatialIndexStatement statement,
         final Database database) {
      final String catalogName = statement.getTableCatalogName();
      final String schemaName = statement.getTableSchemaName();
      final String tableName = statement.getTableName();
      final SpatialIndexExistsPrecondition precondition = new SpatialIndexExistsPrecondition();
      precondition.setCatalogName(catalogName);
      precondition.setSchemaName(schemaName);
      precondition.setTableName(tableName);
      final DatabaseObject example = precondition.getExample(database, tableName);
      try {
         // If a spatial index exists on the table, drop it.
         if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
            return generateSql(statement, database, null);
         }
      } catch (final Exception e) {
         throw new UnexpectedLiquibaseException(e);
      }
      return new Sql[0];
   }
1197579
StatementDMQL compileInsertStatement(RangeVariable[] outerRanges) {

        read();
        readThis(Tokens.INTO);

        boolean[] columnCheckList;
        int[]     columnMap;
        int       colCount;
        Table     table                = readTableName();
        boolean   overridingUser       = false;
        boolean   overridingSystem     = false;
        int       enforcedDefaultIndex = table.getIdentityColumnIndex();
        boolean   assignsToIdentity    = false;

        columnCheckList = null;
        columnMap       = table.getColumnMap();
        colCount        = table.getColumnCount();

        int position = getPosition();

        if (!table.isInsertable()) {
            throw Error.error(ErrorCode.X_42545);
        }

        Table baseTable = table.getBaseTable();

        switch (token.tokenType) {

            case Tokens.DEFAULT : {
                read();
                readThis(Tokens.VALUES);

                Expression insertExpression = new Expression(OpTypes.ROW,
                    new Expression[]{});

                insertExpression = new Expression(OpTypes.TABLE,
                                                  new Expression[]{
                                                      insertExpression });
                columnCheckList = table.getNewColumnCheckList();

                for (int i = 0; i < table.colDefaults.length; i++) {
                    if (table.colDefaults[i] == null
                            && table.identityColumn != i) {
                        throw Error.error(ErrorCode.X_42544);
                    }
                }

                StatementDMQL cs = new StatementInsert(session, table,
                                                       columnMap,
                                                       insertExpression,
                                                       columnCheckList,
                                                       compileContext);

                return cs;
            }
            case Tokens.OPENBRACKET : {
                int brackets = readOpenBrackets();

                if (brackets == 1) {
                    boolean isQuery = false;

                    switch (token.tokenType) {

                        case Tokens.WITH :
                        case Tokens.SELECT :
                        case Tokens.TABLE : {
                            rewind(position);

                            isQuery = true;

                            break;
                        }
                        default :
                    }

                    if (isQuery) {
                        break;
                    }

                    OrderedHashSet columnNames = new OrderedHashSet();

                    readSimpleColumnNames(columnNames, table);
                    readThis(Tokens.CLOSEBRACKET);

                    colCount  = columnNames.size();
                    columnMap = table.getColumnIndexes(columnNames);

                    if (token.tokenType != Tokens.VALUES
                            && token.tokenType != Tokens.OVERRIDING) {
                        break;
                    }

                    // $FALL-THROUGH$
                } else {
                    rewind(position);

                    break;
                }
            }

            // $FALL-THROUGH$
            case Tokens.OVERRIDING : {
                if (token.tokenType == Tokens.OVERRIDING) {
                    read();

                    if (token.tokenType == Tokens.USER) {
                        read();

                        overridingUser = true;
                    } else if (token.tokenType == Tokens.SYSTEM) {
                        read();

                        overridingSystem = true;
                    } else {
                        unexpectedToken();
                    }
                }

                if (token.tokenType != Tokens.VALUES) {
                    break;
                }
            }

            // $FALL-THROUGH$
            case Tokens.VALUES : {
                read();

                columnCheckList = table.getColumnCheckList(columnMap);

                Expression insertExpressions =
                    XreadContextuallyTypedTable(colCount);
                HsqlList unresolved =
                    insertExpressions.resolveColumnReferences(outerRanges,
                        null);

                ExpressionColumn.checkColumnsResolved(unresolved);
                insertExpressions.resolveTypes(session, null);
                setParameterTypes(insertExpressions, table, columnMap);

                if (table != baseTable) {
                    int[] baseColumnMap = table.getBaseTableColumnMap();
                    int[] newColumnMap  = new int[columnMap.length];

                    ArrayUtil.projectRow(baseColumnMap, columnMap,
                                         newColumnMap);

                    columnMap = newColumnMap;
                }

                Expression[] rowList = insertExpressions.nodes;

                for (int j = 0; j < rowList.length; j++) {
                    Expression[] rowArgs = rowList[j].nodes;

                    for (int i = 0; i < rowArgs.length; i++) {
                        Expression e = rowArgs[i];

                        if (enforcedDefaultIndex == columnMap[i]) {
                            assignsToIdentity = true;

                            if (e.getType() != OpTypes.DEFAULT) {
                                if (table.identitySequence.isAlways()) {
                                    if (!overridingUser && !overridingSystem) {
                                        throw Error.error(ErrorCode.X_42543);
                                    }
                                } else {
/*
                                    if (overridingUser) {
                                        throw Trace.error(
                                            Trace.SQL_DEFAULT_CLAUSE_REQUITED);
                                    }
*/
                                }
                            }
                        }

                        if (e.isParam()) {
                            e.setAttributesAsColumn(
                                table.getColumn(columnMap[i]), true);
                        } else if (e.getType() == OpTypes.DEFAULT) {
                            if (table.colDefaults[i] == null
                                    && table.identityColumn != columnMap[i]) {
                                throw Error.error(ErrorCode.X_42544);
                            }
                        }
                    }
                }

                if (!assignsToIdentity
                        && (overridingUser || overridingSystem)) {
                    unexpectedTokenRequire(Tokens.T_OVERRIDING);
                }

                StatementDMQL cs = new StatementInsert(session, table,
                                                       columnMap,
                                                       insertExpressions,
                                                       columnCheckList,
                                                       compileContext);

                return cs;
            }
            case Tokens.WITH :
            case Tokens.SELECT :
            case Tokens.TABLE : {
                break;
            }
            default : {
                throw unexpectedToken();
            }
        }

        columnCheckList = table.getColumnCheckList(columnMap);

        QueryExpression queryExpression = XreadQueryExpression();

        queryExpression.setAsTopLevel();
        queryExpression.resolve(session, outerRanges);

        if (colCount != queryExpression.getColumnCount()) {
            throw Error.error(ErrorCode.X_42546);
        }

        if (table != baseTable) {
            int[] baseColumnMap = table.getBaseTableColumnMap();
            int[] newColumnMap  = new int[columnMap.length];

            ArrayUtil.projectRow(baseColumnMap, columnMap, newColumnMap);

            columnMap = newColumnMap;
        }

        if (enforcedDefaultIndex != -1
                && ArrayUtil.find(columnMap, enforcedDefaultIndex) > -1) {
            if (table.identitySequence.isAlways()) {
                if (!overridingUser && !overridingSystem) {
                    throw Error.error(ErrorCode.X_42543);
                }
            } else {
/*
                if (overridingUser) {
                    throw Trace.error(
                        Trace.SQL_DEFAULT_CLAUSE_REQUITED);
                }
*/
            }
        } else if (overridingUser || overridingSystem) {
            unexpectedTokenRequire(Tokens.T_OVERRIDING);
        }

        StatementDMQL cs = new StatementInsert(session, table, columnMap,
                                               columnCheckList,
                                               queryExpression,
                                               compileContext);

        return cs;
    }
510122
private void executeStatement(String statement) throws SQLException {
		logger.entering(CLASSNAME, "executeStatement", statement);

		Connection conn = getConnection();
		PreparedStatement ps = null;

		ps = conn.prepareStatement(statement);
		ps.executeUpdate();

		cleanupConnection(conn, ps);
		logger.exiting(CLASSNAME, "executeStatement");
	}
1178267
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
        ResultSet rs = null;
        int id = 0;
        try {
            rs = statement.getGeneratedKeys();
            if (!rs.next()) {
                throw new DatabaseException("Unable to get primary key for inserted row");
            }
            id = rs.getInt(1);
        } catch (SQLException ex) {
            throw new DatabaseException("Unable to get primary key for inserted row");
        } finally {
            closeResultSet(rs);
        }
        return id;
    }
696061
public static ParameterizedAnalyticsQuery parameterized(final String statement,
        final JsonArray positionalParams) {
        return new ParameterizedAnalyticsQuery(statement, positionalParams, null, null);
    }
840907
private Statement statement(final Statement base) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                before();
                doStateTransition(State.BEFORE_EXECUTED);
                try {
                    base.evaluate();
                } finally {
                    after();
                    doStateTransition(State.AFTER_EXECUTED);
                }
            }
        };
    }
881352
function BaseStatement(
    statementOptions, context, services, connectionConfig)
{
  // call super
  EventEmitter.call(this);

  // validate input
  Errors.assertInternal(Util.isObject(statementOptions));
  Errors.assertInternal(Util.isObject(context));

  context.services         = services;
  context.connectionConfig = connectionConfig;
  context.isFetchingResult = true;

  // TODO: add the parameters map to the statement context

  var statement = this;

  /**
   * Returns this statement's SQL text.
   *
   * @returns {String}
   */
  this.getSqlText = function()
  {
    return context.sqlText;
  };

  /**
   * Returns the current status of this statement.
   *
   * @returns {String}
   */
  this.getStatus = function()
  {
    return context.isFetchingResult ? states.FETCHING : states.COMPLETE;
  };

  /**
   * Returns the columns produced by this statement.
   *
   * @returns {Object[]}
   */
  this.getColumns = function()
  {
    return context.result ? context.result.getColumns() : undefined;
  };

  /**
   * Given a column identifier, returns the corresponding column. The column
   * identifier can be either the column name (String) or the column index
   * (Number). If a column is specified and there is more than one column with
   * that name, the first column with the specified name will be returned.
   *
   * @param {String | Number} columnIdentifier
   *
   * @returns {Object}
   */
  this.getColumn = function(columnIdentifier)
  {
    return context.result ? context.result.getColumn(columnIdentifier) :
        undefined;
  };

  /**
   * Returns the number of rows returned by this statement.
   *
   * @returns {Number}
   */
  this.getNumRows = function()
  {
    return context.result ? context.result.getReturnedRows() : undefined;
  };

  /**
   * Returns the number of rows updated by this statement.
   *
   * @returns {Number}
   */
  this.getNumUpdatedRows = function()
  {
    return context.result ? context.result.getNumUpdatedRows() : undefined;
  };

  /**
   * Returns an object that contains information about the values of the
   * current warehouse, current database, etc., when this statement finished
   * executing.
   *
   * @returns {Object}
   */
  this.getSessionState = function()
  {
    return context.result ? context.result.getSessionState() : undefined;
  };

  /**
   * Returns the request id that was used when the statement was issued.
   *
   * @returns {String}
   */
  this.getRequestId = function()
  {
    return context.requestId;
  };

  /**
   * Returns the statement id generated by the server for this statement.
   * If the statement is still executing and we don't know the statement id
   * yet, this method will return undefined.
   *
   * @returns {String}
   */
  this.getStatementId = function()
  {
    return context.statementId;
  };

  /**
   * Cancels this statement if possible.
   *
   * @param {Function} [callback]
   */
  this.cancel = function(callback)
  {
    sendCancelStatement(context, statement, callback);
  };

  /**
   * Issues a request to get the statement result again.
   *
   * @param {Function} callback
   */
  context.refresh = function(callback)
  {
    // pick the appropriate function to get the result based on whether we
    // have the statement id or request id (we should have at least one)
    var sendRequestFn = context.statementId ?
        sendRequestPostExec : sendRequestPreExec;

    // the current result error might be transient,
    // so issue a request to get the result again
    sendRequestFn(context, function(err, body)
    {
      // refresh the result
      context.onStatementRequestComp(err, body);

      // if a callback was specified, invoke it
      if (Util.isFunction(callback))
      {
        callback(context);
      }
    });
  };

  /**
   * Called when the statement request is complete.
   *
   * @param err
   * @param body
   */
  context.onStatementRequestComp = function(err, body)
  {
    // if we already have a result or a result error, we invoked the complete
    // callback once, so don't invoke it again
    var suppressComplete = context.result || context.resultError;

    // clear the previous result error
    context.resultError = null;

    // if there was no error, call the success function
    if (!err)
    {
      context.onStatementRequestSucc(body);
    }
    else
    {
      // save the error
      context.resultError = err;

      // if we don't have a statement id and we got a response from GS, extract
      // the statement id from the data
      if (!context.statementId &&
          Errors.isOperationFailedError(err) && err.data)
      {
        context.statementId = err.data.queryId;
      }
    }

    // we're no longer fetching the result
    context.isFetchingResult = false;

    if (!suppressComplete)
    {
      // emit a complete event
      context.emit('statement-complete', Errors.externalize(err), statement);

      // if a complete function was specified, invoke it
      if (Util.exists(context.complete))
      {
        invokeStatementComplete(statement, context);
      }
    }
    else
    {
      Logger.getInstance().debug('refreshed result of statement with %s',
          context.requestId ?
              Util.format('request id = %s', context.requestId) :
              Util.format('statement id = %s', context.statementId));
    }
  };

  /**
   * Called when the statement request is successful. Subclasses must provide
   * their own implementation.
   *
   * @param {Object} body
   */
  context.onStatementRequestSucc = function(body){};
}
1029111
public static void closeStatement(Statement statement) {
        try {
            if (statement != null && !statement.isClosed()) {

                statement.close();
            }
        } catch (SQLException ex) {
            LOGGER.trace(statement.toString(), ex);
        }
    }
1194707
public PreparedStatement prepareStatement(final String sql) throws SQLException {
    return internalPrepareStatement(sql,
        ResultSet.TYPE_FORWARD_ONLY,
        ResultSet.CONCUR_READ_ONLY,
        Statement.NO_GENERATED_KEYS);
  }
647453
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) {
        Statement stmt = createStatement(configName, connection);
        try {
            log.debug("Executing statement [" + description + "]");
            
            List<String> stmtsToExecute = Stream.of(statements.split(";"))
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
            
            if ( log.isTraceEnabled()) {
                log.trace("These statements will be executed:");
                stmtsToExecute.forEach(s -> log.trace("Statement: [" + s + "]"));
            }
            
            for ( String currentStatement : stmtsToExecute) {
                stmt.execute(currentStatement);
                log.trace("Executing statement: " + currentStatement + " OK!");
            }
            
        } catch (SQLException e) {
            throw new ChorusException(
                    String.format("Failed while executing statement [%s] on database + %s [%s]", description, configName, e.toString(), e)
            );
        }
    }
847233
public void close() {
		try {
			Statement statement = set.getStatement();
			if (statement!=null && !statement.isClosed())
				statement.close();
			// Normally not necessary (according to the JDBC standard)
			if (set!=null && !set.isClosed())
				set.close();
		} catch (SQLException e) {
			// NO-OP
		}
	}
1217373
public static QueryCriterion deserialize(String statement){
        char [] delimeter = {' ', '\t', ',', '[', ']'};
        List<String> cmdList = splitStringByDelimeters(statement, delimeter, true);
        List<String> tokenList = filterDelimeterElement(cmdList, delimeter);
        if(tokenList.size() == 1){
            String key = cmdList.get(0);
            if(! key.isEmpty()){
                return new ContainQueryCriterion(key);
            }
        } else if(tokenList.size() == 2){
            String cmd = cmdList.get(0);
            String key = cmdList.get(1);
            if(! key.isEmpty() && cmd.equals("not")){
                return new NotContainQueryCriterion(key);
            }
        } else {
            String key = tokenList.get(0);
            String op = tokenList.get(1);
            if(op.equals("not")){
                op = op + " " + tokenList.get(2);
            }

            if(op.equals("equals")){
                String value = unescapeString(tokenList.get(2));
                if(value != null){
                    return new EqualQueryCriterion(key, value);
                }
            } else if(op.equals("not equals")){
                String value = unescapeString(tokenList.get(3));
                if(value != null){
                    return new NotEqualQueryCriterion(key, value);
                }
            } else if(op.equals("matches")){
                String value = unescapeString(tokenList.get(2));
                if(value != null){
                    return new PatternQueryCriterion(key, value);
                }
            } else if(op.equals("in")){
                List<String> values = new ArrayList<String>();
                boolean start = false;
                for(String s : cmdList){
                    if(s.isEmpty() || s.equals(",")){
                        continue;
                    } else if(s.equals("[")){
                        start = true;
                        continue;
                    } else if(s.equals("]")){
                        start = false;
                        break;
                    } else if(start){
                        String v = unescapeString(s);
                        if(v != null){
                            values.add(v);
                        }
                    }
                }
                return new InQueryCriterion(key, values);
            } else if(op.equals("not in")){
                List<String> values = new ArrayList<String>();
                boolean start = false;
                for(String s : cmdList){
                    if(s.isEmpty() || s.equals(',')){
                        break;
                    } else if(s.equals('[')){
                        start = true;
                        continue;
                    } else if(s.equals(']')){
                        start = false;
                        break;
                    } else if(start){
                        String v = unescapeString(s);
                        if(v != null){
                            values.add(v);
                        }

                    }
                }
                return new NotInQueryCriterion(key, values);
            }
        }
        return null;
    }
1031004
@SuppressWarnings({"rawtypes"})
    public List selectList(String statement) {
        return selectList(statement,
                          null,
                          0,
                          Integer.MAX_VALUE);
    }
948624
public static void closeStatement(Statement statement, String sql) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				log.log(Level.WARNING, "Failed to close SQL Statement: " + sql,
						e);
			}
		}
	}
274663
private void executeAssumeStatement(Tree statement)
    {
        if (!CliMain.isConnected() || !hasKeySpace())
            return;

        String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());

        // VALIDATOR | COMPARATOR | KEYS | SUB_COMPARATOR
        String assumptionElement = statement.getChild(1).getText().toUpperCase();


        // Could be UTF8Type, IntegerType, LexicalUUIDType etc.
        String defaultType = CliUtils.unescapeSQLString(statement.getChild(2).getText());

        if (applyAssumption(cfName, assumptionElement, defaultType))
        {
            assumptions.addAssumption(keySpace, cfName, assumptionElement, defaultType);
            sessionState.out.println(String.format("Assumption for column family '%s' added successfully.", cfName));
        }
    }
425305
public SqlStatement parse(String sql) {

        // does a cached parse result exist for this statement?
        if (_cachedSqlStatements.containsKey(sql)) {
            return _cachedSqlStatements.get(sql);
        }

        SqlGrammar _parser = new SqlGrammar(new StringReader(sql));
        SqlStatement parsed = null;
        try {
            parsed = _parser.parse();
        } catch (ParseException e) {
            throw new ControlException("Error parsing SQL statment." + e.getMessage(), e);
        } catch (TokenMgrError tme) {
            throw new ControlException("Error parsing SQL statment. " + tme.getMessage(), tme);
        }

        if (parsed.isCacheable()) {
            _cachedSqlStatements.put(sql, parsed);
        }
        return parsed;
    }
912657
private void executeDelColumnFamily(Tree statement)
            throws TException, InvalidRequestException, NotFoundException, SchemaDisagreementException
    {
        if (!CliMain.isConnected() || !hasKeySpace())
            return;

        String cfName = CliCompiler.getColumnFamily(statement, currentCfDefs());
        String mySchemaVersion = thriftClient.system_drop_column_family(cfName);
        sessionState.out.println(mySchemaVersion);
    }