private void debug(String action) { LOGGER.debug("Report node " + action); } }
protected void logOperation(Logger logger, final String sql, final List<?> values) { logger.debug("%s, values:%s", sql, values); }
@Override public void rawClose() throws SQLException { LOGGER_CONNECTION.debug("Closed external connection: %s", connection); connection.close(); }
private static void delete(Path path) throws IOException { LOGGER.debug("Deleting '" + path.toString() + "'."); Files.delete(path); }
@Override public void close() { if (!closed) { if (available) { LOGGER_CONNECTION.debug("Releasing connection"); lock.release(); available = false; } closed = true; onClose(); counter.decrementAndGet(); } }
public long executeAndGetLong(String sql, List<Object> values) { LOGGER_SELECT.debug("%s, values:%s", sql, values); return dbmsType.getOperationHandler().executeQuery(dbms, sql, values, rs -> rs.getLong(1) ).findAny().orElseThrow(() -> new NoSuchElementException("No long value for " + sql + ", values " + values)); }
private void discard(PoolableConnection connection) { requireNonNull(connection); LOGGER_CONNECTION.debug("Discard: %s", connection); try { connection.rawClose(); } catch (SQLException sqle) { LOGGER_CONNECTION.error(sqle, "Error closing a connection."); } }
@Override public <ENTITY> SqlStreamOptimizer<ENTITY> get(Pipeline initialPipeline, DbmsType dbmsType) { if (DEBUG.isEqualOrHigherThan(LOGGER_STREAM_OPTIMIZER.getLevel())) { LOGGER_STREAM_OPTIMIZER.debug("Evaluating %s pipeline: %s", initialPipeline.isParallel() ? "parallel" : "sequential", initialPipeline.toString()); } final SqlStreamOptimizer<ENTITY> result = getHelper(initialPipeline, dbmsType); if (DEBUG.isEqualOrHigherThan(LOGGER_STREAM_OPTIMIZER.getLevel())) { LOGGER_STREAM_OPTIMIZER.debug("Selected: %s", result.getClass().getSimpleName()); } return result; }
private static void write(Path path, String content, boolean hidden) throws IOException { LOGGER.debug("Creating '" + path.toString() + "'."); final Path parent = path.getParent(); try { if (parent != null) { Files.createDirectories(parent); if (hidden) { setAttributeHidden(parent); } } } catch (final SecurityException se) { throw new SpeedmentException("Unable to create directory " + parent.toString(), se); } Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); if (hidden) { setAttributeHidden(path); } }
private void blockUntilAvailable() { if (closed) { throw new IllegalStateException("This connection has already been closed."); } if (!available) { LOGGER_CONNECTION.debug("Aquiring connection"); try { if (!lock.tryAcquire()) { if (blocking) { LOGGER_CONNECTION.warn("Waiting for connection to become available..."); lock.acquire(); } else { throw new SpeedmentException( "Error! No connection available. Try " + "wrapping the expression in a transaction or " + "enable the Speedment parameter " + "'connectionpool.blocking=true'."); } } } catch (final InterruptedException ex) { throw new SpeedmentException( "Interrupted while waiting for available connection.", ex); } this.counter.incrementAndGet(); available = true; } } }
@Override public Connection newConnection( final String uri, final String username, final char[] password ) { try { final Connection connection = DriverManager.getConnection(uri, username, charsToString(password)); LOGGER_CONNECTION.debug("New external connection: %s", connection); return connection; } catch (final SQLException ex) { final String msg = "Unable to get connection using url \"" + uri + "\", user = \"" + username + "\", password = \"********\"."; LOGGER_CONNECTION.error(ex, msg); throw new SpeedmentException(msg, ex); } }
@Override public <R> R createAndApply(Function<? super Transaction, ? extends R> mapper) throws TransactionException { requireNonNull(mapper); final Thread currentThread = Thread.currentThread(); final Object txObject = dataSourceHandler.extractor().apply(dataSource); // e.g. obtains a Connection final Isolation oldIsolation = setAndGetIsolation(txObject, isolation); final Transaction tx = new TransactionImpl(txComponent, txObject, dataSourceHandler); TRANSACTION_LOGGER.debug("Transaction %s created for thread '%s' on tranaction object %s", tx, currentThread.getName(), txObject); txComponent.put(currentThread, txObject); try { dataSourceHandler.beginner().accept(txObject); // e.g. con.setAutocommit(false) return mapper.apply(tx); } catch (Exception e) { // Executed in the finally block : dataSourceHandler.rollbacker().accept(txObject); // Automatically rollback if there is an exception throw new TransactionException("Error while invoking transaction for object :" + txObject, e); } finally { dataSourceHandler.rollbacker().accept(txObject); // Always rollback() implicitly and discard uncommitted data dataSourceHandler.closer().accept(txObject); // e.g. con.setAutocommit(true); con.close(); setAndGetIsolation(txObject, oldIsolation); txComponent.remove(currentThread); TRANSACTION_LOGGER.debug("Transaction %s owned by thread '%s' was discarded", tx, currentThread.getName()); } }
LOGGER_JOIN.debug(sb.toString());
private <ENTITY> SqlStreamOptimizer<ENTITY> getHelper(Pipeline initialPipeline, DbmsType dbmsType) { @SuppressWarnings("unchecked") SqlStreamOptimizer<ENTITY> result = (SqlStreamOptimizer<ENTITY>) FALL_BACK; if (initialPipeline.isEmpty()) { return result; } Metrics metric = Metrics.empty(); for (int i = optimizers.size() - 1; i >= 0; i--) { @SuppressWarnings("unchecked") final SqlStreamOptimizer<ENTITY> candidate = (SqlStreamOptimizer<ENTITY>) optimizers.get(i); final Metrics candidateMetric = candidate.metrics(initialPipeline, dbmsType); if (DEBUG.isEqualOrHigherThan(LOGGER_STREAM_OPTIMIZER.getLevel())) { LOGGER_STREAM_OPTIMIZER.debug("Candidate: %-30s : %s ", candidate.getClass().getSimpleName(), candidateMetric); } if (METRICS_COMPARATOR.compare(candidateMetric, metric) > 0) { // if (candidateMetric.getPipelineReductions() > metric.getPipelineReductions()) { metric = candidateMetric; result = candidate; if (metric.getPipelineReductions() == Integer.MAX_VALUE) { return result; } } } return result; }
@Override public PoolableConnection getConnection( final String uri, final String user, final char[] password ) { requireNonNull(uri); // user nullable // password nullable LOGGER_CONNECTION.debug("getConnection(%s, %s, *****)", uri, user); final String key = makeKey(uri, user, password); final Deque<PoolableConnection> q = acquireDeque(key); final PoolableConnection reusedConnection = pollValidOrNull(q); if (reusedConnection != null) { LOGGER_CONNECTION.debug("Reuse Connection: %s", reusedConnection); return lease(reusedConnection); } else { final Connection newRawConnection = newConnection(uri, user, password); final PoolableConnection newConnection = new PoolableConnectionImpl(uri, user, password, newRawConnection, System.currentTimeMillis() + getMaxAge()); newConnection.setOnClose(() -> returnConnection(newConnection)); LOGGER_CONNECTION.debug("New Connection: %s", newConnection); return lease(newConnection); } }
@Override public void returnConnection(PoolableConnection connection) { requireNonNull(connection); leaseReturn(connection); if (!isValidOrNull(connection)) { discard(connection); } else { final String key = makeKey(connection); final Deque<PoolableConnection> q = acquireDeque(key); if (q.size() >= getMaxRetainSize()) { discard(connection); } else { LOGGER_CONNECTION.debug("Recycled: %s", connection); q.addFirst(connection); } } }
protected void validateRuntimeConfig(Injector injector) { LOGGER.debug("Validating Runtime Configuration"); final Project project = injector.getOrThrow(ProjectComponent.class) .getProject(); if (project == null) { throw new SpeedmentException("No project defined"); } project.dbmses().forEach(d -> { final String typeName = d.getTypeName(); final Optional<DbmsType> oDbmsType = injector.getOrThrow( DbmsHandlerComponent.class).findByName(typeName); if (!oDbmsType.isPresent()) { throw new SpeedmentException("The database type " + typeName + " is not registered with the " + DbmsHandlerComponent.class.getSimpleName()); } final DbmsType dbmsType = oDbmsType.get(); if (!dbmsType.isSupported()) { LOGGER.error("The database driver class " + dbmsType.getDriverName() + " is not available. Make sure to include it in your " + "class path (e.g. in the POM file)" ); } }); }
@Override public Stream<T> stream() { setState(State.ESTABLISH); try { LOGGER_STREAM.debug("%s, values:%s", getSql(), getValues()); connectionInfo = connectionInfoSupplier.get(); connectionInfo.ifNotInTransaction(c -> c.setAutoCommit(false)); // Streaming results must be autocommit false for PostgreSQL ps = connectionInfo.connection().prepareStatement(getSql(), java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); statementConfigurator.accept(ps); //System.out.format("*** PreparedStatement: fetchDirection %d, fetchSize %d%n", ps.getFetchDirection(), ps.getFetchSize()); int i = 1; for (final Object o : getValues()) { ps.setObject(i++, o); } rs = ps.executeQuery(); resultSetConfigurator.accept(rs); //System.out.format("*** ResultSet: fetchDirection %d, fetchSize %d%n", rs.getFetchDirection(), rs.getFetchSize()); } catch (SQLException sqle) { LOGGER.error(sqle, "Error executing " + getSql() + ", values=" + getValues()); throw new SpeedmentException(sqle); } setState(State.OPEN); return StreamUtil.asStream(rs, getRsMapper(), parallelStrategy); }
protected void checkDatabaseConnectivity(Injector injector) { LOGGER.debug("Checking Database Connectivity"); final Project project = injector.getOrThrow(ProjectComponent.class) .getProject(); project.dbmses().forEachOrdered(dbms -> { final DbmsHandlerComponent dbmsHandlerComponent = injector .getOrThrow(DbmsHandlerComponent.class); final DbmsType dbmsType = DatabaseUtil .dbmsTypeOf(dbmsHandlerComponent, dbms); final DbmsMetadataHandler handler = dbmsType.getMetadataHandler(); try { LOGGER.info(handler.getDbmsInfoString(dbms)); } catch (final SQLException sqle) { throw new SpeedmentException("Unable to establish initial " + "connection with the database named " + dbms.getName() + ".", sqle); } }); }