Run a SQL query with given configuration

@return the formatted result set by colDelimiter and rowDelimiter
@throws ClassNotFoundException
@throws java.sql.SQLException
978619
public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
            connection.setReadOnly(true);

            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());

            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
            resultSet.close();
            return resultSetToTable;
        }
    }
294174
public ResultSet executeQuery(final String query) throws SQLException {
        startTimer();
        try {
            if (queryResult != null) {
                queryResult.close();
            }
            final Query queryToSend = queryFactory.createQuery(query);
            queryResult = protocol.executeQuery(queryToSend);
            warningsCleared = false;
            return new DrizzleResultSet(queryResult, this, getProtocol());
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        } finally {
            stopTimer();
        }
    }
1030389
private ResultSet getNextResultSet() throws SQLException {
        ResultSet result = null;

        while (stmt.getMoreResults() == true) {

            // when gerMoreResults are returned - some drivers close previous ResultSets - therefore we cannot read them again.
            if (this.type == Type.UPDATE_SCROLL || this.type == Type.READ_ONLY_SCROLL) {
                throw new MjdbcSQLException("Lazy cache scroll does not support Multiple ResultSets. Pleae use" +
                        "non-scrollable lazy handlers or cached output handlers.");
            }

            if (closedResultSet.contains(result) == false) {
                result = stmt.getResultSet();
                break;
            }
        }

        return result;
    }
81881
@Override
  public ResultSet executeQuery(String sql) throws SQLException
  {
    raiseSQLExceptionIfStatementIsClosed();
    return executeQueryInternal(sql, null);
  }
1094228
private void get(final StringBuilder sql) {
        sql.append("SELECT * FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
    }
816585
private Status runQuery(QueryOptions options, QueryRowBlock block) {
        if (options == null)
            options = new QueryOptions();

        // OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
        // they could be indexed with the right collation, instead of having to specify it here.
        String collationStr = "";
        if (collation == View.TDViewCollation.TDViewCollationASCII)
            collationStr += " COLLATE JSON_ASCII";
        else if (collation == View.TDViewCollation.TDViewCollationRaw)
            collationStr += " COLLATE JSON_RAW";


        StringBuilder sql = new StringBuilder("SELECT key, value, docid, revs.sequence");
        if (options.isIncludeDocs()) {
            sql.append(", revid, json");
        }
        sql.append(String.format(Locale.ENGLISH, " FROM 'maps_%s', revs, docs", mapTableName()));
        sql.append(" WHERE 1");

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

        if (options.getKeys() != null && options.getKeys().size() > 0) {
            sql.append(" AND key in (");
            String item = "?";
            for (Object key : options.getKeys()) {
                // null key should be ignored
                if (key != null) {
                    sql.append(item);
                    item = ", ?";
                    argsList.add(toJSONString(key));
                }
            }
            sql.append(')');
        }

        Object minKey = options.getStartKey();
        Object maxKey = options.getEndKey();
        String minKeyDocId = options.getStartKeyDocId();
        String maxKeyDocId = options.getEndKeyDocId();

        boolean inclusiveMin = options.isInclusiveStart();
        boolean inclusiveMax = options.isInclusiveEnd();
        if (options.isDescending()) {
            Object min = minKey;
            minKey = maxKey;
            maxKey = min;
            inclusiveMin = inclusiveMax;
            inclusiveMax = true;
            minKeyDocId = options.getEndKeyDocId();
            maxKeyDocId = options.getStartKeyDocId();
        }

        if (minKey != null) {
            String minKeyJSON = toJSONString(minKey);
            sql.append(inclusiveMin ? " AND key >= ?" : " AND key > ?");
            sql.append(collationStr);
            argsList.add(minKeyJSON);
            if (minKeyDocId != null && inclusiveMin) {
                //OPT: This calls the JSON collator a 2nd time unnecessarily.
                sql.append(String.format(Locale.ENGLISH, " AND (key > ? %s OR docid >= ?)", collationStr));
                argsList.add(minKeyJSON);
                argsList.add(minKeyDocId);
            }
        }

        if (maxKey != null) {
            maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
            String maxKeyJSON = toJSONString(maxKey);
            sql.append(inclusiveMax ? " AND key <= ?" : " AND key < ?");
            sql.append(collationStr);
            argsList.add(maxKeyJSON);
            if (maxKeyDocId != null && inclusiveMax) {
                sql.append(String.format(Locale.ENGLISH, " AND (key < ? %s OR docid <= ?)", collationStr));
                argsList.add(maxKeyJSON);
                argsList.add(maxKeyDocId);
            }
        }

        sql.append(String.format(Locale.ENGLISH,
                " AND revs.sequence = 'maps_%s'.sequence AND docs.doc_id = revs.doc_id ORDER BY key",
                mapTableName()));
        sql.append(collationStr);
        if (options.isDescending()) {
            sql.append(" DESC");
        }
        sql.append(options.isDescending() ? ", docid DESC" : ", docid");

        sql.append(" LIMIT ? OFFSET ?");
        argsList.add(Integer.toString(options.getLimit()));
        argsList.add(Integer.toString(options.getSkip()));

        Log.v(Log.TAG_VIEW, "Query %s: %s | args: %s", name, sql.toString(), argsList);

        Status status = new Status(Status.OK);
        Cursor cursor = null;
        try {
            cursor = store.getStorageEngine().rawQuery(sql.toString(),
                    argsList.toArray(new String[argsList.size()]));
            // regular query
            cursor.moveToNext();
            while (!cursor.isAfterLast()) {
                // Call the block!
                byte[] keyData = cursor.getBlob(0);
                byte[] valueData = cursor.getBlob(1);
                String docID = cursor.getString(2);
                status = block.onRow(keyData, valueData, docID, cursor);
                if (status.isError())
                    break;
                else if (status.getCode() <= 0) {
                    status = new Status(Status.OK);
                    break;
                }
                cursor.moveToNext();
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return status;
    }
641282
public String query(String query) {
        try {
            Connection conn = this.tx().getConnection();
            ObjectNode result = this.mapper.createObjectNode();
            ArrayNode dataNode = this.mapper.createArrayNode();
            ArrayNode metaNode = this.mapper.createArrayNode();
            Statement statement = conn.createStatement();
            if (logger.isDebugEnabled()) {
                logger.debug(query);
            }
            ResultSet rs = statement.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            boolean first = true;
            while (rs.next()) {
                int numColumns = rsmd.getColumnCount();
                ObjectNode obj = this.mapper.createObjectNode();
                for (int i = 1; i < numColumns + 1; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    int type = rsmd.getColumnType(i);
                    //make sure to obtain array using getArray()
                    //At least in H2, this makes a difference...
                    Object o = type == Types.ARRAY ? rs.getArray(i) : rs.getObject(i);
                    this.sqlDialect.putJsonObject(obj, columnName, type, o);
                    if (first) {
                        this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
                    }
                }
                first = false;
                dataNode.add(obj);
            }
            result.set("data", dataNode);
            result.set("meta", metaNode);
            return result.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.tx().rollback();
        }
    }
919860
public Set<String> execute(final ConnectionResource _con)
        throws SQLException
    {
        final Set<String> ret = new HashSet<>();
        if (getIds().length > 1 || checkUpdateRequired(_con)) {
            final StringBuilder cmd = new StringBuilder()
                .append(Context.getDbType().getSQLPart(SQLPart.UPDATE)).append(" ")
                .append(Context.getDbType().getTableQuote())
                .append(getTableName())
                .append(Context.getDbType().getTableQuote()).append(" ")
                .append(Context.getDbType().getSQLPart(SQLPart.SET)).append(" ");

            // append SQL values
            boolean first = true;
            for (final ColumnWithSQLValue col : getColumnWithSQLValues())  {
                if (first)  {
                    first = false;
                } else  {
                    cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                }
                cmd.append(Context.getDbType().getColumnQuote())
                    .append(col.getColumnName())
                    .append(Context.getDbType().getColumnQuote())
                    .append(Context.getDbType().getSQLPart(SQLPart.EQUAL))
                    .append(col.getSqlValue());
            }

            // append values
            for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
                if (first)  {
                    first = false;
                } else  {
                    cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                }
                cmd.append(Context.getDbType().getColumnQuote())
                    .append(col.getColumnName())
                    .append(Context.getDbType().getColumnQuote())
                    .append(Context.getDbType().getSQLPart(SQLPart.EQUAL))
                    .append("?");
                ret.add(col.getColumnName());
            }

            // append where clause
            cmd.append(" ").append(Context.getDbType().getSQLPart(SQLPart.WHERE)).append(" ")
                .append(Context.getDbType().getColumnQuote())
                .append(getIdColumn())
                .append(Context.getDbType().getColumnQuote());

            if (this.ids.length == 1) {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.EQUAL))
                    .append("?");
            } else {
                cmd.append(" ").append(Context.getDbType().getSQLPart(SQLPart.IN)).append(" ")
                    .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_OPEN));
                first = true;
                for (@SuppressWarnings("unused") final long id : this.ids) {
                    if (first)  {
                        first = false;
                    } else  {
                        cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                    }
                    cmd.append("?");
                }
                cmd.append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_CLOSE));
            }

            if (SQLUpdate.LOG.isDebugEnabled()) {
                SQLUpdate.LOG.debug(cmd.toString());
            }

            final PreparedStatement stmt = _con.prepareStatement(cmd.toString());
            int index = 1;
            for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
                if (SQLUpdate.LOG.isDebugEnabled()) {
                    SQLUpdate.LOG.debug("    " + index + " = " + col.getValue());
                }
                col.set(index++, stmt);
            }

            for (final long id : this.ids) {
                SQLUpdate.LOG.debug("    " + index + " = " + id);
                stmt.setLong(index++, id);
            }

            try  {
                final int rows = stmt.executeUpdate();
                if (rows == 0) {
                    throw new SQLException("Object for SQL table '" + getTableName()
                            + "' with ids '" + this.ids + "' does not exists and was not updated.");
                }
            } finally  {
                stmt.close();
            }
        }
        return ret;
    }
406037
public synchronized QueryResult execute() throws QueryException, InterruptedException {
		// create query string
		String queryString = createQueryString();

        PreparedStatement countPstmt = null;
        if (computeCount) {
            try {
                // count statement
                String countQueryString = "SELECT COUNT(*) FROM (" + queryString + ") A";
                if (isCsv) {
                	// csv jdbc driver does not support sub-select
                	countQueryString = getCsvCountQuery(queryString);
                }
                countPstmt = createStatement(countQueryString);
                if (parameterNames.size() != 0) {
                    setParameterValues(countPstmt);
                }
            } catch (QueryException ex) {
                LOG.info("Cannot create count statement : " + ex.getMessage() + " .Will use rs.last()");
                countPstmt = null;
            }
        }

        // create statement
		PreparedStatement pstmt = createStatement(queryString);

        // set parameter values
		if (parameterNames.size() != 0) {
			setParameterValues(pstmt);
		}
        
        try {
            setOutParametersValues(pstmt);
        } catch (SQLException e) {
            throw new QueryException(e);
        } catch (DialectException e) {
            throw new QueryException("Error set out parameter values for executing query : could not get dialect", e);
        }

        // set query's input wrapper
		synchronized (inputWrapper) {
			inputWrapper.statement = pstmt;
            inputWrapper.countStatement = countPstmt;
            inputWrapper.query = queryString;
			inputWrapper.pending = true;
			inputWrapper.notify();
		}

		synchronized (resultWrapper) {
			try {
				// wait for the query to complete
				while (!resultWrapper.serviced) {
					resultWrapper.wait();
				}
				if (resultWrapper.exception != null) {
					throw resultWrapper.exception;
				}
			} catch (InterruptedException e) {
				cancel();
				throw e;
			} finally {
				resultWrapper.serviced = false;
			}

			if ((maxRows > 0) && (resultWrapper.count > maxRows)) {
				resultWrapper.count = maxRows;
			}

			//must finish run method thread normally
			closeRequest = true;
			synchronized (inputWrapper) {
				inputWrapper.pending = true;
				inputWrapper.notify();
			}

			return new QueryResult(resultWrapper.resultSet, resultWrapper.count, resultWrapper.executeTime);
		}
	}
1051049
private boolean query()
		throws SQLException
	{
		statement = this.connection.createStatement();

		String query = "SELECT PrimaryKey, RevisionCounter,"
				+ " RevisionID, ArticleID, Timestamp, FullRevisionID "
				+ "FROM revisions";

		if (primaryKey > 0) {
			query += " WHERE PrimaryKey > " + primaryKey;
		}

		if (MAX_NUMBER_RESULTS > 0) {
			query += " LIMIT " + MAX_NUMBER_RESULTS;
		}

		result = statement.executeQuery(query);
		return result.next();
	}
869945
public @NotNull ResultTable findTable(@NotNull @SQL String sql, Object... args) {
        return findTable(SqlQuery.query(sql, args));
    }
20321
public QueryBuilder<T, ID> queryBuilder() throws SQLException {
		if (statementBuilder instanceof QueryBuilder) {
			return (QueryBuilder<T, ID>) statementBuilder;
		} else {
			throw new SQLException("Cannot cast " + statementBuilder.getType() + " to QueryBuilder");
		}
	}
850290
public void runQueries() throws Exception {

        System.out.println();
        System.out.println("Running Queries: ");
        System.out.println();

        // Specify, run and print the queries (and their results), one at a time
        runQuery("Select some login sessions - just a small portion of the data (limit results to 10):",
                 "SELECT username, json_data FROM user_session_table ORDER BY username LIMIT 10");
        runQuery("Select some login sessions that have been made to the VoltDB Forum, using 'field' (limit results to 10):",
                 "SELECT username, field(json_data,'site') AS site, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'site')='VoltDB Forum' ORDER BY username LIMIT 10");

        runQuery("Select VoltDB Forum sessions that are moderators (at most 10), using 'field' multiple times:",
                 "SELECT username, field(json_data,'moderator') AS moderator, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'site')='VoltDB Forum' AND field(json_data, 'moderator')='true' ORDER BY username LIMIT 10");
        runQuery("Change user 'voltdb' to be a moderator, using 'set_field':",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'moderator', 'true') "
                 + "WHERE username='voltdb'");
        runQuery("Select VoltDB Forum sessions that are moderators (again, after update):",
                 "SELECT username, field(json_data,'moderator') AS moderator, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'site')='VoltDB Forum' AND field(json_data, 'moderator')='true' ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Forum) logins with a download_count larger than one:",
                 "SELECT username, field(json_data,'download_count') AS download_count, json_data FROM user_session_table "
                 + "WHERE cast(field(json_data,'download_count') AS INTEGER) > 1 ORDER BY username LIMIT 10");

        runQuery("User pattern matching (SQL LIKE) to look for records of (VoltDB Forum) logins who have downloaded version v2.x "
                 + "- the old way, using nested calls of 'field':",
                 "SELECT username, field(field(json_data,'props'), 'download_version') AS download_version, json_data FROM user_session_table "
                 + "WHERE field(field(json_data,'props'), 'download_version') LIKE 'v2%' ORDER BY username LIMIT 10");
        runQuery("Identical query (logins who have downloaded version v2.x), using newer, simpler dot notation, rather than 'field' twice:",
                 "SELECT username, field(json_data,'props.download_version') AS download_version, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'props.download_version') LIKE 'v2%' ORDER BY username LIMIT 10");
        runQuery("Change several users to set 'props.download_version' to 'v2.9', using 'set_field' with dot notation:",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'props.download_version', '\"v2.9\"') "
                 + "WHERE username < 'user-10000'");
        runQuery("User pattern matching (SQL LIKE) to look for records of (VoltDB Forum??) logins who have downloaded "
                 + "version v2.x (again, after update):",
                 "SELECT username, field(json_data,'props.download_version') AS download_version, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'props.download_version') LIKE 'v2%' ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Blog) logins whose first role is 'writer' - the old way, using 'array_element':",
                 "SELECT username, array_element(field(json_data,'roles'), 0) AS first_role, json_data FROM user_session_table "
                 + "WHERE array_element(field(json_data,'roles'), 0)='writer' ORDER BY username LIMIT 10");
        runQuery("Identical query (logins whose first role is 'writer'), using newer, simpler bracket notation, "
                 + "rather than 'array_element':",
                 "SELECT username, field(json_data,'roles[0]') AS first_role, json_data FROM user_session_table "
                 + "WHERE field(json_data,'roles[0]')='writer' ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Blog) logins that have more than one role, using 'array_length':",
                 "SELECT username, field(json_data,'roles[0]') AS first_role, field(json_data,'roles[1]') AS second_role, "
                 + "field(json_data,'roles[2]') AS third_role, json_data FROM user_session_table "
                 + "WHERE array_length(field(json_data,'roles')) > 1 ORDER BY username LIMIT 10");
        runQuery("Change user voltdb2's first role to be 'author' (to match the others), using 'set_field' with bracket notation:",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'roles[0]', '\"author\"') "
                 + "WHERE username='voltdb2'");
        runQuery("Add an additional role to user 'voltdb2': 'administrator', using 'set_field' with [-1] to mean beyond the last:",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'roles[-1]', '\"administrator\"') "
                 + "WHERE username='voltdb2'");
        runQuery("Select records of (VoltDB Blog) logins that have more than one role (again, after updates):",
                 "SELECT username, field(json_data,'roles[0]') AS first_role, field(json_data,'roles[1]') AS second_role, "
                 + "field(json_data,'roles[2]') AS third_role, json_data FROM user_session_table "
                 + "WHERE array_length(field(json_data,'roles')) > 1 ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Blog) logins whose last role is 'administrator', using 'field' with [-1] to mean the last:",
                 "SELECT username, field(json_data,'roles[-1]') AS last_role, json_data FROM user_session_table "
                 + "WHERE field(json_data,'roles[-1]')='administrator' ORDER BY username LIMIT 10");

        runQuery("Look deep into the JSON data for records of (VoltDB Forum) logins who have downloaded version v3.0 and "
                 + "have specified a (first) client language of Java (combines dot and bracket notation):",
                 "SELECT username, json_data FROM user_session_table "
                 + "WHERE field(json_data, 'props.download_version')='v3.0' and field(json_data, 'props.client_languages[0]')='Java' "
                 + "ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Forum) logins that have more than one client language (combines "
                 + "'array_length' and 'field' with dot notation):",
                 "SELECT username, field(json_data,'props.client_languages') AS client_languages, json_data FROM user_session_table "
                 + "WHERE array_length(field(json_data,'props.client_languages')) > 1 ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Forum) logins whose second client language is Java:",
                 "SELECT username, field(json_data,'props.client_languages') AS client_languages, json_data FROM user_session_table "
                 + "WHERE field(json_data,'props.client_languages[1]')='Java' ORDER BY username LIMIT 10");
        runQuery("Change user voltdb's second client language to be 'Java' (to match):",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'props.client_languages[1]', '\"Java\"') "
                 + "WHERE username='voltdb'");
        runQuery("Change user voltdb's third client language to be 'Ruby':",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'props.client_languages[2]', '\"Ruby\"') "
                 + "WHERE username='voltdb'");
        runQuery("Select records of (VoltDB Forum) logins whose second client language is Java (again, after updates):",
                 "SELECT username, field(json_data,'props.client_languages') AS client_languages, json_data FROM user_session_table "
                 + "WHERE field(json_data,'props.client_languages[1]')='Java' ORDER BY username LIMIT 10");
        runQuery("Add an additional client language to user 'voltdb': 'Python' (using 'set_field', combines dot and "
                 + "bracket notation, with [-1]):",
                 "UPDATE user_session_table SET json_data = set_field(json_data, 'props.client_languages[-1]', '\"Python\"') "
                 + "WHERE username='voltdb'");
        runQuery("Select records of (VoltDB Forum) logins whose second client language is Java (again, after one more update):",
                 "SELECT username, field(json_data,'props.client_languages') AS client_languages, json_data FROM user_session_table "
                 + "WHERE field(json_data,'props.client_languages[1]')='Java' ORDER BY username LIMIT 10");

        runQuery("Select records of (VoltDB Blog) logins whose last client language is 'Python' (using 'field', combines "
                 + "dot and bracket notation, with [-1]):",
                 "SELECT username, field(json_data,'props.client_languages') AS client_languages, json_data FROM user_session_table "
                 + "WHERE field(json_data,'props.client_languages[-1]')='Python' ORDER BY username LIMIT 10");

        // Display the whole query results as a JSON String
        String SQL = "SELECT json_data FROM user_session_table WHERE username='voltdb' OR username='voltdb2' ORDER BY username";
        VoltTable table = runQuery("Retrieve the JSON data for two particular logins. Treat the whole result set as JSON:", SQL);
        System.out.println("The whole result set as JSON:");
        System.out.println(table.toJSONString());
        System.out.println();

        // Display individual results as JSON
        table = runQuery("Retrieve the JSON data for two particular logins. Just grab a JSON value from the result:", SQL);
        table.advanceRow();
        System.out.println("JSON value from result's first tuple:");
        System.out.println(table.get("json_data", VoltType.STRING));
        System.out.println();
        table.advanceRow();
        System.out.println("JSON value from result's second tuple:");
        System.out.println(table.get("json_data", VoltType.STRING));
        System.out.println();
    }
47949
private VoltTable runQuery(String description, String SQL) throws Exception {
        System.out.println(description);
        ClientResponse resp = client.callProcedure("@AdHoc", SQL);
        System.out.println("SQL query: " + SQL);
        System.out.println();
        VoltTable table = resp.getResults()[0];
        System.out.println(table.toFormattedString());
        System.out.println();
        return table;
    }
835548
@SuppressWarnings( "deprecation" )
    @Override
    public org.modeshape.jcr.api.query.QueryResult execute() throws RepositoryException {
        context.checkValid();
        final long start = System.nanoTime();
        // Create an executable query and set it on this object ...
        CancellableQuery newExecutable = context.createExecutableQuery(query, hints, variables);
        CancellableQuery executable = executingQuery.getAndSet(newExecutable);
        if (executable == null) {
            // We are the first to call 'execute()', so use our newly-created one ...
            executable = newExecutable;
        }
        // otherwise, some other thread called execute, so we can use it and just wait for the results ...
        final QueryResults result = executable.execute(); // may be cancelled

        // And reset the reference to null (if not already set to something else) ...
        executingQuery.compareAndSet(executable, null);

        checkForProblems(result.getProblems());
        context.recordDuration(Math.abs(System.nanoTime() - start), TimeUnit.NANOSECONDS, statement, language);
        if (Query.XPATH.equals(language)) {
            return new XPathQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        } else if (Query.SQL.equals(language)) {
            return new JcrSqlQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        }
        return new JcrQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
    }
691573
@Nullable
    public T query() throws SQLException {
        try (ResultSet r = executeQuery()) {
            if (r.next()) {
                return resultMapper.map(r);
            }
            return null;
        }
    }
491463
@Override
	public boolean execute(final LineReader reader, final String[] parts, final SqlConfig sqlConfig,
			final Properties props) {
		PrintWriter writer = reader.getTerminal().writer();

		String tableNamePattern = parts.length > 1 ? parts[parts.length - 1] : "%";

		try {
			Connection conn = sqlConfig.getConnectionSupplier().getConnection();
			DatabaseMetaData md = conn.getMetaData();

			List<Map<String, String>> columns = new ArrayList<>();
			Map<String, Integer> labelLength = new HashMap<>();
			for (String label : DESC_COLUMN_LABELS) {
				labelLength.put(label, label.length());
			}
			try (ResultSet rs = md.getColumns(conn.getCatalog(), conn.getSchema(), tableNamePattern, null)) {
				while (rs.next()) {
					Map<String, String> column = new HashMap<>();
					for (String label : DESC_COLUMN_LABELS) {
						final String value = StringUtils.defaultString(rs.getString(label));
						column.put(label, value);
						labelLength.compute(
								label,
								(k, v) -> v == null ? getByteLength(value)
										: v.compareTo(getByteLength(value)) >= 0 ? v : getByteLength(value));
					}
					columns.add(column);
				}
			}

			// ラベル
			writer.print("-");
			for (String label : DESC_COLUMN_LABELS) {
				writer.print(StringUtils.rightPad("", labelLength.get(label), "-"));
				writer.print("-");
			}
			writer.println();
			writer.print("|");
			for (String label : DESC_COLUMN_LABELS) {
				writer.print(StringUtils.rightPad(label, labelLength.get(label)));
				writer.print("|");
			}
			writer.println();
			// カラムデータ
			String tableName = null;
			boolean breakFlag = false;
			for (Map<String, String> column : columns) {
				if (tableName == null || !tableName.equalsIgnoreCase(column.get("TABLE_NAME"))) {
					tableName = column.get("TABLE_NAME");
					breakFlag = true;
				}
				if (breakFlag) {
					writer.print("-");
					for (String label : DESC_COLUMN_LABELS) {
						writer.print(StringUtils.rightPad("", labelLength.get(label), "-"));
						writer.print("-");
					}
					writer.println();
					breakFlag = false;
				}

				writer.print("|");
				for (String label : DESC_COLUMN_LABELS) {
					String val = column.get(label);
					if (StringUtils.isNumeric(val)) {
						writer.print(StringUtils.leftPad(val, labelLength.get(label)));
					} else {
						writer.print(StringUtils.rightPad(val, labelLength.get(label)));
					}
					writer.print("|");
				}
				writer.println();
			}
			writer.print("-");
			for (String label : DESC_COLUMN_LABELS) {
				writer.print(StringUtils.rightPad("", labelLength.get(label), "-"));
				writer.print("-");
			}
			writer.println();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		writer.flush();

		return true;
	}