Search in sources :

Example 1 with Query

use of org.jooq.Query in project collect by openforis.

the class RecordDao method execute.

public void execute(List<CollectStoreQuery> queries) {
    List<Query> internalQueries = new ArrayList<Query>(queries.size());
    for (CollectStoreQuery recordStoreQuery : queries) {
        internalQueries.add(recordStoreQuery.getInternalQuery());
    }
    Batch batch = dsl().batch(internalQueries);
    batch.execute();
}
Also used : InsertQuery(org.jooq.InsertQuery) UpdateQuery(org.jooq.UpdateQuery) Query(org.jooq.Query) StoreQuery(org.jooq.StoreQuery) SelectQuery(org.jooq.SelectQuery) Batch(org.jooq.Batch) ArrayList(java.util.ArrayList)

Example 2 with Query

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

the class Example_3_4_StatementsAndResults method run.

@Test
public void run() throws SQLException {
    Connection connection = connection();
    Tools.title("If you don't know whether a result set is produced with JDBC");
    try (PreparedStatement stmt = connection.prepareStatement("SELECT FIRST_NAME FROM AUTHOR")) {
        boolean moreResults = stmt.execute();
        do {
            if (moreResults) {
                try (ResultSet rs = stmt.getResultSet()) {
                    while (rs.next()) {
                        System.out.println(rs.getString(1));
                    }
                }
            } else {
                System.out.println(stmt.getUpdateCount());
            }
        } while ((moreResults = stmt.getMoreResults()) || stmt.getUpdateCount() != -1);
    }
    Tools.title("You always know whether a result set is produced with jOOQ, because of the type");
    Query q1 = DSL.using(connection).query("UPDATE AUTHOR SET LAST_NAME = LAST_NAME");
    System.out.println(q1.execute());
    ResultQuery<Record> q2 = DSL.using(connection).resultQuery("SELECT * FROM AUTHOR");
    System.out.println(q2.fetch());
}
Also used : ResultQuery(org.jooq.ResultQuery) Query(org.jooq.Query) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Record(org.jooq.Record) Test(org.junit.Test)

Example 3 with Query

use of org.jooq.Query 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 4 with Query

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

the class InterpreterMetaProvider method provide.

@Override
public Meta provide() {
    final Interpreter interpreter = new Interpreter(configuration);
    Configuration localConfiguration = configuration.derive();
    DSLContext ctx = DSL.using(localConfiguration);
    if (sources != null)
        for (Source source : sources) loadSource(ctx, source, interpreter);
    else
        for (Query query : queries) interpreter.accept(query);
    return interpreter.meta();
}
Also used : Configuration(org.jooq.Configuration) Query(org.jooq.Query) DSLContext(org.jooq.DSLContext) Source(org.jooq.Source)

Example 5 with Query

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

the class DefaultParseContext method parseWith.

private final Query parseWith(boolean parseSelect, Integer degree) {
    int parens = 0;
    while (parseIf('(')) parens++;
    parseKeyword("WITH");
    boolean recursive = parseKeywordIf("RECURSIVE");
    List<CommonTableExpression<?>> cte = new ArrayList<>();
    do {
        Name name = parseIdentifier();
        DerivedColumnList dcl = null;
        if (parseIf('(')) {
            List<Name> columnNames = parseIdentifiers();
            parse(')');
            dcl = name.fields(columnNames.toArray(EMPTY_NAME));
        }
        parseKeyword("AS");
        boolean materialized = parseKeywordIf("MATERIALIZED");
        boolean notMaterialized = !materialized && parseKeywordIf("NOT MATERIALIZED");
        parse('(');
        ResultQuery<?> resultQuery = (ResultQuery<?>) parseQuery(true, false);
        parse(')');
        cte.add(dcl != null ? materialized ? dcl.asMaterialized(resultQuery) : notMaterialized ? dcl.asNotMaterialized(resultQuery) : dcl.as(resultQuery) : materialized ? name.asMaterialized(resultQuery) : notMaterialized ? name.asNotMaterialized(resultQuery) : name.as(resultQuery));
    } while (parseIf(','));
    // TODO Better model API for WITH clause
    WithImpl with = (WithImpl) new WithImpl(dsl.configuration(), recursive).with(cte.toArray(EMPTY_COMMON_TABLE_EXPRESSION));
    Query result;
    if (!parseSelect && (peekKeyword("DELETE") || peekKeyword("DEL")))
        result = parseDelete(with, false);
    else if (!parseSelect && (peekKeyword("INSERT") || peekKeyword("INS")))
        result = parseInsert(with, false);
    else if (!parseSelect && peekKeyword("MERGE"))
        result = parseMerge(with);
    else if (peekSelect(true))
        result = parseSelect(degree, with);
    else if (!parseSelect && (peekKeyword("UPDATE") || peekKeyword("UPD")))
        result = parseUpdate(with, false);
    else if ((parseWhitespaceIf() || true) && done())
        throw exception("Missing statement after WITH");
    else
        throw exception("Unsupported statement after WITH");
    while (parens-- > 0) parse(')');
    return result;
}
Also used : ResultQuery(org.jooq.ResultQuery) Query(org.jooq.Query) DDLQuery(org.jooq.DDLQuery) CommonTableExpression(org.jooq.CommonTableExpression) ArrayList(java.util.ArrayList) DerivedColumnList(org.jooq.DerivedColumnList) ResultQuery(org.jooq.ResultQuery) Constraint(org.jooq.Constraint) DSL.constraint(org.jooq.impl.DSL.constraint) Name(org.jooq.Name) DSL.systemName(org.jooq.impl.DSL.systemName)

Aggregations

Query (org.jooq.Query)34 ArrayList (java.util.ArrayList)18 DSLContext (org.jooq.DSLContext)14 Record (org.jooq.Record)11 ResultQuery (org.jooq.ResultQuery)10 List (java.util.List)9 Configuration (org.jooq.Configuration)9 SQLException (java.sql.SQLException)8 Map (java.util.Map)8 BigDecimal (java.math.BigDecimal)6 Timestamp (java.sql.Timestamp)6 HashMap (java.util.HashMap)4 Constraint (org.jooq.Constraint)4 DDLQuery (org.jooq.DDLQuery)4 Result (org.jooq.Result)4 DSL.constraint (org.jooq.impl.DSL.constraint)4 Almura (com.almuradev.almura.Almura)3 ServerNotificationManager (com.almuradev.almura.feature.notification.ServerNotificationManager)3 BasicStore (com.almuradev.almura.feature.store.basic.BasicStore)3 BasicBuyingItem (com.almuradev.almura.feature.store.basic.listing.BasicBuyingItem)3