Search in sources :

Example 1 with StringValueFactory

use of com.mysql.cj.result.StringValueFactory in project ABC by RuiPinto96274.

the class NativeSession method findProcessHost.

private String findProcessHost(long threadId) {
    try {
        String processHost = null;
        String ps = this.protocol.getServerSession().getServerVariable("performance_schema");
        NativePacketPayload resultPacket = // performance_schema.threads in MySQL 5.5 does not contain PROCESSLIST_HOST column
        versionMeetsMinimum(5, 6, 0) && ps != null && ("1".contentEquals(ps) || "ON".contentEquals(ps)) ? sendCommand(this.commandBuilder.buildComQuery(null, "select PROCESSLIST_ID, PROCESSLIST_USER, PROCESSLIST_HOST from performance_schema.threads where PROCESSLIST_ID=" + threadId), false, 0) : sendCommand(this.commandBuilder.buildComQuery(null, "SHOW PROCESSLIST"), false, 0);
        Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
        ValueFactory<Long> lvf = new LongValueFactory(getPropertySet());
        ValueFactory<String> svf = new StringValueFactory(this.propertySet);
        Row r;
        while ((r = rs.getRows().next()) != null) {
            long id = r.getValue(0, lvf);
            if (threadId == id) {
                processHost = r.getValue(2, svf);
                break;
            }
        }
        return processHost;
    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
Also used : StringValueFactory(com.mysql.cj.result.StringValueFactory) NativeProtocol(com.mysql.cj.protocol.a.NativeProtocol) IOException(java.io.IOException) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) ResultsetFactory(com.mysql.cj.protocol.a.ResultsetFactory) LongValueFactory(com.mysql.cj.result.LongValueFactory) Resultset(com.mysql.cj.protocol.Resultset) Row(com.mysql.cj.result.Row)

Example 2 with StringValueFactory

use of com.mysql.cj.result.StringValueFactory in project ABC by RuiPinto96274.

the class NativeSession method loadServerVariables.

/**
 * Loads the result of 'SHOW VARIABLES' into the serverVariables field so
 * that the driver can configure itself.
 *
 * @param syncMutex
 *            synchronization mutex
 * @param version
 *            driver version string
 */
public void loadServerVariables(Object syncMutex, String version) {
    if (this.cacheServerConfiguration.getValue()) {
        createConfigCacheIfNeeded(syncMutex);
        Map<String, String> cachedVariableMap = this.serverConfigCache.get(this.hostInfo.getDatabaseUrl());
        if (cachedVariableMap != null) {
            String cachedServerVersion = cachedVariableMap.get(SERVER_VERSION_STRING_VAR_NAME);
            if (cachedServerVersion != null && getServerSession().getServerVersion() != null && cachedServerVersion.equals(getServerSession().getServerVersion().toString())) {
                Map<String, String> localVariableMap = this.protocol.getServerSession().getServerVariables();
                Map<String, String> newLocalVariableMap = new HashMap<>();
                newLocalVariableMap.putAll(cachedVariableMap);
                // preserving variables already configured on previous session initialization steps
                newLocalVariableMap.putAll(localVariableMap);
                this.protocol.getServerSession().setServerVariables(newLocalVariableMap);
                return;
            }
            this.serverConfigCache.invalidate(this.hostInfo.getDatabaseUrl());
        }
    }
    try {
        if (version != null && version.indexOf('*') != -1) {
            StringBuilder buf = new StringBuilder(version.length() + 10);
            for (int i = 0; i < version.length(); i++) {
                char c = version.charAt(i);
                buf.append(c == '*' ? "[star]" : c);
            }
            version = buf.toString();
        }
        String versionComment = (this.propertySet.getBooleanProperty(PropertyKey.paranoid).getValue() || version == null) ? "" : "/* " + version + " */";
        this.protocol.getServerSession().setServerVariables(new HashMap<String, String>());
        if (versionMeetsMinimum(5, 1, 0)) {
            StringBuilder queryBuf = new StringBuilder(versionComment).append("SELECT");
            queryBuf.append("  @@session.auto_increment_increment AS auto_increment_increment");
            queryBuf.append(", @@character_set_client AS character_set_client");
            queryBuf.append(", @@character_set_connection AS character_set_connection");
            queryBuf.append(", @@character_set_results AS character_set_results");
            queryBuf.append(", @@character_set_server AS character_set_server");
            queryBuf.append(", @@collation_server AS collation_server");
            queryBuf.append(", @@collation_connection AS collation_connection");
            queryBuf.append(", @@init_connect AS init_connect");
            queryBuf.append(", @@interactive_timeout AS interactive_timeout");
            if (!versionMeetsMinimum(5, 5, 0)) {
                queryBuf.append(", @@language AS language");
            }
            queryBuf.append(", @@license AS license");
            queryBuf.append(", @@lower_case_table_names AS lower_case_table_names");
            queryBuf.append(", @@max_allowed_packet AS max_allowed_packet");
            queryBuf.append(", @@net_write_timeout AS net_write_timeout");
            queryBuf.append(", @@performance_schema AS performance_schema");
            if (!versionMeetsMinimum(8, 0, 3)) {
                queryBuf.append(", @@query_cache_size AS query_cache_size");
                queryBuf.append(", @@query_cache_type AS query_cache_type");
            }
            queryBuf.append(", @@sql_mode AS sql_mode");
            queryBuf.append(", @@system_time_zone AS system_time_zone");
            queryBuf.append(", @@time_zone AS time_zone");
            if (versionMeetsMinimum(8, 0, 3) || (versionMeetsMinimum(5, 7, 20) && !versionMeetsMinimum(8, 0, 0))) {
                queryBuf.append(", @@transaction_isolation AS transaction_isolation");
            } else {
                queryBuf.append(", @@tx_isolation AS transaction_isolation");
            }
            queryBuf.append(", @@wait_timeout AS wait_timeout");
            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, queryBuf.toString()), false, 0);
            Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
            Field[] f = rs.getColumnDefinition().getFields();
            if (f.length > 0) {
                ValueFactory<String> vf = new StringValueFactory(this.propertySet);
                Row r;
                if ((r = rs.getRows().next()) != null) {
                    for (int i = 0; i < f.length; i++) {
                        String value = r.getValue(i, vf);
                        this.protocol.getServerSession().getServerVariables().put(f[i].getColumnLabel(), // recent server versions return "utf8mb3" instead of "utf8"
                        "utf8mb3".equalsIgnoreCase(value) ? "utf8" : value);
                    }
                }
            }
        } else {
            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, versionComment + "SHOW VARIABLES"), false, 0);
            Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
            ValueFactory<String> vf = new StringValueFactory(this.propertySet);
            Row r;
            while ((r = rs.getRows().next()) != null) {
                this.protocol.getServerSession().getServerVariables().put(r.getValue(0, vf), r.getValue(1, vf));
            }
        }
    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
    if (this.cacheServerConfiguration.getValue()) {
        this.protocol.getServerSession().getServerVariables().put(SERVER_VERSION_STRING_VAR_NAME, getServerSession().getServerVersion().toString());
        Map<String, String> localVariableMap = new HashMap<>();
        localVariableMap.putAll(this.protocol.getServerSession().getServerVariables());
        this.serverConfigCache.put(this.hostInfo.getDatabaseUrl(), Collections.unmodifiableMap(localVariableMap));
    }
}
Also used : StringValueFactory(com.mysql.cj.result.StringValueFactory) HashMap(java.util.HashMap) NativeProtocol(com.mysql.cj.protocol.a.NativeProtocol) IOException(java.io.IOException) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) ResultsetFactory(com.mysql.cj.protocol.a.ResultsetFactory) Field(com.mysql.cj.result.Field) Resultset(com.mysql.cj.protocol.Resultset) Row(com.mysql.cj.result.Row)

Example 3 with StringValueFactory

use of com.mysql.cj.result.StringValueFactory in project ABC by RuiPinto96274.

the class NativeProtocol method appendResultSetSlashGStyle.

private StringBuilder appendResultSetSlashGStyle(StringBuilder appendTo, Resultset rs) {
    Field[] fields = rs.getColumnDefinition().getFields();
    int maxWidth = 0;
    for (int i = 0; i < fields.length; i++) {
        if (fields[i].getColumnLabel().length() > maxWidth) {
            maxWidth = fields[i].getColumnLabel().length();
        }
    }
    int rowCount = 1;
    Row r;
    while ((r = rs.getRows().next()) != null) {
        appendTo.append("*************************** ");
        appendTo.append(rowCount++);
        appendTo.append(". row ***************************\n");
        for (int i = 0; i < fields.length; i++) {
            int leftPad = maxWidth - fields[i].getColumnLabel().length();
            for (int j = 0; j < leftPad; j++) {
                appendTo.append(" ");
            }
            appendTo.append(fields[i].getColumnLabel()).append(": ");
            String stringVal = r.getValue(i, new StringValueFactory(this.propertySet));
            appendTo.append(stringVal != null ? stringVal : "NULL").append("\n");
        }
        appendTo.append("\n");
    }
    return appendTo;
}
Also used : Field(com.mysql.cj.result.Field) StringValueFactory(com.mysql.cj.result.StringValueFactory) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) Row(com.mysql.cj.result.Row) LazyString(com.mysql.cj.util.LazyString)

Example 4 with StringValueFactory

use of com.mysql.cj.result.StringValueFactory in project ABC by RuiPinto96274.

the class NativeProtocol method convertShowWarningsToSQLWarnings.

/**
 * Turns output of 'SHOW WARNINGS' into JDBC SQLWarning instances.
 *
 * If 'forTruncationOnly' is true, only looks for truncation warnings, and
 * actually throws DataTruncation as an exception.
 *
 * @param warningCountIfKnown
 *            the warning count (if known), otherwise set it to 0.
 * @param forTruncationOnly
 *            if this method should only scan for data truncation warnings
 *
 * @return the SQLWarning chain (or null if no warnings)
 */
public SQLWarning convertShowWarningsToSQLWarnings(int warningCountIfKnown, boolean forTruncationOnly) {
    SQLWarning currentWarning = null;
    ResultsetRows rows = null;
    try {
        /*
             * +---------+------+---------------------------------------------+
             * | Level ..| Code | Message ....................................|
             * +---------+------+---------------------------------------------+
             * | Warning | 1265 | Data truncated for column 'field1' at row 1 |
             * +---------+------+---------------------------------------------+
             */
        NativePacketPayload resultPacket = sendCommand(getCommandBuilder().buildComQuery(getSharedSendPacket(), "SHOW WARNINGS"), false, 0);
        Resultset warnRs = readAllResults(-1, warningCountIfKnown > 99, /* stream large warning counts */
        resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, Concurrency.READ_ONLY));
        int codeFieldIndex = warnRs.getColumnDefinition().findColumn("Code", false, 1) - 1;
        int messageFieldIndex = warnRs.getColumnDefinition().findColumn("Message", false, 1) - 1;
        ValueFactory<String> svf = new StringValueFactory(this.propertySet);
        ValueFactory<Integer> ivf = new IntegerValueFactory(this.propertySet);
        rows = warnRs.getRows();
        Row r;
        while ((r = rows.next()) != null) {
            int code = r.getValue(codeFieldIndex, ivf);
            if (forTruncationOnly) {
                if (code == MysqlErrorNumbers.ER_WARN_DATA_TRUNCATED || code == MysqlErrorNumbers.ER_WARN_DATA_OUT_OF_RANGE) {
                    DataTruncation newTruncation = new MysqlDataTruncation(r.getValue(messageFieldIndex, svf), 0, false, false, 0, 0, code);
                    if (currentWarning == null) {
                        currentWarning = newTruncation;
                    } else {
                        currentWarning.setNextWarning(newTruncation);
                    }
                }
            } else {
                // String level = warnRs.getString("Level");
                String message = r.getValue(messageFieldIndex, svf);
                SQLWarning newWarning = new SQLWarning(message, MysqlErrorNumbers.mysqlToSqlState(code), code);
                if (currentWarning == null) {
                    currentWarning = newWarning;
                } else {
                    currentWarning.setNextWarning(newWarning);
                }
            }
        }
        if (forTruncationOnly && (currentWarning != null)) {
            throw ExceptionFactory.createException(currentWarning.getMessage(), currentWarning);
        }
        return currentWarning;
    } catch (IOException ex) {
        throw ExceptionFactory.createException(ex.getMessage(), ex);
    } finally {
        if (rows != null) {
            rows.close();
        }
    }
}
Also used : SQLWarning(java.sql.SQLWarning) StringValueFactory(com.mysql.cj.result.StringValueFactory) MysqlDataTruncation(com.mysql.cj.jdbc.exceptions.MysqlDataTruncation) IntegerValueFactory(com.mysql.cj.result.IntegerValueFactory) LazyString(com.mysql.cj.util.LazyString) IOException(java.io.IOException) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) DataTruncation(java.sql.DataTruncation) MysqlDataTruncation(com.mysql.cj.jdbc.exceptions.MysqlDataTruncation) Resultset(com.mysql.cj.protocol.Resultset) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) Row(com.mysql.cj.result.Row)

Example 5 with StringValueFactory

use of com.mysql.cj.result.StringValueFactory in project ABC by RuiPinto96274.

the class XProtocolTest method testResultSet.

/**
 * This is a development method that will print a detailed result set for any command sent.
 */
@Test
public void testResultSet() {
    assumeTrue(this.isSetForXTests, PropertyDefinitions.SYSP_testsuite_url_mysqlx + " must be set to run this test.");
    // begin "send" stage, change this as necessary
    this.protocol.send(this.messageBuilder.buildListNotices(), 0);
    // this will read the metadata and result and print all data
    ColumnDefinition metadata = this.protocol.readMetadata();
    Arrays.stream(metadata.getFields()).forEach(f -> {
        System.err.println("***************** field ****************");
        System.err.println("Field: " + f.getColumnLabel());
        System.err.println("Type: " + f.getMysqlTypeId());
        System.err.println("Encoding: " + f.getEncoding());
    });
    Iterator<Row> ris = new XProtocolRowInputStream(metadata, this.protocol, null);
    ris.forEachRemaining(r -> {
        System.err.println("***************** row ****************");
        for (int i = 0; i < metadata.getFields().length; ++i) {
            System.err.println(metadata.getFields()[i].getColumnLabel() + ": " + r.getValue(i, new StringValueFactory(this.protocol.getPropertySet())));
        }
    });
    this.protocol.readQueryResult(new StatementExecuteOkBuilder());
}
Also used : XProtocolRowInputStream(com.mysql.cj.protocol.x.XProtocolRowInputStream) StringValueFactory(com.mysql.cj.result.StringValueFactory) StatementExecuteOkBuilder(com.mysql.cj.protocol.x.StatementExecuteOkBuilder) Row(com.mysql.cj.result.Row) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) Test(org.junit.jupiter.api.Test)

Aggregations

StringValueFactory (com.mysql.cj.result.StringValueFactory)66 Row (com.mysql.cj.result.Row)48 Test (org.junit.jupiter.api.Test)39 ColumnDefinition (com.mysql.cj.protocol.ColumnDefinition)24 StatementExecuteOkBuilder (com.mysql.cj.protocol.x.StatementExecuteOkBuilder)24 XProtocolRowInputStream (com.mysql.cj.protocol.x.XProtocolRowInputStream)24 DefaultPropertySet (com.mysql.cj.conf.DefaultPropertySet)18 Resultset (com.mysql.cj.protocol.Resultset)18 Field (com.mysql.cj.result.Field)18 IOException (java.io.IOException)18 DocFilterParams (com.mysql.cj.xdevapi.DocFilterParams)15 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)12 ResultsetFactory (com.mysql.cj.protocol.a.ResultsetFactory)12 FilterParams (com.mysql.cj.xdevapi.FilterParams)12 ArrayList (java.util.ArrayList)12 ResultsetRow (com.mysql.cj.protocol.ResultsetRow)9 NativeProtocol (com.mysql.cj.protocol.a.NativeProtocol)9 IntegerValueFactory (com.mysql.cj.result.IntegerValueFactory)9 LazyString (com.mysql.cj.util.LazyString)9 HashMap (java.util.HashMap)9