Search in sources :

Example 1 with PalantirSqlException

use of com.palantir.exception.PalantirSqlException in project atlasdb by palantir.

the class AbstractDbWriteTable method putSentinels.

@Override
public void putSentinels(Iterable<Cell> cells) {
    byte[] value = new byte[0];
    long ts = Value.INVALID_VALUE_TIMESTAMP;
    for (List<Cell> batch : Iterables.partition(Ordering.natural().immutableSortedCopy(cells), 1000)) {
        List<Object[]> args = Lists.newArrayListWithCapacity(batch.size());
        for (Cell cell : batch) {
            args.add(new Object[] { cell.getRowName(), cell.getColumnName(), ts, value, cell.getRowName(), cell.getColumnName(), ts });
        }
        while (true) {
            try {
                String prefixedTableName = prefixedTableNames.get(tableRef, conns);
                conns.get().insertManyUnregisteredQuery("/* INSERT_WHERE_NOT_EXISTS (" + prefixedTableName + ") */" + " INSERT INTO " + prefixedTableName + " (row_name, col_name, ts, val) " + " SELECT ?, ?, ?, ? FROM DUAL" + " WHERE NOT EXISTS (SELECT * FROM " + prefixedTableName + " WHERE" + " row_name = ? AND" + " col_name = ? AND" + " ts = ?)", args);
                break;
            } catch (PalantirSqlException e) {
                // TODO(jboreiko): Actually you can. Evaluate use of MERGE or UPSERT here.
                if (!ExceptionCheck.isUniqueConstraintViolation(e)) {
                    throw e;
                }
            }
        }
    }
}
Also used : PalantirSqlException(com.palantir.exception.PalantirSqlException) Cell(com.palantir.atlasdb.keyvalue.api.Cell)

Example 2 with PalantirSqlException

use of com.palantir.exception.PalantirSqlException in project atlasdb by palantir.

the class BasicSQL method insertMany.

public boolean insertMany(final Connection c, final FinalSQLString sql, final Object[][] vs) throws PalantirSqlException {
    if (SqlLoggers.LOGGER.isTraceEnabled()) {
        SqlLoggers.LOGGER.trace("SQL insert many query: {}", sql.getQuery());
    }
    return BasicSQLUtils.runUninterruptably(() -> {
        int[] inserted = null;
        PreparedStatement ps = null;
        // $NON-NLS-1$ //$NON-NLS-2$
        SqlTimer.Handle timerKey = getSqlTimer().start("insertMany(" + vs.length + ")", sql.getKey(), sql.getQuery());
        List<BlobHandler> cleanups = Lists.newArrayList();
        try {
            ps = c.prepareStatement(sql.getQuery());
            for (int i = 0; i < vs.length; i++) {
                for (int j = 0; j < vs[i].length; j++) {
                    Object obj = vs[i][j];
                    BlobHandler cleanup = setObject(c, ps, j + 1, obj);
                    if (cleanup != null) {
                        cleanups.add(cleanup);
                    }
                }
                ps.addBatch();
            }
            inserted = ps.executeBatch();
        } catch (SQLException sqle) {
            SqlLoggers.SQL_EXCEPTION_LOG.debug("Caught SQLException", sqle);
            throw wrapSQLExceptionWithVerboseLogging(sqle, sql.getQuery(), vs);
        } finally {
            closeSilently(ps);
            timerKey.stop();
            for (BlobHandler cleanup : cleanups) {
                try {
                    cleanup.freeTemporary();
                } catch (Exception e) {
                    // $NON-NLS-1$
                    SqlLoggers.LOGGER.error("failed to free temp blob", e);
                }
            }
        }
        if (inserted == null || inserted.length != vs.length) {
            assert false;
            return false;
        }
        for (int numInsertedForRow : inserted) {
            if (numInsertedForRow == Statement.EXECUTE_FAILED) {
                // $NON-NLS-1$
                assert DBType.getTypeFromConnection(c) != DBType.ORACLE : "numInsertedForRow: " + numInsertedForRow;
                return false;
            }
        }
        return true;
    }, sql.toString(), c);
}
Also used : VerboseSQLException(com.palantir.util.sql.VerboseSQLException) SQLException(java.sql.SQLException) BlobHandler(com.palantir.db.oracle.JdbcHandler.BlobHandler) SqlTimer(com.palantir.nexus.db.monitoring.timer.SqlTimer) PreparedStatement(java.sql.PreparedStatement) PalantirSqlException(com.palantir.exception.PalantirSqlException) VerboseSQLException(com.palantir.util.sql.VerboseSQLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PalantirInterruptedException(com.palantir.exception.PalantirInterruptedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with PalantirSqlException

use of com.palantir.exception.PalantirSqlException in project atlasdb by palantir.

the class BasicSQL method selectLightResultSetSpecifyingDBType.

protected AgnosticLightResultSet selectLightResultSetSpecifyingDBType(final Connection c, final FinalSQLString sql, Object[] vs, final DBType dbType, @Nullable Integer fetchSize) throws PalantirSqlException, PalantirInterruptedException {
    if (SqlLoggers.LOGGER.isTraceEnabled()) {
        SqlLoggers.LOGGER.trace("SQL light result set selection query: {}", sql.getQuery());
    }
    // $NON-NLS-1$
    final ResourceCreationLocation alrsCreationException = new ResourceCreationLocation("This is where the AgnosticLightResultSet wrapper was created");
    PreparedStatementVisitor<AgnosticLightResultSet> preparedStatementVisitor = ps -> {
        // $NON-NLS-1$
        final ResourceCreationLocation creationException = new ResourceCreationLocation("This is where the ResultsSet was created", alrsCreationException);
        final ResultSetVisitor<AgnosticLightResultSet> resultSetVisitor = rs -> {
            try {
                return new AgnosticLightResultSetImpl(rs, dbType, rs.getMetaData(), ps, // $NON-NLS-1$
                "selectList", sql, getSqlTimer(), creationException);
            } catch (Exception e) {
                closeSilently(rs);
                BasicSQLUtils.throwUncheckedIfSQLException(e);
                throw Throwables.throwUncheckedException(e);
            }
        };
        try {
            return runCancellably(ps, resultSetVisitor, sql, AutoClose.FALSE, fetchSize);
        } catch (Exception e) {
            closeSilently(ps);
            BasicSQLUtils.throwUncheckedIfSQLException(e);
            throw Throwables.throwUncheckedException(e);
        }
    };
    return wrapPreparedStatement(c, sql, vs, preparedStatementVisitor, // $NON-NLS-1$
    "selectList", // don't close the ps
    AutoClose.FALSE);
}
Also used : PalantirSqlException(com.palantir.exception.PalantirSqlException) FinalSQLString(com.palantir.nexus.db.sql.BasicSQLString.FinalSQLString) Connection(java.sql.Connection) Throwables(com.palantir.common.base.Throwables) ObjectInputStream(java.io.ObjectInputStream) BigDecimal(java.math.BigDecimal) Future(java.util.concurrent.Future) ByteArrayInputStream(java.io.ByteArrayInputStream) PTExecutors(com.palantir.common.concurrent.PTExecutors) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSet(java.sql.ResultSet) Map(java.util.Map) ResultSets(com.palantir.sql.ResultSets) Method(java.lang.reflect.Method) DateTimeFormat(org.joda.time.format.DateTimeFormat) NamedThreadFactory(com.palantir.common.concurrent.NamedThreadFactory) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) JdbcHandler(com.palantir.db.oracle.JdbcHandler) BlobHandler(com.palantir.db.oracle.JdbcHandler.BlobHandler) PreparedStatement(java.sql.PreparedStatement) VerboseSQLException(com.palantir.util.sql.VerboseSQLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) ResourceCreationLocation(com.palantir.nexus.db.ResourceCreationLocation) PalantirInterruptedException(com.palantir.exception.PalantirInterruptedException) SqlLoggers(com.palantir.nexus.db.sql.monitoring.logger.SqlLoggers) ResultSetMetaData(java.sql.ResultSetMetaData) Proxy(java.lang.reflect.Proxy) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Callable(java.util.concurrent.Callable) ThreadNamingCallable(com.palantir.common.concurrent.ThreadNamingCallable) ArrayList(java.util.ArrayList) Connections(com.palantir.sql.Connections) SQLException(java.sql.SQLException) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) PreparedStatements(com.palantir.sql.PreparedStatements) ObjectOutputStream(java.io.ObjectOutputStream) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) DBType(com.palantir.nexus.db.DBType) Iterator(java.util.Iterator) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Validate(org.apache.commons.lang3.Validate) SqlTimer(com.palantir.nexus.db.monitoring.timer.SqlTimer) Statement(java.sql.Statement) InvocationHandler(java.lang.reflect.InvocationHandler) InputStream(java.io.InputStream) ResourceCreationLocation(com.palantir.nexus.db.ResourceCreationLocation) PalantirSqlException(com.palantir.exception.PalantirSqlException) VerboseSQLException(com.palantir.util.sql.VerboseSQLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PalantirInterruptedException(com.palantir.exception.PalantirInterruptedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with PalantirSqlException

use of com.palantir.exception.PalantirSqlException in project atlasdb by palantir.

the class BasicSQL method handleInterruptions.

public static PalantirSqlException handleInterruptions(long startTime, SQLException cause) throws PalantirSqlException {
    SqlLoggers.SQL_EXCEPTION_LOG.debug("Caught SQLException", cause);
    String message = cause.getMessage().trim();
    // check for oracle and postgres
    if (!message.contains(ORACLE_CANCEL_ERROR) && !message.contains(POSTGRES_CANCEL_ERROR)) {
        throw PalantirSqlException.create(cause);
    }
    String elapsedTime = "N/A";
    if (startTime > 0) {
        // $NON-NLS-1$
        elapsedTime = String.valueOf(System.currentTimeMillis() - startTime);
    }
    SqlLoggers.CANCEL_LOGGER.info(// $NON-NLS-1$
    "We got an execution exception that was an interrupt, most likely from someone " + "incorrectly ignoring an interrupt. " + "Elapsed time: {}\n" + "Error message: {} " + "Error code: {} " + "Error state: {} " + "Error cause: {}", elapsedTime, // $NON-NLS-1$
    cause.getMessage(), // $NON-NLS-1$
    cause.getErrorCode(), // $NON-NLS-1$
    cause.getSQLState(), // $NON-NLS-1$
    cause.getNextException(), new Exception("Just for a stack trace"));
    Thread.currentThread().interrupt();
    // $NON-NLS-1$
    throw new PalantirInterruptedException("SQL call interrupted", cause);
}
Also used : PalantirInterruptedException(com.palantir.exception.PalantirInterruptedException) FinalSQLString(com.palantir.nexus.db.sql.BasicSQLString.FinalSQLString) PalantirSqlException(com.palantir.exception.PalantirSqlException) VerboseSQLException(com.palantir.util.sql.VerboseSQLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PalantirInterruptedException(com.palantir.exception.PalantirInterruptedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 5 with PalantirSqlException

use of com.palantir.exception.PalantirSqlException in project atlasdb by palantir.

the class OracleOverflowWriteTable method put.

private void put(List<Object[]> args, List<Object[]> overflowArgs) {
    if (!overflowArgs.isEmpty()) {
        if (config.overflowMigrationState() == OverflowMigrationState.UNSTARTED) {
            conns.get().insertManyUnregisteredQuery("/* INSERT_OVERFLOW */" + " INSERT INTO " + config.singleOverflowTable() + " (id, val) VALUES (?, ?) ", overflowArgs);
        } else {
            String shortOverflowTableName = getShortOverflowTableName();
            conns.get().insertManyUnregisteredQuery("/* INSERT_OVERFLOW (" + shortOverflowTableName + ") */" + " INSERT INTO " + shortOverflowTableName + " (id, val) VALUES (?, ?) ", overflowArgs);
        }
    }
    try {
        String shortTableName = oraclePrefixedTableNames.get(tableRef, conns);
        conns.get().insertManyUnregisteredQuery("/* INSERT_ONE (" + shortTableName + ") */" + " INSERT INTO " + shortTableName + " (row_name, col_name, ts, val, overflow) " + " VALUES (?, ?, ?, ?, ?) ", args);
    } catch (PalantirSqlException e) {
        if (ExceptionCheck.isUniqueConstraintViolation(e)) {
            throw new KeyAlreadyExistsException("primary key violation", e);
        }
        throw e;
    }
}
Also used : PalantirSqlException(com.palantir.exception.PalantirSqlException) KeyAlreadyExistsException(com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException)

Aggregations

PalantirSqlException (com.palantir.exception.PalantirSqlException)11 SQLException (java.sql.SQLException)6 PalantirInterruptedException (com.palantir.exception.PalantirInterruptedException)4 VerboseSQLException (com.palantir.util.sql.VerboseSQLException)4 IOException (java.io.IOException)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 PreparedStatement (java.sql.PreparedStatement)4 ExecutionException (java.util.concurrent.ExecutionException)4 Cell (com.palantir.atlasdb.keyvalue.api.Cell)3 BlobHandler (com.palantir.db.oracle.JdbcHandler.BlobHandler)3 SqlTimer (com.palantir.nexus.db.monitoring.timer.SqlTimer)3 KeyAlreadyExistsException (com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException)2 FinalSQLString (com.palantir.nexus.db.sql.BasicSQLString.FinalSQLString)2 SqlConnection (com.palantir.nexus.db.sql.SqlConnection)2 Map (java.util.Map)2 ImmutableList (com.google.common.collect.ImmutableList)1 Lists (com.google.common.collect.Lists)1 Throwables (com.palantir.common.base.Throwables)1 NamedThreadFactory (com.palantir.common.concurrent.NamedThreadFactory)1 PTExecutors (com.palantir.common.concurrent.PTExecutors)1