Search in sources :

Example 6 with Resultset

use of com.mysql.cj.protocol.Resultset in project core-ng-project by neowu.

the class MySQLQueryInterceptorTest method defaultBehavior.

@Test
void defaultBehavior() {
    assertThat(interceptor.init(null, null, null)).isSameAs(interceptor);
    Resultset result = interceptor.preProcess(null, null);
    assertThat(result).isNull();
    assertThat(interceptor.executeTopLevelOnly()).isTrue();
    interceptor.destroy();
}
Also used : Resultset(com.mysql.cj.protocol.Resultset) Test(org.junit.jupiter.api.Test)

Example 7 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class NativeSession method queryServerVariable.

/**
 * Get the variable value from server.
 *
 * @param varName
 *            server variable name
 * @return server variable value
 */
public String queryServerVariable(String varName) {
    try {
        NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, "SELECT " + varName), false, 0);
        Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
        ValueFactory<String> svf = new StringValueFactory(this.propertySet);
        Row r;
        if ((r = rs.getRows().next()) != null) {
            String s = r.getValue(0, svf);
            if (s != null) {
                return s;
            }
        }
        return null;
    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
Also used : StringValueFactory(com.mysql.cj.result.StringValueFactory) Resultset(com.mysql.cj.protocol.Resultset) NativeProtocol(com.mysql.cj.protocol.a.NativeProtocol) Row(com.mysql.cj.result.Row) IOException(java.io.IOException) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) ResultsetFactory(com.mysql.cj.protocol.a.ResultsetFactory)

Example 8 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

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 9 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class NativeCharsetSettings method buildCollationMapping.

/**
 * Builds the map needed for 4.1.0 and newer servers that maps field-level
 * charset/collation info to a java character encoding name.
 */
private void buildCollationMapping() {
    Map<Integer, String> customCollationIndexToCollationName = null;
    Map<String, Integer> customCollationNameToCollationIndex = null;
    Map<Integer, String> customCollationIndexToCharsetName = null;
    Map<String, Integer> customCharsetNameToMblen = null;
    Map<String, String> customCharsetNameToJavaEncoding = new HashMap<>();
    Map<String, String> customJavaEncodingUcToCharsetName = new HashMap<>();
    Map<String, Integer> customCharsetNameToCollationIndex = new HashMap<>();
    Set<String> customMultibyteEncodings = new HashSet<>();
    String databaseURL = this.session.getHostInfo().getDatabaseUrl();
    if (this.cacheServerConfiguration.getValue()) {
        synchronized (customCollationIndexToCharsetNameByUrl) {
            customCollationIndexToCollationName = customCollationIndexToCollationNameByUrl.get(databaseURL);
            customCollationNameToCollationIndex = customCollationNameToCollationIndexByUrl.get(databaseURL);
            customCollationIndexToCharsetName = customCollationIndexToCharsetNameByUrl.get(databaseURL);
            customCharsetNameToMblen = customCharsetNameToMblenByUrl.get(databaseURL);
            customCharsetNameToJavaEncoding = customCharsetNameToJavaEncodingByUrl.get(databaseURL);
            customJavaEncodingUcToCharsetName = customJavaEncodingUcToCharsetNameByUrl.get(databaseURL);
            customCharsetNameToCollationIndex = customCharsetNameToCollationIndexByUrl.get(databaseURL);
            customMultibyteEncodings = customMultibyteEncodingsByUrl.get(databaseURL);
        }
    }
    if (customCollationIndexToCharsetName == null && this.session.getPropertySet().getBooleanProperty(PropertyKey.detectCustomCollations).getValue()) {
        customCollationIndexToCollationName = new HashMap<>();
        customCollationNameToCollationIndex = new HashMap<>();
        customCollationIndexToCharsetName = new HashMap<>();
        customCharsetNameToMblen = new HashMap<>();
        customCharsetNameToJavaEncoding = new HashMap<>();
        customJavaEncodingUcToCharsetName = new HashMap<>();
        customCharsetNameToCollationIndex = new HashMap<>();
        customMultibyteEncodings = new HashSet<>();
        String customCharsetMapping = this.session.getPropertySet().getStringProperty(PropertyKey.customCharsetMapping).getValue();
        if (customCharsetMapping != null) {
            String[] pairs = customCharsetMapping.split(",");
            for (String pair : pairs) {
                int keyEnd = pair.indexOf(":");
                if (keyEnd > 0 && (keyEnd + 1) < pair.length()) {
                    String charset = pair.substring(0, keyEnd);
                    String encoding = pair.substring(keyEnd + 1);
                    customCharsetNameToJavaEncoding.put(charset, encoding);
                    customJavaEncodingUcToCharsetName.put(encoding.toUpperCase(Locale.ENGLISH), charset);
                }
            }
        }
        ValueFactory<Integer> ivf = new IntegerValueFactory(this.session.getPropertySet());
        try {
            NativePacketPayload resultPacket = this.session.sendCommand(getCommandBuilder().buildComQuery(null, "select c.COLLATION_NAME, c.CHARACTER_SET_NAME, c.ID, cs.MAXLEN, c.IS_DEFAULT='Yes' from INFORMATION_SCHEMA.COLLATIONS as c left join" + " INFORMATION_SCHEMA.CHARACTER_SETS as cs on cs.CHARACTER_SET_NAME=c.CHARACTER_SET_NAME"), false, 0);
            Resultset rs = this.session.getProtocol().readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
            ValueFactory<String> svf = new StringValueFactory(this.session.getPropertySet());
            Row r;
            while ((r = rs.getRows().next()) != null) {
                String collationName = r.getValue(0, svf);
                String charsetName = r.getValue(1, svf);
                int collationIndex = ((Number) r.getValue(2, ivf)).intValue();
                int maxlen = ((Number) r.getValue(3, ivf)).intValue();
                boolean isDefault = ((Number) r.getValue(4, ivf)).intValue() > 0;
                if (// 
                collationIndex >= MAP_SIZE || !collationName.equals(getStaticCollationNameForCollationIndex(collationIndex)) || !charsetName.equals(getStaticMysqlCharsetNameForCollationIndex(collationIndex))) {
                    customCollationIndexToCollationName.put(collationIndex, collationName);
                    customCollationNameToCollationIndex.put(collationName, collationIndex);
                    customCollationIndexToCharsetName.put(collationIndex, charsetName);
                    if (isDefault) {
                        customCharsetNameToCollationIndex.put(charsetName, collationIndex);
                    } else {
                        customCharsetNameToCollationIndex.putIfAbsent(charsetName, collationIndex);
                    }
                }
                // if no static map for charsetName adding to custom map
                if (getStaticMysqlCharsetByName(charsetName) == null) {
                    customCharsetNameToMblen.put(charsetName, maxlen);
                    if (maxlen > 1) {
                        String enc = customCharsetNameToJavaEncoding.get(charsetName);
                        if (enc != null) {
                            customMultibyteEncodings.add(enc.toUpperCase(Locale.ENGLISH));
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw ExceptionFactory.createException(e.getMessage(), e, this.session.getExceptionInterceptor());
        }
        if (this.cacheServerConfiguration.getValue()) {
            synchronized (customCollationIndexToCharsetNameByUrl) {
                customCollationIndexToCollationNameByUrl.put(databaseURL, Collections.unmodifiableMap(customCollationIndexToCollationName));
                customCollationNameToCollationIndexByUrl.put(databaseURL, Collections.unmodifiableMap(customCollationNameToCollationIndex));
                customCollationIndexToCharsetNameByUrl.put(databaseURL, Collections.unmodifiableMap(customCollationIndexToCharsetName));
                customCharsetNameToMblenByUrl.put(databaseURL, Collections.unmodifiableMap(customCharsetNameToMblen));
                customCharsetNameToJavaEncodingByUrl.put(databaseURL, Collections.unmodifiableMap(customCharsetNameToJavaEncoding));
                customJavaEncodingUcToCharsetNameByUrl.put(databaseURL, Collections.unmodifiableMap(customJavaEncodingUcToCharsetName));
                customCharsetNameToCollationIndexByUrl.put(databaseURL, Collections.unmodifiableMap(customCharsetNameToCollationIndex));
                customMultibyteEncodingsByUrl.put(databaseURL, Collections.unmodifiableSet(customMultibyteEncodings));
            }
        }
    }
    if (customCollationIndexToCharsetName != null) {
        this.collationIndexToCollationName = customCollationIndexToCollationName;
        this.collationNameToCollationIndex = customCollationNameToCollationIndex;
        this.collationIndexToCharsetName = customCollationIndexToCharsetName;
        this.charsetNameToMblen = customCharsetNameToMblen;
        this.charsetNameToJavaEncoding = customCharsetNameToJavaEncoding;
        this.javaEncodingUcToCharsetName = customJavaEncodingUcToCharsetName;
        this.charsetNameToCollationIndex = customCharsetNameToCollationIndex;
        this.multibyteEncodings = customMultibyteEncodings;
    }
}
Also used : StringValueFactory(com.mysql.cj.result.StringValueFactory) HashMap(java.util.HashMap) IntegerValueFactory(com.mysql.cj.result.IntegerValueFactory) IOException(java.io.IOException) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) ResultsetFactory(com.mysql.cj.protocol.a.ResultsetFactory) Resultset(com.mysql.cj.protocol.Resultset) Row(com.mysql.cj.result.Row) HashSet(java.util.HashSet)

Example 10 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class TextResultsetReader method read.

@Override
public Resultset read(int maxRows, boolean streamResults, NativePacketPayload resultPacket, ColumnDefinition metadata, ProtocolEntityFactory<Resultset, NativePacketPayload> resultSetFactory) throws IOException {
    Resultset rs = null;
    // try {
    long columnCount = resultPacket.readInteger(IntegerDataType.INT_LENENC);
    if (columnCount > 0) {
        // Build a result set with rows.
        // Read in the column information
        ColumnDefinition cdef = this.protocol.read(ColumnDefinition.class, new ColumnDefinitionFactory(columnCount, metadata));
        // There is no EOF packet after fields when CLIENT_DEPRECATE_EOF is set
        if (!this.protocol.getServerSession().isEOFDeprecated()) {
            this.protocol.skipPacket();
        // this.protocol.readServerStatusForResultSets(this.protocol.readPacket(this.protocol.getReusablePacket()), true);
        }
        ResultsetRows rows = null;
        if (!streamResults) {
            TextRowFactory trf = new TextRowFactory(this.protocol, cdef, resultSetFactory.getResultSetConcurrency(), false);
            ArrayList<ResultsetRow> rowList = new ArrayList<>();
            ResultsetRow row = this.protocol.read(ResultsetRow.class, trf);
            while (row != null) {
                if ((maxRows == -1) || (rowList.size() < maxRows)) {
                    rowList.add(row);
                }
                row = this.protocol.read(ResultsetRow.class, trf);
            }
            rows = new ResultsetRowsStatic(rowList, cdef);
        } else {
            rows = new ResultsetRowsStreaming<>(this.protocol, cdef, false, resultSetFactory);
            this.protocol.setStreamingData(rows);
        }
        /*
             * Build ResultSet from ResultsetRows
             */
        rs = resultSetFactory.createFromProtocolEntity(rows);
    } else {
        // check for file request
        if (columnCount == NativePacketPayload.NULL_LENGTH) {
            String charEncoding = this.protocol.getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue();
            String fileName = resultPacket.readString(StringSelfDataType.STRING_TERM, this.protocol.getServerSession().getCharsetSettings().doesPlatformDbCharsetMatches() ? charEncoding : null);
            resultPacket = this.protocol.sendFileToServer(fileName);
        }
        /*
             * Build ResultSet with no ResultsetRows
             */
        // read and parse OK packet
        // oldStatus set in sendCommand()
        OkPacket ok = this.protocol.readServerStatusForResultSets(resultPacket, false);
        rs = resultSetFactory.createFromProtocolEntity(ok);
    }
    return rs;
// } catch (IOException ioEx) {
// throw SQLError.createCommunicationsException(this.protocol.getConnection(), this.protocol.getPacketSentTimeHolder().getLastPacketSentTime(),
// this.protocol.getPacketReceivedTimeHolder().getLastPacketReceivedTime(), ioEx, this.protocol.getExceptionInterceptor());
// }
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket) ArrayList(java.util.ArrayList) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) Resultset(com.mysql.cj.protocol.Resultset)

Aggregations

Resultset (com.mysql.cj.protocol.Resultset)14 IOException (java.io.IOException)9 Row (com.mysql.cj.result.Row)7 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)6 StringValueFactory (com.mysql.cj.result.StringValueFactory)6 NativeProtocol (com.mysql.cj.protocol.a.NativeProtocol)5 ResultsetFactory (com.mysql.cj.protocol.a.ResultsetFactory)5 ResultsetRow (com.mysql.cj.protocol.ResultsetRow)4 ArrayList (java.util.ArrayList)4 ColumnDefinition (com.mysql.cj.protocol.ColumnDefinition)3 ResultsetRows (com.mysql.cj.protocol.ResultsetRows)3 Test (org.junit.jupiter.api.Test)3 CJException (com.mysql.cj.exceptions.CJException)2 ClientPreparedStatement (com.mysql.cj.jdbc.ClientPreparedStatement)2 ResultSetInternalMethods (com.mysql.cj.jdbc.result.ResultSetInternalMethods)2 OkPacket (com.mysql.cj.protocol.a.result.OkPacket)2 ResultsetRowsStatic (com.mysql.cj.protocol.a.result.ResultsetRowsStatic)2 Field (com.mysql.cj.result.Field)2 LongValueFactory (com.mysql.cj.result.LongValueFactory)2 InputStream (java.io.InputStream)2