Search in sources :

Example 26 with Row

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

the class AbstractDataResult method next.

public T next() {
    if (this.all != null) {
        throw new WrongArgumentException("Cannot iterate after fetchAll()");
    }
    Row r = this.rows.next();
    if (r == null) {
        throw new NoSuchElementException();
    }
    this.position++;
    return this.rowToData.createFromProtocolEntity(r);
}
Also used : WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) Row(com.mysql.cj.result.Row) NoSuchElementException(java.util.NoSuchElementException)

Example 27 with Row

use of com.mysql.cj.result.Row in project JavaSegundasQuintas by ecteruel.

the class DatabaseMetaData method getCallStmtParameterTypes.

/*
     * Extract parameter details for Procedures and Functions by parsing the DDL query obtained from SHOW CREATE [PROCEDURE|FUNCTION] ... statements.
     * The result rows returned follow the required structure for getProcedureColumns() and getFunctionColumns() methods.
     * 
     * Internal use only.
     */
private void getCallStmtParameterTypes(String db, String quotedProcName, ProcedureType procType, String parameterNamePattern, List<Row> resultRows, boolean forGetFunctionColumns) throws SQLException {
    java.sql.Statement paramRetrievalStmt = null;
    java.sql.ResultSet paramRetrievalRs = null;
    String parameterDef = null;
    byte[] procNameAsBytes = null;
    byte[] procCatAsBytes = null;
    boolean isProcedureInAnsiMode = false;
    String storageDefnDelims = null;
    String storageDefnClosures = null;
    try {
        paramRetrievalStmt = this.conn.getMetadataSafeStatement();
        String oldDb = this.conn.getDatabase();
        if (this.conn.lowerCaseTableNames() && db != null && db.length() != 0 && oldDb != null && oldDb.length() != 0) {
            // Workaround for bug in server wrt. to  SHOW CREATE PROCEDURE not respecting lower-case table names
            ResultSet rs = null;
            try {
                this.conn.setDatabase(StringUtils.unQuoteIdentifier(db, this.quotedId));
                rs = paramRetrievalStmt.executeQuery("SELECT DATABASE()");
                rs.next();
                db = rs.getString(1);
            } finally {
                this.conn.setDatabase(oldDb);
                if (rs != null) {
                    rs.close();
                }
            }
        }
        if (paramRetrievalStmt.getMaxRows() != 0) {
            paramRetrievalStmt.setMaxRows(0);
        }
        int dotIndex = " ".equals(this.quotedId) ? quotedProcName.indexOf(".") : StringUtils.indexOfIgnoreCase(0, quotedProcName, ".", this.quotedId, this.quotedId, this.session.getServerSession().isNoBackslashEscapesSet() ? SearchMode.__MRK_COM_MYM_HNT_WS : SearchMode.__BSE_MRK_COM_MYM_HNT_WS);
        String dbName = null;
        if (dotIndex != -1 && (dotIndex + 1) < quotedProcName.length()) {
            dbName = quotedProcName.substring(0, dotIndex);
            quotedProcName = quotedProcName.substring(dotIndex + 1);
        } else {
            dbName = StringUtils.quoteIdentifier(db, this.quotedId, this.pedantic);
        }
        // Moved from above so that procName is *without* database as expected by the rest of code
        // Removing QuoteChar to get output as it was before PROC_CAT fixes
        String tmpProcName = StringUtils.unQuoteIdentifier(quotedProcName, this.quotedId);
        procNameAsBytes = StringUtils.getBytes(tmpProcName, "UTF-8");
        tmpProcName = StringUtils.unQuoteIdentifier(dbName, this.quotedId);
        procCatAsBytes = StringUtils.getBytes(tmpProcName, "UTF-8");
        // there is no need to quote the identifier here since 'dbName' and 'procName' are guaranteed to be already quoted.
        StringBuilder procNameBuf = new StringBuilder();
        procNameBuf.append(dbName);
        procNameBuf.append('.');
        procNameBuf.append(quotedProcName);
        String fieldName = null;
        if (procType == PROCEDURE) {
            paramRetrievalRs = paramRetrievalStmt.executeQuery("SHOW CREATE PROCEDURE " + procNameBuf.toString());
            fieldName = "Create Procedure";
        } else {
            paramRetrievalRs = paramRetrievalStmt.executeQuery("SHOW CREATE FUNCTION " + procNameBuf.toString());
            fieldName = "Create Function";
        }
        if (paramRetrievalRs.next()) {
            String procedureDef = paramRetrievalRs.getString(fieldName);
            if (!this.conn.getPropertySet().getBooleanProperty(PropertyKey.noAccessToProcedureBodies).getValue() && (procedureDef == null || procedureDef.length() == 0)) {
                throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.4"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
            }
            try {
                String sqlMode = paramRetrievalRs.getString("sql_mode");
                if (StringUtils.indexOfIgnoreCase(sqlMode, "ANSI") != -1) {
                    isProcedureInAnsiMode = true;
                }
            } catch (SQLException sqlEx) {
            // doesn't exist
            }
            String identifierMarkers = isProcedureInAnsiMode ? "`\"" : "`";
            String identifierAndStringMarkers = "'" + identifierMarkers;
            storageDefnDelims = "(" + identifierMarkers;
            storageDefnClosures = ")" + identifierMarkers;
            if (procedureDef != null && procedureDef.length() != 0) {
                // sanitize/normalize by stripping out comments
                procedureDef = StringUtils.stripCommentsAndHints(procedureDef, identifierAndStringMarkers, identifierAndStringMarkers, !this.session.getServerSession().isNoBackslashEscapesSet());
                int openParenIndex = StringUtils.indexOfIgnoreCase(0, procedureDef, "(", this.quotedId, this.quotedId, this.session.getServerSession().isNoBackslashEscapesSet() ? SearchMode.__MRK_COM_MYM_HNT_WS : SearchMode.__FULL);
                int endOfParamDeclarationIndex = 0;
                endOfParamDeclarationIndex = endPositionOfParameterDeclaration(openParenIndex, procedureDef, this.quotedId);
                if (procType == FUNCTION) {
                    // Grab the return column since it needs
                    // to go first in the output result set
                    int returnsIndex = StringUtils.indexOfIgnoreCase(0, procedureDef, " RETURNS ", this.quotedId, this.quotedId, this.session.getServerSession().isNoBackslashEscapesSet() ? SearchMode.__MRK_COM_MYM_HNT_WS : SearchMode.__FULL);
                    int endReturnsDef = findEndOfReturnsClause(procedureDef, returnsIndex);
                    // Trim off whitespace after "RETURNS"
                    int declarationStart = returnsIndex + "RETURNS ".length();
                    while (declarationStart < procedureDef.length()) {
                        if (Character.isWhitespace(procedureDef.charAt(declarationStart))) {
                            declarationStart++;
                        } else {
                            break;
                        }
                    }
                    String returnsDefn = procedureDef.substring(declarationStart, endReturnsDef).trim();
                    TypeDescriptor returnDescriptor = new TypeDescriptor(returnsDefn, "YES");
                    resultRows.add(convertTypeDescriptorToProcedureRow(procNameAsBytes, procCatAsBytes, "", false, false, true, returnDescriptor, forGetFunctionColumns, 0));
                }
                if ((openParenIndex == -1) || (endOfParamDeclarationIndex == -1)) {
                    // parse error?
                    throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.5"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
                }
                parameterDef = procedureDef.substring(openParenIndex + 1, endOfParamDeclarationIndex);
            }
        }
    } finally {
        SQLException sqlExRethrow = null;
        if (paramRetrievalRs != null) {
            try {
                paramRetrievalRs.close();
            } catch (SQLException sqlEx) {
                sqlExRethrow = sqlEx;
            }
            paramRetrievalRs = null;
        }
        if (paramRetrievalStmt != null) {
            try {
                paramRetrievalStmt.close();
            } catch (SQLException sqlEx) {
                sqlExRethrow = sqlEx;
            }
            paramRetrievalStmt = null;
        }
        if (sqlExRethrow != null) {
            throw sqlExRethrow;
        }
    }
    if (parameterDef != null) {
        int ordinal = 1;
        List<String> parseList = StringUtils.split(parameterDef, ",", storageDefnDelims, storageDefnClosures, true);
        int parseListLen = parseList.size();
        for (int i = 0; i < parseListLen; i++) {
            String declaration = parseList.get(i);
            if (declaration.trim().length() == 0) {
                // no parameters actually declared, but whitespace spans lines
                break;
            }
            // Bug#52167, tokenizer will break if declaration contains special characters like \n
            declaration = declaration.replaceAll("[\\t\\n\\x0B\\f\\r]", " ");
            StringTokenizer declarationTok = new StringTokenizer(declaration, " \t");
            String paramName = null;
            boolean isOutParam = false;
            boolean isInParam = false;
            if (declarationTok.hasMoreTokens()) {
                String possibleParamName = declarationTok.nextToken();
                if (possibleParamName.equalsIgnoreCase("OUT")) {
                    isOutParam = true;
                    if (declarationTok.hasMoreTokens()) {
                        paramName = declarationTok.nextToken();
                    } else {
                        throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.6"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
                    }
                } else if (possibleParamName.equalsIgnoreCase("INOUT")) {
                    isOutParam = true;
                    isInParam = true;
                    if (declarationTok.hasMoreTokens()) {
                        paramName = declarationTok.nextToken();
                    } else {
                        throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.6"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
                    }
                } else if (possibleParamName.equalsIgnoreCase("IN")) {
                    isOutParam = false;
                    isInParam = true;
                    if (declarationTok.hasMoreTokens()) {
                        paramName = declarationTok.nextToken();
                    } else {
                        throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.6"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
                    }
                } else {
                    isOutParam = false;
                    isInParam = true;
                    paramName = possibleParamName;
                }
                TypeDescriptor typeDesc = null;
                if (declarationTok.hasMoreTokens()) {
                    StringBuilder typeInfoBuf = new StringBuilder(declarationTok.nextToken());
                    while (declarationTok.hasMoreTokens()) {
                        typeInfoBuf.append(" ");
                        typeInfoBuf.append(declarationTok.nextToken());
                    }
                    String typeInfo = typeInfoBuf.toString();
                    typeDesc = new TypeDescriptor(typeInfo, "YES");
                } else {
                    throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.7"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
                }
                if ((paramName.startsWith("`") && paramName.endsWith("`")) || (isProcedureInAnsiMode && paramName.startsWith("\"") && paramName.endsWith("\""))) {
                    paramName = paramName.substring(1, paramName.length() - 1);
                }
                if (parameterNamePattern == null || StringUtils.wildCompareIgnoreCase(paramName, parameterNamePattern)) {
                    Row row = convertTypeDescriptorToProcedureRow(procNameAsBytes, procCatAsBytes, paramName, isOutParam, isInParam, false, typeDesc, forGetFunctionColumns, ordinal++);
                    resultRows.add(row);
                }
            } else {
                throw SQLError.createSQLException(Messages.getString("DatabaseMetaData.8"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
            }
        }
    } else {
    // Is this an error? JDBC spec doesn't make it clear if stored procedure doesn't exist, is it an error....
    }
}
Also used : SQLException(java.sql.SQLException) StringTokenizer(java.util.StringTokenizer) ResultSet(java.sql.ResultSet) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow) Row(com.mysql.cj.result.Row)

Example 28 with Row

use of com.mysql.cj.result.Row in project JavaSegundasQuintas by ecteruel.

the class DatabaseMetaData method getTableTypes.

@Override
public java.sql.ResultSet getTableTypes() throws SQLException {
    ArrayList<Row> tuples = new ArrayList<>();
    Field[] fields = new Field[] { new Field("", "TABLE_TYPE", this.metadataCollationIndex, this.metadataEncoding, MysqlType.VARCHAR, 256) };
    tuples.add(new ByteArrayRow(new byte[][] { TableType.LOCAL_TEMPORARY.asBytes() }, getExceptionInterceptor()));
    tuples.add(new ByteArrayRow(new byte[][] { TableType.SYSTEM_TABLE.asBytes() }, getExceptionInterceptor()));
    tuples.add(new ByteArrayRow(new byte[][] { TableType.SYSTEM_VIEW.asBytes() }, getExceptionInterceptor()));
    tuples.add(new ByteArrayRow(new byte[][] { TableType.TABLE.asBytes() }, getExceptionInterceptor()));
    tuples.add(new ByteArrayRow(new byte[][] { TableType.VIEW.asBytes() }, getExceptionInterceptor()));
    return this.resultSetFactory.createFromResultsetRows(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, new ResultsetRowsStatic(tuples, new DefaultColumnDefinition(fields)));
}
Also used : Field(com.mysql.cj.result.Field) DefaultColumnDefinition(com.mysql.cj.result.DefaultColumnDefinition) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) ArrayList(java.util.ArrayList) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow) Row(com.mysql.cj.result.Row) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow)

Example 29 with Row

use of com.mysql.cj.result.Row in project JavaSegundasQuintas by ecteruel.

the class DatabaseMetaData method getCatalogs.

@Override
public java.sql.ResultSet getCatalogs() throws SQLException {
    List<String> resultsAsList = this.databaseTerm.getValue() == DatabaseTerm.SCHEMA ? new ArrayList<>() : getDatabases();
    Field[] fields = new Field[1];
    fields[0] = new Field("", "TABLE_CAT", this.metadataCollationIndex, this.metadataEncoding, MysqlType.VARCHAR, 0);
    ArrayList<Row> tuples = new ArrayList<>(resultsAsList.size());
    for (String cat : resultsAsList) {
        byte[][] rowVal = new byte[1][];
        rowVal[0] = s2b(cat);
        tuples.add(new ByteArrayRow(rowVal, getExceptionInterceptor()));
    }
    return this.resultSetFactory.createFromResultsetRows(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, new ResultsetRowsStatic(tuples, new DefaultColumnDefinition(fields)));
}
Also used : Field(com.mysql.cj.result.Field) DefaultColumnDefinition(com.mysql.cj.result.DefaultColumnDefinition) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) ArrayList(java.util.ArrayList) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow) Row(com.mysql.cj.result.Row) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow)

Example 30 with Row

use of com.mysql.cj.result.Row in project JavaSegundasQuintas by ecteruel.

the class DatabaseMetaData method getIndexInfo.

@Override
public java.sql.ResultSet getIndexInfo(String catalog, String schema, final String table, final boolean unique, boolean approximate) throws SQLException {
    /*
         * MySQL stores index information in the following fields: Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part
         */
    Field[] fields = createIndexInfoFields();
    final SortedMap<IndexMetaDataKey, Row> sortedRows = new TreeMap<>();
    final ArrayList<Row> rows = new ArrayList<>();
    final Statement stmt = this.conn.getMetadataSafeStatement();
    String db = getDatabase(catalog, schema);
    final boolean dbMapsToSchema = DatabaseMetaData.this.databaseTerm.getValue() == DatabaseTerm.SCHEMA;
    try {
        new IterateBlock<String>(getDatabaseIterator(db)) {

            @Override
            void forEach(String dbStr) throws SQLException {
                ResultSet results = null;
                try {
                    StringBuilder queryBuf = new StringBuilder("SHOW INDEX FROM ");
                    queryBuf.append(StringUtils.quoteIdentifier(table, DatabaseMetaData.this.quotedId, DatabaseMetaData.this.pedantic));
                    queryBuf.append(" FROM ");
                    queryBuf.append(StringUtils.quoteIdentifier(dbStr, DatabaseMetaData.this.quotedId, DatabaseMetaData.this.pedantic));
                    try {
                        results = stmt.executeQuery(queryBuf.toString());
                    } catch (SQLException sqlEx) {
                        // If SQLState is 42S02, ignore this SQLException it means the table doesn't exist....
                        String sqlState = sqlEx.getSQLState();
                        // Sometimes SQLState is not mapped correctly for pre-4.1 so use error code instead.
                        int errorCode = sqlEx.getErrorCode();
                        if (!"42S02".equals(sqlState) && errorCode != MysqlErrorNumbers.ER_NO_SUCH_TABLE && errorCode != MysqlErrorNumbers.ER_BAD_DB_ERROR) {
                            throw sqlEx;
                        }
                    }
                    while (results != null && results.next()) {
                        byte[][] row = new byte[14][];
                        // TABLE_CAT
                        row[0] = dbMapsToSchema ? s2b("def") : s2b(dbStr);
                        // TABLE_SCHEM
                        row[1] = dbMapsToSchema ? s2b(dbStr) : null;
                        // TABLE_NAME
                        row[2] = results.getBytes("Table");
                        boolean indexIsUnique = results.getInt("Non_unique") == 0;
                        // NON_UNIQUE
                        row[3] = !indexIsUnique ? s2b("true") : s2b("false");
                        // INDEX_QUALIFIER
                        row[4] = null;
                        // INDEX_NAME
                        row[5] = results.getBytes("Key_name");
                        short indexType = java.sql.DatabaseMetaData.tableIndexOther;
                        // TYPE
                        row[6] = Integer.toString(indexType).getBytes();
                        // ORDINAL_POSITION
                        row[7] = results.getBytes("Seq_in_index");
                        // COLUMN_NAME
                        row[8] = results.getBytes("Column_name");
                        // ASC_OR_DESC
                        row[9] = results.getBytes("Collation");
                        long cardinality = results.getLong("Cardinality");
                        // CARDINALITY
                        row[10] = s2b(String.valueOf(cardinality));
                        // PAGES
                        row[11] = s2b("0");
                        // FILTER_CONDITION
                        row[12] = null;
                        IndexMetaDataKey indexInfoKey = new IndexMetaDataKey(!indexIsUnique, indexType, results.getString("Key_name").toLowerCase(), results.getShort("Seq_in_index"));
                        if (unique) {
                            if (indexIsUnique) {
                                sortedRows.put(indexInfoKey, new ByteArrayRow(row, getExceptionInterceptor()));
                            }
                        } else {
                            // All rows match
                            sortedRows.put(indexInfoKey, new ByteArrayRow(row, getExceptionInterceptor()));
                        }
                    }
                } finally {
                    if (results != null) {
                        try {
                            results.close();
                        } catch (Exception ex) {
                        }
                        results = null;
                    }
                }
            }
        }.doForAll();
        Iterator<Row> sortedRowsIterator = sortedRows.values().iterator();
        while (sortedRowsIterator.hasNext()) {
            rows.add(sortedRowsIterator.next());
        }
        java.sql.ResultSet indexInfo = this.resultSetFactory.createFromResultsetRows(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, new ResultsetRowsStatic(rows, new DefaultColumnDefinition(fields)));
        return indexInfo;
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) CJException(com.mysql.cj.exceptions.CJException) SQLException(java.sql.SQLException) AssertionFailedException(com.mysql.cj.exceptions.AssertionFailedException) Field(com.mysql.cj.result.Field) ResultSet(java.sql.ResultSet) DefaultColumnDefinition(com.mysql.cj.result.DefaultColumnDefinition) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) ResultSet(java.sql.ResultSet) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow) Row(com.mysql.cj.result.Row) ByteArrayRow(com.mysql.cj.protocol.a.result.ByteArrayRow)

Aggregations

Row (com.mysql.cj.result.Row)144 ArrayList (java.util.ArrayList)81 ResultsetRow (com.mysql.cj.protocol.ResultsetRow)78 ByteArrayRow (com.mysql.cj.protocol.a.result.ByteArrayRow)72 DefaultColumnDefinition (com.mysql.cj.result.DefaultColumnDefinition)69 Field (com.mysql.cj.result.Field)69 ResultsetRowsStatic (com.mysql.cj.protocol.a.result.ResultsetRowsStatic)66 StringValueFactory (com.mysql.cj.result.StringValueFactory)48 ResultSet (java.sql.ResultSet)48 SQLException (java.sql.SQLException)45 PreparedStatement (java.sql.PreparedStatement)36 StatementExecuteOkBuilder (com.mysql.cj.protocol.x.StatementExecuteOkBuilder)33 Statement (java.sql.Statement)33 CJException (com.mysql.cj.exceptions.CJException)30 ColumnDefinition (com.mysql.cj.protocol.ColumnDefinition)30 AssertionFailedException (com.mysql.cj.exceptions.AssertionFailedException)27 XProtocolRowInputStream (com.mysql.cj.protocol.x.XProtocolRowInputStream)27 Test (org.junit.jupiter.api.Test)27 Resultset (com.mysql.cj.protocol.Resultset)21 IOException (java.io.IOException)21