Search in sources :

Example 21 with SQLDataException

use of java.sql.SQLDataException in project jdk8u_jdk by JetBrains.

the class SQLDataExceptionTests method test8.

/**
     * Create SQLDataException with null Throwable
     */
@Test
public void test8() {
    SQLDataException ex = new SQLDataException((Throwable) null);
    assertTrue(ex.getMessage() == null && ex.getSQLState() == null && ex.getCause() == null && ex.getErrorCode() == 0);
}
Also used : SQLDataException(java.sql.SQLDataException) Test(org.testng.annotations.Test) BaseTest(util.BaseTest)

Example 22 with SQLDataException

use of java.sql.SQLDataException in project jdk8u_jdk by JetBrains.

the class SQLDataExceptionTests method test3.

/**
     * Create SQLDataException with message, and SQLState
     */
@Test
public void test3() {
    SQLDataException ex = new SQLDataException(reason, state);
    assertTrue(ex.getMessage().equals(reason) && ex.getSQLState().equals(state) && ex.getCause() == null && ex.getErrorCode() == 0);
}
Also used : SQLDataException(java.sql.SQLDataException) Test(org.testng.annotations.Test) BaseTest(util.BaseTest)

Example 23 with SQLDataException

use of java.sql.SQLDataException in project jdk8u_jdk by JetBrains.

the class SQLDataExceptionTests method test9.

/**
     * Create SQLDataException with Throwable
     */
@Test
public void test9() {
    SQLDataException ex = new SQLDataException(t);
    assertTrue(ex.getMessage().equals(cause) && ex.getSQLState() == null && cause.equals(ex.getCause().toString()) && ex.getErrorCode() == 0);
}
Also used : SQLDataException(java.sql.SQLDataException) Test(org.testng.annotations.Test) BaseTest(util.BaseTest)

Example 24 with SQLDataException

use of java.sql.SQLDataException in project nifi by apache.

the class PutDatabaseRecord method generateInsert.

SqlAndIncludedColumns generateInsert(final RecordSchema recordSchema, final String tableName, final TableSchema tableSchema, final DMLSettings settings) throws IllegalArgumentException, SQLException {
    final Set<String> normalizedFieldNames = getNormalizedColumnNames(recordSchema, settings.translateFieldNames);
    for (final String requiredColName : tableSchema.getRequiredColumnNames()) {
        final String normalizedColName = normalizeColumnName(requiredColName, settings.translateFieldNames);
        if (!normalizedFieldNames.contains(normalizedColName)) {
            String missingColMessage = "Record does not have a value for the Required column '" + requiredColName + "'";
            if (settings.failUnmappedColumns) {
                getLogger().error(missingColMessage);
                throw new IllegalArgumentException(missingColMessage);
            } else if (settings.warningUnmappedColumns) {
                getLogger().warn(missingColMessage);
            }
        }
    }
    final StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("INSERT INTO ");
    if (settings.quoteTableName) {
        sqlBuilder.append(tableSchema.getQuotedIdentifierString()).append(tableName).append(tableSchema.getQuotedIdentifierString());
    } else {
        sqlBuilder.append(tableName);
    }
    sqlBuilder.append(" (");
    // iterate over all of the fields in the record, building the SQL statement by adding the column names
    List<String> fieldNames = recordSchema.getFieldNames();
    final List<Integer> includedColumns = new ArrayList<>();
    if (fieldNames != null) {
        int fieldCount = fieldNames.size();
        AtomicInteger fieldsFound = new AtomicInteger(0);
        for (int i = 0; i < fieldCount; i++) {
            RecordField field = recordSchema.getField(i);
            String fieldName = field.getFieldName();
            final ColumnDescription desc = tableSchema.getColumns().get(normalizeColumnName(fieldName, settings.translateFieldNames));
            if (desc == null && !settings.ignoreUnmappedFields) {
                throw new SQLDataException("Cannot map field '" + fieldName + "' to any column in the database");
            }
            if (desc != null) {
                if (fieldsFound.getAndIncrement() > 0) {
                    sqlBuilder.append(", ");
                }
                if (settings.escapeColumnNames) {
                    sqlBuilder.append(tableSchema.getQuotedIdentifierString()).append(desc.getColumnName()).append(tableSchema.getQuotedIdentifierString());
                } else {
                    sqlBuilder.append(desc.getColumnName());
                }
                includedColumns.add(i);
            }
        }
        // complete the SQL statements by adding ?'s for all of the values to be escaped.
        sqlBuilder.append(") VALUES (");
        sqlBuilder.append(StringUtils.repeat("?", ",", includedColumns.size()));
        sqlBuilder.append(")");
        if (fieldsFound.get() == 0) {
            throw new SQLDataException("None of the fields in the record map to the columns defined by the " + tableName + " table");
        }
    }
    return new SqlAndIncludedColumns(sqlBuilder.toString(), includedColumns);
}
Also used : RecordField(org.apache.nifi.serialization.record.RecordField) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SQLDataException(java.sql.SQLDataException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 25 with SQLDataException

use of java.sql.SQLDataException in project nifi by apache.

the class AbstractHiveQLProcessor method setParameters.

/**
 * Sets all of the appropriate parameters on the given PreparedStatement, based on the given FlowFile attributes.
 *
 * @param stmt       the statement to set the parameters on
 * @param attributes the attributes from which to derive parameter indices, values, and types
 * @throws SQLException if the PreparedStatement throws a SQLException when the appropriate setter is called
 */
protected int setParameters(int base, final PreparedStatement stmt, int paramCount, final Map<String, String> attributes) throws SQLException {
    Map<Integer, ParameterHolder> parmMap = new TreeMap<Integer, ParameterHolder>();
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String key = entry.getKey();
        final Matcher matcher = HIVEQL_TYPE_ATTRIBUTE_PATTERN.matcher(key);
        if (matcher.matches()) {
            final int parameterIndex = Integer.parseInt(matcher.group(1));
            if (parameterIndex >= base && parameterIndex < base + paramCount) {
                final boolean isNumeric = NUMBER_PATTERN.matcher(entry.getValue()).matches();
                if (!isNumeric) {
                    throw new SQLDataException("Value of the " + key + " attribute is '" + entry.getValue() + "', which is not a valid JDBC numeral jdbcType");
                }
                final String valueAttrName = "hiveql.args." + parameterIndex + ".value";
                ParameterHolder ph = new ParameterHolder();
                int realIndexLoc = parameterIndex - base + 1;
                ph.jdbcType = Integer.parseInt(entry.getValue());
                ph.value = attributes.get(valueAttrName);
                ph.attributeName = valueAttrName;
                parmMap.put(realIndexLoc, ph);
            }
        }
    }
    // Now that's we've retrieved the correct number of parameters and it's sorted, let's set them.
    for (final Map.Entry<Integer, ParameterHolder> entry : parmMap.entrySet()) {
        final Integer index = entry.getKey();
        final ParameterHolder ph = entry.getValue();
        try {
            setParameter(stmt, ph.attributeName, index, ph.value, ph.jdbcType);
        } catch (final NumberFormatException nfe) {
            throw new SQLDataException("The value of the " + ph.attributeName + " is '" + ph.value + "', which cannot be converted into the necessary data jdbcType", nfe);
        }
    }
    return base + paramCount;
}
Also used : Matcher(java.util.regex.Matcher) TreeMap(java.util.TreeMap) SQLDataException(java.sql.SQLDataException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Aggregations

SQLDataException (java.sql.SQLDataException)28 Test (org.testng.annotations.Test)14 BaseTest (util.BaseTest)14 SQLException (java.sql.SQLException)7 Connection (java.sql.Connection)3 ResultSet (java.sql.ResultSet)3 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 RecordField (org.apache.nifi.serialization.record.RecordField)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 StringReader (java.io.StringReader)2 SQLIntegrityConstraintViolationException (java.sql.SQLIntegrityConstraintViolationException)2 Statement (java.sql.Statement)2 Timestamp (java.sql.Timestamp)2 Matcher (java.util.regex.Matcher)2 MalformedRecordException (org.apache.nifi.serialization.MalformedRecordException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1