Search in sources :

Example 1 with ExecuteListener

use of org.jooq.ExecuteListener in project waltz by khartec.

the class MSSqlImportExportExample method main.

public static void main(String[] args) throws ParseException, IOException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);
    if (false) {
        System.out.println("-- saving");
        dsl.selectFrom(PERSON).fetch().formatCSV(new FileOutputStream("person.csv"), ',', "{null}");
    }
    if (true) {
        System.out.println("-- deleting");
        dsl.deleteFrom(PERSON).execute();
        dsl.transaction(cfg -> {
            // insert the identity insert statement
            ExecuteListener listener = new DefaultExecuteListener() {

                @Override
                public void renderEnd(ExecuteContext ctx) {
                    ctx.sql("SET IDENTITY_INSERT [person] ON " + ctx.sql());
                }
            };
            cfg.set(new DefaultExecuteListenerProvider(listener));
            DSLContext tx = DSL.using(cfg);
            System.out.println("-- loading");
            Loader<PersonRecord> loader = tx.loadInto(PERSON).loadCSV(new FileInputStream("person.csv")).fields(PERSON.fields()).nullString(// treat this from the csv as a database NULL value
            "{null}").execute();
            System.out.println("processed:" + loader.processed());
            System.out.println("stored:" + loader.stored());
            System.out.println("ignored:" + loader.ignored());
            loader.errors().forEach(e -> System.out.println("error:" + e.exception().getMessage()));
        });
    }
    System.out.println("-- done");
}
Also used : DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) DefaultExecuteListenerProvider(org.jooq.impl.DefaultExecuteListenerProvider) FileOutputStream(java.io.FileOutputStream) DSLContext(org.jooq.DSLContext) ExecuteContext(org.jooq.ExecuteContext) ExecuteListener(org.jooq.ExecuteListener) DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) PersonRecord(com.khartec.waltz.schema.tables.records.PersonRecord) FileInputStream(java.io.FileInputStream)

Example 2 with ExecuteListener

use of org.jooq.ExecuteListener in project jOOQ by jOOQ.

the class AbstractDatabase method create.

protected final DSLContext create(boolean muteExceptions) {
    // [#3800] Make sure that faulty queries are logged in a formatted
    // way to help users provide us with bug reports
    final Configuration configuration;
    try {
        configuration = create0().configuration();
    }// [#6226] This is mostly due to a wrong Maven groupId
     catch (NoSuchFieldError e) {
        log.error("NoSuchFieldError may happen when the jOOQ Open Source Edition (Maven groupId 'org.jooq') is used with a commercial SQLDialect. Use an appropriate groupId instead: 'org.jooq.trial', 'org.jooq.trial-java-8', 'org.jooq.trial-java-11', 'org.jooq.pro', 'org.jooq.pro-java-8', or 'org.jooq.pro-java-11'. See also: https://www.jooq.org/doc/latest/manual/getting-started/tutorials/jooq-in-7-steps/jooq-in-7-steps-step1/");
        throw e;
    }
    // [#9511] In some cases, it's better not to quote identifiers from
    // jOOQ-meta queries for better dialect interoperability. No
    // cases where quoting would have been necessary were found in
    // integration tests, or when looking for identifiers matching
    // [A-Za-z_$#][A-Za-z0-9_$#]+ in generated jOOQ-meta code.
    configuration.settings().setRenderQuotedNames(getRenderQuotedNames());
    if (muteExceptions) {
        return DSL.using(configuration);
    } else {
        final ExecuteListener newListener = new DefaultExecuteListener() {

            class SQLPerformanceWarning extends Exception {
            }

            @Override
            public void start(ExecuteContext ctx) {
                // SQLPerformanceWarning.
                if (!initialised) {
                    try {
                        DSL.using(configuration).selectOne().fetch();
                    }// [#7248] Unsupported dialects might not be able to run queries on the DUAL table
                     catch (DataAccessException e) {
                        log.debug("Error while running init query", e);
                    }
                    initialised = true;
                }
            }

            @Override
            public void executeStart(ExecuteContext ctx) {
                ctx.data("org.jooq.meta.AbstractDatabase.SQLPerformanceWarning.execute", new StopWatch());
            }

            @Override
            public void executeEnd(ExecuteContext ctx) {
                int s = getLogSlowQueriesAfterSeconds();
                if (s <= 0)
                    return;
                StopWatch watch = (StopWatch) ctx.data("org.jooq.meta.AbstractDatabase.SQLPerformanceWarning.execute");
                if (watch.split() > TimeUnit.SECONDS.toNanos(s)) {
                    watch.splitWarn("Slow SQL");
                    log.warn("Slow SQL", "jOOQ Meta executed a slow query (slower than " + s + " seconds, configured by configuration/generator/database/logSlowQueriesAfterSeconds)" + "\n\n" + "If you think this is a bug in jOOQ, please report it here: https://github.com/jOOQ/jOOQ/issues/new" + "\n\n```sql\n" + formatted(ctx.query()) + "```\n", new SQLPerformanceWarning());
                }
            }

            @Override
            public void fetchStart(ExecuteContext ctx) {
                ctx.data("org.jooq.meta.AbstractDatabase.SQLPerformanceWarning.fetch", new StopWatch());
            }

            @Override
            public void fetchEnd(ExecuteContext ctx) {
                int s = getLogSlowResultsAfterSeconds();
                if (s <= 0)
                    return;
                StopWatch watch = (StopWatch) ctx.data("org.jooq.meta.AbstractDatabase.SQLPerformanceWarning.fetch");
                if (watch.split() > TimeUnit.SECONDS.toNanos(s)) {
                    watch.splitWarn("Slow Result Fetching");
                    log.warn("Slow Result Fetching", "jOOQ Meta fetched a slow result (slower than " + s + " seconds, configured by configuration/generator/database/logSlowResultsAfterSeconds)" + "\n\n" + "If you think this is a bug in jOOQ, please report it here: https://github.com/jOOQ/jOOQ/issues/new" + "\n\n```sql\n" + formatted(ctx.query()) + "```\n", new SQLPerformanceWarning());
                }
            }

            @Override
            public void exception(ExecuteContext ctx) {
                log.warn("SQL exception", "Exception while executing meta query: " + (ctx.sqlException() != null ? ctx.sqlException().getMessage() : ctx.exception() != null ? ctx.exception().getMessage() : "No exception available") + "\n\n" + "If you think this is a bug in jOOQ, please report it here: https://github.com/jOOQ/jOOQ/issues/new" + "\n\n" + "Note you can mute some exceptions using the configuration/onError flag" + "\n\n```sql\n" + formatted(ctx.query()) + "```\n");
            }

            private String formatted(Query query) {
                return configuration.deriveSettings(s -> s.withRenderFormatted(true)).dsl().renderInlined(query);
            }
        };
        return configuration.deriveAppending(newListener).dsl();
    }
}
Also used : DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) Configuration(org.jooq.Configuration) Query(org.jooq.Query) ExecuteContext(org.jooq.ExecuteContext) ExecuteListener(org.jooq.ExecuteListener) DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) DataAccessException(org.jooq.exception.DataAccessException) StopWatch(org.jooq.tools.StopWatch)

Example 3 with ExecuteListener

use of org.jooq.ExecuteListener in project jOOQ by jOOQ.

the class ExecuteListeners method listeners.

/**
 * Provide delegate listeners from an <code>ExecuteContext</code>
 */
private static final ExecuteListener[][] listeners(ExecuteContext ctx) {
    List<ExecuteListener> list = null;
    // [#6580] Fetching server output may require some pre / post actions around the actual statement
    if (SettingsTools.getFetchServerOutputSize(0, ctx.settings()) > 0)
        (list = init(list)).add(new FetchServerOutputListener());
    // [#6051] The previously used StopWatchListener is no longer included by default
    if (!FALSE.equals(ctx.settings().isExecuteLogging())) {
        // we do not DEBUG log anyway.
        if (LOGGER_LISTENER_LOGGER.isDebugEnabled())
            (list = init(list)).add(new LoggerListener());
    }
    for (ExecuteListenerProvider provider : ctx.configuration().executeListenerProviders()) // Could be null after deserialisation
    if (provider != null)
        (list = init(list)).add(provider.provide());
    if (list == null)
        return null;
    ExecuteListener[] def = list.toArray(EMPTY_EXECUTE_LISTENER);
    ExecuteListener[] rev = null;
    return new ExecuteListener[][] { ctx.settings().getExecuteListenerStartInvocationOrder() != REVERSE ? def : (rev = Tools.reverse(def.clone())), ctx.settings().getExecuteListenerEndInvocationOrder() != REVERSE ? def : (rev != null ? rev : (rev = Tools.reverse(def.clone()))) };
}
Also used : ExecuteListenerProvider(org.jooq.ExecuteListenerProvider) ExecuteListener(org.jooq.ExecuteListener) LoggerListener(org.jooq.tools.LoggerListener)

Example 4 with ExecuteListener

use of org.jooq.ExecuteListener in project jOOQ by jOOQ.

the class ExecuteListeners method getAndStart.

/**
 * Initialise the provided {@link ExecuteListener} set and return a wrapper.
 * <p>
 * Call this if the {@link ExecuteListener#start(ExecuteContext)} event
 * should be triggered eagerly.
 */
static ExecuteListener getAndStart(ExecuteContext ctx) {
    ExecuteListener result = get(ctx);
    result.start(ctx);
    return result;
}
Also used : ExecuteListener(org.jooq.ExecuteListener)

Example 5 with ExecuteListener

use of org.jooq.ExecuteListener in project jOOQ by jOOQ.

the class AbstractQuery method execute.

@Override
public final int execute() {
    if (isExecutable()) {
        // Get the attached configuration of this query
        Configuration c = configuration();
        // [#1191] The following triggers a start event on all listeners.
        // This may be used to provide jOOQ with a JDBC connection,
        // in case this Query / Configuration was previously
        // deserialised
        DefaultExecuteContext ctx = new DefaultExecuteContext(c, this);
        ExecuteListener listener = ExecuteListeners.get(ctx);
        int result = 0;
        try {
            // [#8968] Keep start() event inside of lifecycle management
            listener.start(ctx);
            // [#385] If a statement was previously kept open
            if (keepStatement() && statement != null) {
                ctx.sql(rendered.sql);
                ctx.statement(statement);
                // [#3191] Pre-initialise the ExecuteContext with a previous connection, if available.
                ctx.connection(c.connectionProvider(), statement.getConnection());
                // [#6903] Increment and set the new statement execution count on re-execution
                ctx.withStatementExecutionCount(++statementExecutionCount);
            } else // [#385] First time statement preparing
            {
                listener.renderStart(ctx);
                rendered = getSQL0(ctx);
                ctx.sql(rendered.sql);
                listener.renderEnd(ctx);
                rendered.sql = ctx.sql();
                // ControlFlowSignals are thrown
                if (ctx.connection() == null)
                    if (ctx.configuration().connectionFactory() instanceof NoConnectionFactory)
                        throw new DetachedException("Cannot execute query. No JDBC Connection configured");
                    else
                        throw new DetachedException("Attempt to execute a blocking method (e.g. Query.execute() or ResultQuery.fetch()) " + "when only an R2BDC ConnectionFactory was configured. jOOQ's RowCountQuery and ResultQuery " + "extend Publisher, which allows for reactive streams implementations to subscribe to the " + "results of a jOOQ query. Simply embed your query in the stream, e.g. using Flux.from(query). " + "See also: https://www.jooq.org/doc/latest/manual/sql-execution/fetching/reactive-fetching/");
                listener.prepareStart(ctx);
                prepare(ctx);
                listener.prepareEnd(ctx);
                statement = ctx.statement();
            }
            // [#1856] [#4753] Set the query timeout onto the Statement
            int t = SettingsTools.getQueryTimeout(timeout, ctx.settings());
            if (t != 0)
                ctx.statement().setQueryTimeout(t);
            QueryPoolable p = SettingsTools.getQueryPoolable(poolable, ctx.settings());
            if (p == QueryPoolable.TRUE)
                ctx.statement().setPoolable(true);
            else if (p == QueryPoolable.FALSE)
                ctx.statement().setPoolable(false);
            if (// QueryParts may override this behaviour!
            executePreparedStatements(c.settings()) && // [#1520] Renderers may enforce static statements, too
            !TRUE.equals(ctx.data(DATA_FORCE_STATIC_STATEMENT))) {
                listener.bindStart(ctx);
                if (rendered.bindValues != null)
                    using(c).bindContext(ctx.statement()).visit(rendered.bindValues);
                listener.bindEnd(ctx);
            }
            result = execute(ctx, listener);
            return result;
        }// [#3427] ControlFlowSignals must not be passed on to ExecuteListners
         catch (ControlFlowSignal e) {
            throw e;
        } catch (RuntimeException e) {
            ctx.exception(e);
            listener.exception(ctx);
            throw ctx.exception();
        } catch (SQLException e) {
            ctx.sqlException(e);
            listener.exception(ctx);
            throw ctx.exception();
        } finally {
            // [#2385] Successful fetchLazy() needs to keep open resources
            if (!keepResultSet() || ctx.exception() != null) {
                Tools.safeClose(listener, ctx, keepStatement());
            }
            if (!keepStatement()) {
                statement = null;
                rendered = null;
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Query is not executable", this);
        return 0;
    }
}
Also used : Configuration(org.jooq.Configuration) SQLException(java.sql.SQLException) QueryPoolable(org.jooq.conf.QueryPoolable) DetachedException(org.jooq.exception.DetachedException) ExecuteListener(org.jooq.ExecuteListener) ControlFlowSignal(org.jooq.exception.ControlFlowSignal)

Aggregations

ExecuteListener (org.jooq.ExecuteListener)14 ExecuteContext (org.jooq.ExecuteContext)8 SQLException (java.sql.SQLException)4 ControlFlowSignal (org.jooq.exception.ControlFlowSignal)4 Connection (java.sql.Connection)3 DSLContext (org.jooq.DSLContext)3 DefaultExecuteListener (org.jooq.impl.DefaultExecuteListener)3 DefaultExecuteListenerProvider (org.jooq.impl.DefaultExecuteListenerProvider)3 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 Configuration (org.jooq.Configuration)2 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)2 PersonRecord (com.khartec.waltz.schema.tables.records.PersonRecord)1 ResultSet (java.sql.ResultSet)1 ArrayList (java.util.ArrayList)1 Arrays.asList (java.util.Arrays.asList)1 List (java.util.List)1 PersonRecord (org.finos.waltz.schema.tables.records.PersonRecord)1 ExecuteListenerProvider (org.jooq.ExecuteListenerProvider)1 Param (org.jooq.Param)1