Search in sources :

Example 1 with Clause

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

the class InsertQueryImpl method toInsertSelect.

@SuppressWarnings("unchecked")
private final QueryPart toInsertSelect(Context<?> ctx) {
    List<List<? extends Field<?>>> keys = conflictingKeys(ctx);
    if (!keys.isEmpty()) {
        Select<Record> rows = null;
        Set<Field<?>> fields = insertMaps.keysFlattened(ctx);
        // [#10989] INSERT .. SELECT .. ON DUPLICATE KEY IGNORE
        if (select != null) {
            Map<Field<?>, Field<?>> map = new HashMap<>();
            Field<?>[] names = Tools.fields(select.fields().length);
            List<Field<?>> f = new ArrayList<>(fields);
            for (int i = 0; i < fields.size() && i < names.length; i++) map.put(f.get(i), names[i]);
            rows = (Select<Record>) selectFrom(select.asTable(DSL.table(name("t")), names)).whereNotExists(selectOne().from(table()).where(matchByConflictingKeys(ctx, map)));
        } else // [#5089] Multi-row inserts need to explicitly generate UNION ALL
        // here. TODO: Refactor this logic to be more generally
        // reusable - i.e. ordinary UNION ALL emulation should be
        // re-used.
        {
            for (Map<Field<?>, Field<?>> map : insertMaps.maps()) {
                Select<Record> row = select(aliasedFields(map.entrySet().stream().filter(e -> fields.contains(e.getKey())).map(Entry::getValue).collect(toList()))).whereNotExists(selectOne().from(table()).where(matchByConflictingKeys(ctx, map)));
                if (rows == null)
                    rows = row;
                else
                    rows = rows.unionAll(row);
            }
        }
        return ctx.dsl().insertInto(table()).columns(fields).select(selectFrom(rows.asTable("t")));
    } else
        return DSL.sql("[ The ON DUPLICATE KEY IGNORE/UPDATE clause cannot be emulated when inserting into tables without any known keys : " + table() + " ]");
}
Also used : K_VALUES(org.jooq.impl.Keywords.K_VALUES) QueryPartListView.wrap(org.jooq.impl.QueryPartListView.wrap) UniqueKey(org.jooq.UniqueKey) Arrays(java.util.Arrays) Tools.map(org.jooq.impl.Tools.map) UNotYetImplemented(org.jooq.impl.QOM.UNotYetImplemented) InsertQuery(org.jooq.InsertQuery) Table(org.jooq.Table) MergeOnConditionStep(org.jooq.MergeOnConditionStep) Operator(org.jooq.Operator) Condition(org.jooq.Condition) Collections.singletonList(java.util.Collections.singletonList) K_DEFAULT_VALUES(org.jooq.impl.Keywords.K_DEFAULT_VALUES) Clause(org.jooq.Clause) Arrays.asList(java.util.Arrays.asList) K_IGNORE(org.jooq.impl.Keywords.K_IGNORE) Tools.unqualified(org.jooq.impl.Tools.unqualified) Map(java.util.Map) SQLDialect(org.jooq.SQLDialect) Scope(org.jooq.Scope) Tools.aliasedFields(org.jooq.impl.Tools.aliasedFields) Select(org.jooq.Select) DSL.constraint(org.jooq.impl.DSL.constraint) DSL.name(org.jooq.impl.DSL.name) WriteIfReadonly(org.jooq.conf.WriteIfReadonly) Collections.nCopies(java.util.Collections.nCopies) Name(org.jooq.Name) DSL.falseCondition(org.jooq.impl.DSL.falseCondition) Collection(java.util.Collection) Set(java.util.Set) DataExtendedKey(org.jooq.impl.Tools.DataExtendedKey) Field(org.jooq.Field) DSL.select(org.jooq.impl.DSL.select) DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST) INSERT_SELECT(org.jooq.Clause.INSERT_SELECT) Collectors(java.util.stream.Collectors) QueryPart(org.jooq.QueryPart) K_INTO(org.jooq.impl.Keywords.K_INTO) K_ON_DUPLICATE_KEY_UPDATE(org.jooq.impl.Keywords.K_ON_DUPLICATE_KEY_UPDATE) List(java.util.List) K_INSERT(org.jooq.impl.Keywords.K_INSERT) DATA_ON_DUPLICATE_KEY_WHERE(org.jooq.impl.Tools.DataKey.DATA_ON_DUPLICATE_KEY_WHERE) Context(org.jooq.Context) K_SET(org.jooq.impl.Keywords.K_SET) TableField(org.jooq.TableField) Entry(java.util.Map.Entry) INSERT(org.jooq.Clause.INSERT) DATA_INSERT_SELECT(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT) K_ON_CONFLICT(org.jooq.impl.Keywords.K_ON_CONFLICT) TRUE(java.lang.Boolean.TRUE) Tools.anyMatch(org.jooq.impl.Tools.anyMatch) DERBY(org.jooq.SQLDialect.DERBY) Merge(org.jooq.Merge) HashMap(java.util.HashMap) INSERT_ON_DUPLICATE_KEY_UPDATE_ASSIGNMENT(org.jooq.Clause.INSERT_ON_DUPLICATE_KEY_UPDATE_ASSIGNMENT) DSL.row(org.jooq.impl.DSL.row) ArrayList(java.util.ArrayList) MergeNotMatchedStep(org.jooq.MergeNotMatchedStep) K_ON_CONSTRAINT(org.jooq.impl.Keywords.K_ON_CONSTRAINT) DATA_CONSTRAINT_REFERENCE(org.jooq.impl.Tools.BooleanDataKey.DATA_CONSTRAINT_REFERENCE) Identity(org.jooq.Identity) DSL.selectFrom(org.jooq.impl.DSL.selectFrom) INSERT_RETURNING(org.jooq.Clause.INSERT_RETURNING) Tools.flattenCollection(org.jooq.impl.Tools.flattenCollection) K_DEFAULT(org.jooq.impl.Keywords.K_DEFAULT) INSERT_ON_DUPLICATE_KEY_UPDATE(org.jooq.Clause.INSERT_ON_DUPLICATE_KEY_UPDATE) K_DO_NOTHING(org.jooq.impl.Keywords.K_DO_NOTHING) INSERT_INSERT_INTO(org.jooq.Clause.INSERT_INSERT_INTO) MYSQL(org.jooq.SQLDialect.MYSQL) Record(org.jooq.Record) Tools.collect(org.jooq.impl.Tools.collect) K_DO_UPDATE(org.jooq.impl.Keywords.K_DO_UPDATE) StringUtils(org.jooq.tools.StringUtils) DSL.selectOne(org.jooq.impl.DSL.selectOne) K_WHERE(org.jooq.impl.Keywords.K_WHERE) Constraint(org.jooq.Constraint) DSL.one(org.jooq.impl.DSL.one) Configuration(org.jooq.Configuration) Collectors.toList(java.util.stream.Collectors.toList) H2(org.jooq.SQLDialect.H2) MARIADB(org.jooq.SQLDialect.MARIADB) EMPTY_FIELD(org.jooq.impl.Tools.EMPTY_FIELD) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DSL.constraint(org.jooq.impl.DSL.constraint) Constraint(org.jooq.Constraint) Field(org.jooq.Field) TableField(org.jooq.TableField) Entry(java.util.Map.Entry) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) Record(org.jooq.Record)

Example 2 with Clause

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

the class SelectQueryImpl method accept0.

final void accept0(Context<?> context) {
    boolean topLevelCte = false;
    // Subquery scopes are started in AbstractContext
    if (context.subqueryLevel() == 0) {
        context.scopeStart();
        if (topLevelCte |= (context.data(DATA_TOP_LEVEL_CTE) == null))
            context.data(DATA_TOP_LEVEL_CTE, new TopLevelCte());
    }
    SQLDialect dialect = context.dialect();
    // [#2791] TODO: Instead of explicitly manipulating these data() objects, future versions
    // of jOOQ should implement a push / pop semantics to clearly delimit such scope.
    Object renderTrailingLimit = context.data(DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE);
    Object localWindowDefinitions = context.data(DATA_WINDOW_DEFINITIONS);
    Name[] selectAliases = (Name[]) context.data(DATA_SELECT_ALIASES);
    try {
        List<Field<?>> originalFields = null;
        List<Field<?>> alternativeFields = null;
        if (selectAliases != null) {
            context.data().remove(DATA_SELECT_ALIASES);
            alternativeFields = map(originalFields = getSelect(), (f, i) -> i < selectAliases.length ? f.as(selectAliases[i]) : f);
        }
        if (TRUE.equals(renderTrailingLimit))
            context.data().remove(DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE);
        // [#5127] Lazy initialise this map
        if (localWindowDefinitions != null)
            context.data(DATA_WINDOW_DEFINITIONS, null);
        if (intoTable != null && !TRUE.equals(context.data(DATA_OMIT_INTO_CLAUSE)) && EMULATE_SELECT_INTO_AS_CTAS.contains(dialect)) {
            context.data(DATA_OMIT_INTO_CLAUSE, true, c -> c.visit(createTable(intoTable).as(this)));
            return;
        }
        if (with != null)
            context.visit(with);
        else if (topLevelCte)
            markTopLevelCteAndAccept(context, c -> {
            });
        pushWindow(context);
        Boolean wrapDerivedTables = (Boolean) context.data(DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES);
        if (TRUE.equals(wrapDerivedTables)) {
            context.sqlIndentStart('(').data().remove(DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES);
        }
        switch(dialect) {
            case CUBRID:
            case FIREBIRD:
            case MYSQL:
            case YUGABYTEDB:
                {
                    if (getLimit().isApplicable() && getLimit().withTies())
                        toSQLReferenceLimitWithWindowFunctions(context);
                    else
                        toSQLReferenceLimitDefault(context, originalFields, alternativeFields);
                    break;
                }
            // By default, render the dialect's limit clause
            default:
                {
                    toSQLReferenceLimitDefault(context, originalFields, alternativeFields);
                    break;
                }
        }
        // [#1296] [#7328] FOR UPDATE is emulated in some dialects using hints
        if (forLock != null)
            context.visit(forLock);
        // end-of-query clauses are appended to the end of a query
        if (!StringUtils.isBlank(option))
            context.formatSeparator().sql(option);
        if (TRUE.equals(wrapDerivedTables))
            context.sqlIndentEnd(')').data(DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES, true);
    } finally {
        context.data(DATA_WINDOW_DEFINITIONS, localWindowDefinitions);
        if (renderTrailingLimit != null)
            context.data(DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE, renderTrailingLimit);
        if (selectAliases != null)
            context.data(DATA_SELECT_ALIASES, selectAliases);
    }
    if (context.subqueryLevel() == 0)
        context.scopeEnd();
}
Also used : Internal.isub(org.jooq.impl.Internal.isub) Tools.aliased(org.jooq.impl.Tools.aliased) UnmodifiableList(org.jooq.impl.QOM.UnmodifiableList) DSL.emptyGroupingSet(org.jooq.impl.DSL.emptyGroupingSet) K_BY(org.jooq.impl.Keywords.K_BY) Arrays.asList(java.util.Arrays.asList) DSL.createTable(org.jooq.impl.DSL.createTable) Map(java.util.Map) QualifiedAsterisk(org.jooq.QualifiedAsterisk) SQLDialect(org.jooq.SQLDialect) Scope(org.jooq.Scope) Select(org.jooq.Select) SELECT_START_WITH(org.jooq.Clause.SELECT_START_WITH) DSL.partitionBy(org.jooq.impl.DSL.partitionBy) QueryPartCollectionView.wrap(org.jooq.impl.QueryPartCollectionView.wrap) Tools.isWindow(org.jooq.impl.Tools.isWindow) DataExtendedKey(org.jooq.impl.Tools.DataExtendedKey) DATA_TRANSFORM_ROWNUM_TO_LIMIT(org.jooq.impl.Tools.DataExtendedKey.DATA_TRANSFORM_ROWNUM_TO_LIMIT) TableField(org.jooq.TableField) SUPPORT_NATIVE_EXCEPT(org.jooq.impl.AsteriskImpl.SUPPORT_NATIVE_EXCEPT) DSL.noCondition(org.jooq.impl.DSL.noCondition) K_START_WITH(org.jooq.impl.Keywords.K_START_WITH) DATA_INSERT_SELECT(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT) TRUE(java.lang.Boolean.TRUE) DERBY(org.jooq.SQLDialect.DERBY) EXCEPT_ALL(org.jooq.impl.CombineOperator.EXCEPT_ALL) DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE(org.jooq.impl.Tools.BooleanDataKey.DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE) DSL.jsonArrayAgg(org.jooq.impl.DSL.jsonArrayAgg) K_WITH_READ_ONLY(org.jooq.impl.Keywords.K_WITH_READ_ONLY) LinkedHashMap(java.util.LinkedHashMap) K_ORDER_BY(org.jooq.impl.Keywords.K_ORDER_BY) Tools.autoAlias(org.jooq.impl.Tools.autoAlias) INTERSECT(org.jooq.impl.CombineOperator.INTERSECT) VARCHAR(org.jooq.impl.SQLDataType.VARCHAR) XML(org.jooq.impl.SQLDataType.XML) DATA_OMIT_INTO_CLAUSE(org.jooq.impl.Tools.BooleanDataKey.DATA_OMIT_INTO_CLAUSE) DATA_DML_TARGET_TABLE(org.jooq.impl.Tools.DataKey.DATA_DML_TARGET_TABLE) MYSQL(org.jooq.SQLDialect.MYSQL) DATA_COLLECTED_SEMI_ANTI_JOIN(org.jooq.impl.Tools.DataKey.DATA_COLLECTED_SEMI_ANTI_JOIN) K_WITH_CHECK_OPTION(org.jooq.impl.Keywords.K_WITH_CHECK_OPTION) K_FROM(org.jooq.impl.Keywords.K_FROM) Comparator(org.jooq.Comparator) SelectFieldOrAsterisk(org.jooq.SelectFieldOrAsterisk) DSL.jsonbArrayAgg(org.jooq.impl.DSL.jsonbArrayAgg) DATA_COLLECT_SEMI_ANTI_JOIN(org.jooq.impl.Tools.BooleanDataKey.DATA_COLLECT_SEMI_ANTI_JOIN) FIREBIRD(org.jooq.SQLDialect.FIREBIRD) K_WHERE(org.jooq.impl.Keywords.K_WHERE) SELECT(org.jooq.Clause.SELECT) DSL.xmlattributes(org.jooq.impl.DSL.xmlattributes) JoinType(org.jooq.JoinType) IGNITE(org.jooq.SQLDialect.IGNITE) MARIADB(org.jooq.SQLDialect.MARIADB) NO_SUPPORT_ABSENT_ON_NULL(org.jooq.impl.JSONNull.NO_SUPPORT_ABSENT_ON_NULL) K_DISTINCT_ON(org.jooq.impl.Keywords.K_DISTINCT_ON) SelectQuery(org.jooq.SelectQuery) DSL.table(org.jooq.impl.DSL.table) INTERSECT_ALL(org.jooq.impl.CombineOperator.INTERSECT_ALL) Row(org.jooq.Row) IntStream.range(java.util.stream.IntStream.range) SELECT_WINDOW(org.jooq.Clause.SELECT_WINDOW) BiFunction(java.util.function.BiFunction) Table(org.jooq.Table) DSL.rowNumber(org.jooq.impl.DSL.rowNumber) Operator(org.jooq.Operator) ForLockWaitMode(org.jooq.impl.ForLock.ForLockWaitMode) SelectLimitPercentStep(org.jooq.SelectLimitPercentStep) Clause(org.jooq.Clause) SELECT_SELECT(org.jooq.Clause.SELECT_SELECT) NO_SUPPORT_UNQUALIFIED_COMBINED(org.jooq.impl.AsteriskImpl.NO_SUPPORT_UNQUALIFIED_COMBINED) JSONB(org.jooq.impl.SQLDataType.JSONB) DataKey(org.jooq.impl.Tools.DataKey) Tools.aliasedFields(org.jooq.impl.Tools.aliasedFields) SELECT_FROM(org.jooq.Clause.SELECT_FROM) K_TOP(org.jooq.impl.Keywords.K_TOP) GroupField(org.jooq.GroupField) OR(org.jooq.Operator.OR) DataType(org.jooq.DataType) DSL.name(org.jooq.impl.DSL.name) K_HAVING(org.jooq.impl.Keywords.K_HAVING) SELECT_CONNECT_BY(org.jooq.Clause.SELECT_CONNECT_BY) Name(org.jooq.Name) Collection(java.util.Collection) SelectLimitStep(org.jooq.SelectLimitStep) Field(org.jooq.Field) DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST) CUBRID(org.jooq.SQLDialect.CUBRID) SELECT_UNION(org.jooq.Clause.SELECT_UNION) K_QUALIFY(org.jooq.impl.Keywords.K_QUALIFY) EXCEPT(org.jooq.impl.CombineOperator.EXCEPT) K_INTO(org.jooq.impl.Keywords.K_INTO) Tools.containsUnaliasedTable(org.jooq.impl.Tools.containsUnaliasedTable) SelectWithTiesStep(org.jooq.SelectWithTiesStep) JSON(org.jooq.impl.SQLDataType.JSON) Entry(java.util.Map.Entry) K_DISTINCT(org.jooq.impl.Keywords.K_DISTINCT) Tools.anyMatch(org.jooq.impl.Tools.anyMatch) ResultSetMetaData(java.sql.ResultSetMetaData) K_SELECT(org.jooq.impl.Keywords.K_SELECT) K_SIBLINGS(org.jooq.impl.Keywords.K_SIBLINGS) SELECT_HAVING(org.jooq.Clause.SELECT_HAVING) INLINED(org.jooq.conf.ParamType.INLINED) Function(java.util.function.Function) K_CONNECT_BY(org.jooq.impl.Keywords.K_CONNECT_BY) TableLike(org.jooq.TableLike) Tools.fieldArray(org.jooq.impl.Tools.fieldArray) DSL.inline(org.jooq.impl.DSL.inline) K_PERCENT(org.jooq.impl.Keywords.K_PERCENT) SelectHavingStep(org.jooq.SelectHavingStep) DataAccessException(org.jooq.exception.DataAccessException) DATA_NESTED_SET_OPERATIONS(org.jooq.impl.Tools.BooleanDataKey.DATA_NESTED_SET_OPERATIONS) SELECT_INTERSECT(org.jooq.Clause.SELECT_INTERSECT) Consumer(java.util.function.Consumer) SortField(org.jooq.SortField) Multiset.returningClob(org.jooq.impl.Multiset.returningClob) H2(org.jooq.SQLDialect.H2) Tools.unalias(org.jooq.impl.Tools.unalias) K_WINDOW(org.jooq.impl.Keywords.K_WINDOW) Arrays(java.util.Arrays) DSL.orderBy(org.jooq.impl.DSL.orderBy) POSTGRES(org.jooq.SQLDialect.POSTGRES) DATA_UNALIAS_ALIASED_EXPRESSIONS(org.jooq.impl.Tools.BooleanDataKey.DATA_UNALIAS_ALIASED_EXPRESSIONS) JOIN(org.jooq.JoinType.JOIN) Condition(org.jooq.Condition) DSL.trueCondition(org.jooq.impl.DSL.trueCondition) EMULATE_WITH_GROUP_CONCAT(org.jooq.impl.JSONArrayAgg.EMULATE_WITH_GROUP_CONCAT) SelectField(org.jooq.SelectField) Tools.unqualified(org.jooq.impl.Tools.unqualified) CommonTableExpressionList.markTopLevelCteAndAccept(org.jooq.impl.CommonTableExpressionList.markTopLevelCteAndAccept) JSONObjectNullStep(org.jooq.JSONObjectNullStep) K_NOCYCLE(org.jooq.impl.Keywords.K_NOCYCLE) Set(java.util.Set) Tools.camelCase(org.jooq.impl.Tools.camelCase) QueryPart(org.jooq.QueryPart) Tools.traverseJoins(org.jooq.impl.Tools.traverseJoins) SELECT_UNION_ALL(org.jooq.Clause.SELECT_UNION_ALL) Tools.qualify(org.jooq.impl.Tools.qualify) N_LEVEL(org.jooq.impl.Names.N_LEVEL) Materialized(org.jooq.impl.QOM.Materialized) DSL.jsonObject(org.jooq.impl.DSL.jsonObject) K_AND(org.jooq.impl.Keywords.K_AND) DSL.xmlagg(org.jooq.impl.DSL.xmlagg) DATA_SELECT_INTO_TABLE(org.jooq.impl.Tools.DataKey.DATA_SELECT_INTO_TABLE) XML(org.jooq.XML) K_GROUP_BY(org.jooq.impl.Keywords.K_GROUP_BY) CompareCondition(org.jooq.impl.QOM.CompareCondition) DSL.row(org.jooq.impl.DSL.row) DSL.xmlelement(org.jooq.impl.DSL.xmlelement) ArrayList(java.util.ArrayList) Tools.isNotEmpty(org.jooq.impl.Tools.isNotEmpty) SELECT_INTO(org.jooq.Clause.SELECT_INTO) Transformations.transformRownum(org.jooq.impl.Transformations.transformRownum) SQLITE(org.jooq.SQLDialect.SQLITE) SELECT_WHERE(org.jooq.Clause.SELECT_WHERE) Record(org.jooq.Record) RIGHT_OUTER_JOIN(org.jooq.JoinType.RIGHT_OUTER_JOIN) JSONObjectReturningStep(org.jooq.JSONObjectReturningStep) K_MATERIALIZE(org.jooq.impl.Keywords.K_MATERIALIZE) K_ORDER(org.jooq.impl.Keywords.K_ORDER) DATA_TOP_LEVEL_CTE(org.jooq.impl.Tools.DataKey.DATA_TOP_LEVEL_CTE) SELECT_INTERSECT_ALL(org.jooq.Clause.SELECT_INTERSECT_ALL) StringUtils(org.jooq.tools.StringUtils) YUGABYTEDB(org.jooq.SQLDialect.YUGABYTEDB) UNION_ALL(org.jooq.impl.CombineOperator.UNION_ALL) ArrayDeque(java.util.ArrayDeque) ForLockMode(org.jooq.impl.ForLock.ForLockMode) TableOnStep(org.jooq.TableOnStep) Tools.map(org.jooq.impl.Tools.map) WindowDefinition(org.jooq.WindowDefinition) DSL.jsonbObject(org.jooq.impl.DSL.jsonbObject) Transformations.transformQualify(org.jooq.impl.Transformations.transformQualify) SelectOffsetStep(org.jooq.SelectOffsetStep) DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES(org.jooq.impl.Tools.BooleanDataKey.DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES) K_INLINE(org.jooq.impl.Keywords.K_INLINE) DSL.regexpReplaceAll(org.jooq.impl.DSL.regexpReplaceAll) DATA_SELECT_ALIASES(org.jooq.impl.Tools.DataKey.DATA_SELECT_ALIASES) JSONArrayAgg.patchOracleArrayAggBug(org.jooq.impl.JSONArrayAgg.patchOracleArrayAggBug) SELECT_EXCEPT(org.jooq.Clause.SELECT_EXCEPT) DEFAULT(org.jooq.SQLDialect.DEFAULT) Tools.selectQueryImpl(org.jooq.impl.Tools.selectQueryImpl) SELECT_GROUP_BY(org.jooq.Clause.SELECT_GROUP_BY) JooqLogger(org.jooq.tools.JooqLogger) Collections.emptyList(java.util.Collections.emptyList) DSL.falseCondition(org.jooq.impl.DSL.falseCondition) JSONEntry(org.jooq.JSONEntry) DATA_WINDOW_DEFINITIONS(org.jooq.impl.Tools.DataKey.DATA_WINDOW_DEFINITIONS) HSQLDB(org.jooq.SQLDialect.HSQLDB) List(java.util.List) Context(org.jooq.Context) DATA_OVERRIDE_ALIASES_IN_ORDER_BY(org.jooq.impl.Tools.DataKey.DATA_OVERRIDE_ALIASES_IN_ORDER_BY) TablePartitionByStep(org.jooq.TablePartitionByStep) Tools.recordType(org.jooq.impl.Tools.recordType) DSL.key(org.jooq.impl.DSL.key) ForeignKey(org.jooq.ForeignKey) Deque(java.util.Deque) BooleanDataKey(org.jooq.impl.Tools.BooleanDataKey) UNION(org.jooq.impl.CombineOperator.UNION) DSL.asterisk(org.jooq.impl.DSL.asterisk) SELECT_EXCEPT_ALL(org.jooq.Clause.SELECT_EXCEPT_ALL) Tools.hasAmbiguousNames(org.jooq.impl.Tools.hasAmbiguousNames) DSL.unquotedName(org.jooq.impl.DSL.unquotedName) Tools.isEmpty(org.jooq.impl.Tools.isEmpty) DESC(org.jooq.SortOrder.DESC) N_ROWNUM(org.jooq.impl.Names.N_ROWNUM) DSL.one(org.jooq.impl.DSL.one) Configuration(org.jooq.Configuration) TableOptionalOnStep(org.jooq.TableOptionalOnStep) SELECT_ORDER_BY(org.jooq.Clause.SELECT_ORDER_BY) LEFT_OUTER_JOIN(org.jooq.JoinType.LEFT_OUTER_JOIN) DSL.generateSeries(org.jooq.impl.DSL.generateSeries) OrderField(org.jooq.OrderField) Collections(java.util.Collections) TableField(org.jooq.TableField) GroupField(org.jooq.GroupField) Field(org.jooq.Field) SortField(org.jooq.SortField) SelectField(org.jooq.SelectField) OrderField(org.jooq.OrderField) SQLDialect(org.jooq.SQLDialect) DSL.jsonObject(org.jooq.impl.DSL.jsonObject) DSL.jsonbObject(org.jooq.impl.DSL.jsonbObject) Name(org.jooq.Name) DSL.unquotedName(org.jooq.impl.DSL.unquotedName)

Example 3 with Clause

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

the class MergeImpl method toSQLStandard.

private final void toSQLStandard(Context<?> ctx) {
    ctx.start(MERGE_MERGE_INTO).visit(K_MERGE_INTO).sql(' ').declareTables(true, c -> c.visit(table)).end(MERGE_MERGE_INTO).formatSeparator().start(MERGE_USING).visit(K_USING).sql(' ');
    ctx.declareTables(true, c1 -> c1.data(DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES, true, c2 -> {
        // in its MERGE statement.
        if (usingDual) {
            switch(c2.family()) {
                case DERBY:
                    c2.visit(new Dual());
                    break;
                default:
                    c2.visit(DSL.selectOne());
                    break;
            }
        } else
            c2.visit(using);
    }));
    boolean onParentheses = false;
    ctx.end(MERGE_USING).formatSeparator().start(MERGE_ON).visit(K_ON).sql(onParentheses ? " (" : " ").visit(on).sql(onParentheses ? ")" : "").end(MERGE_ON).start(MERGE_WHEN_MATCHED_THEN_UPDATE).start(MERGE_SET);
    // [#7291] Multi MATCHED emulation
    boolean emulate = false;
    boolean requireMatchedConditions = false;
    // [#10054] TODO: Skip all WHEN MATCHED clauses after a WHEN MATCHED clause with no search condition
    if (NO_SUPPORT_CONDITION_AFTER_NO_CONDITION.contains(ctx.dialect())) {
        boolean withoutMatchedConditionFound = false;
        for (MatchedClause m : matched) {
            if (requireMatchedConditions |= withoutMatchedConditionFound)
                break;
            withoutMatchedConditionFound |= m.condition instanceof NoCondition;
        }
    }
    emulateCheck: if ((NO_SUPPORT_MULTI.contains(ctx.dialect()) && matched.size() > 1)) {
        boolean matchUpdate = false;
        boolean matchDelete = false;
        for (MatchedClause m : matched) {
            if (m.delete) {
                if (emulate |= matchDelete)
                    break emulateCheck;
                matchDelete = true;
            } else {
                if (emulate |= matchUpdate)
                    break emulateCheck;
                matchUpdate = true;
            }
        }
    }
    if (emulate) {
        MatchedClause update = null;
        MatchedClause delete = null;
        Condition negate = noCondition();
        for (MatchedClause m : matched) {
            Condition condition = negate.and(m.condition);
            if (m.delete) {
                if (delete == null)
                    delete = new MatchedClause(noCondition(), true);
                delete.condition = delete.condition.or(condition);
            } else {
                if (update == null)
                    update = new MatchedClause(noCondition());
                for (Entry<Field<?>, Field<?>> e : m.updateMap.entrySet()) {
                    Field<?> exp = update.updateMap.get(e.getKey());
                    if (exp instanceof CaseConditionStepImpl)
                        ((CaseConditionStepImpl) exp).when(negate.and(condition), e.getValue());
                    else
                        update.updateMap.put(e.getKey(), when(negate.and(condition), (Field) e.getValue()).else_(e.getKey()));
                }
                update.condition = update.condition.or(condition);
            }
            if (REQUIRE_NEGATION.contains(ctx.dialect()))
                negate = negate.andNot(m.condition instanceof NoCondition ? trueCondition() : m.condition);
        }
        {
            if (delete != null)
                toSQLMatched(ctx, delete, requireMatchedConditions);
            if (update != null)
                toSQLMatched(ctx, update, requireMatchedConditions);
        }
    } else // [#7291] Workaround for https://github.com/h2database/h2database/issues/2552
    if (REQUIRE_NEGATION.contains(ctx.dialect())) {
        Condition negate = noCondition();
        for (MatchedClause m : matched) {
            toSQLMatched(ctx, new MatchedClause(negate.and(m.condition), m.delete, m.updateMap), requireMatchedConditions);
            negate = negate.andNot(m.condition instanceof NoCondition ? trueCondition() : m.condition);
        }
    } else {
        for (MatchedClause m : matched) toSQLMatched(ctx, m, requireMatchedConditions);
    }
    ctx.end(MERGE_SET).end(MERGE_WHEN_MATCHED_THEN_UPDATE).start(MERGE_WHEN_NOT_MATCHED_THEN_INSERT);
    for (NotMatchedClause m : notMatched) toSQLNotMatched(ctx, m);
    ctx.end(MERGE_WHEN_NOT_MATCHED_THEN_INSERT);
}
Also used : QueryPartListView.wrap(org.jooq.impl.QueryPartListView.wrap) THROW(org.jooq.conf.WriteIfReadonly.THROW) Arrays(java.util.Arrays) DSL.condition(org.jooq.impl.DSL.condition) DSL.when(org.jooq.impl.DSL.when) Condition(org.jooq.Condition) DSL.trueCondition(org.jooq.impl.DSL.trueCondition) K_UPDATE(org.jooq.impl.Keywords.K_UPDATE) Record1(org.jooq.Record1) Map(java.util.Map) MERGE_SET_ASSIGNMENT(org.jooq.Clause.MERGE_SET_ASSIGNMENT) MergeMatchedSetMoreStep(org.jooq.MergeMatchedSetMoreStep) SQLDialect(org.jooq.SQLDialect) Select(org.jooq.Select) DSL.exists(org.jooq.impl.DSL.exists) K_NOT(org.jooq.impl.Keywords.K_NOT) MERGE(org.jooq.Clause.MERGE) Set(java.util.Set) DataExtendedKey(org.jooq.impl.Tools.DataExtendedKey) K_MATCHED(org.jooq.impl.Keywords.K_MATCHED) Serializable(java.io.Serializable) QueryPart(org.jooq.QueryPart) Tools.filter(org.jooq.impl.Tools.filter) K_AS(org.jooq.impl.Keywords.K_AS) DSL.noCondition(org.jooq.impl.DSL.noCondition) MergeMatchedThenStep(org.jooq.MergeMatchedThenStep) K_AND(org.jooq.impl.Keywords.K_AND) MergeKeyStep9(org.jooq.MergeKeyStep9) MergeKeyStep8(org.jooq.MergeKeyStep8) MERGE_WHEN_MATCHED_THEN_UPDATE(org.jooq.Clause.MERGE_WHEN_MATCHED_THEN_UPDATE) MergeKeyStep1(org.jooq.MergeKeyStep1) MergeKeyStep3(org.jooq.MergeKeyStep3) MergeKeyStep2(org.jooq.MergeKeyStep2) MergeKeyStep5(org.jooq.MergeKeyStep5) MergeKeyStep4(org.jooq.MergeKeyStep4) MergeKeyStep7(org.jooq.MergeKeyStep7) ArrayList(java.util.ArrayList) MergeKeyStep6(org.jooq.MergeKeyStep6) LinkedHashMap(java.util.LinkedHashMap) MERGE_MERGE_INTO(org.jooq.Clause.MERGE_MERGE_INTO) MergeNotMatchedValuesStepN(org.jooq.MergeNotMatchedValuesStepN) MergeUsingStep(org.jooq.MergeUsingStep) DSL.notExists(org.jooq.impl.DSL.notExists) MERGE_ON(org.jooq.Clause.MERGE_ON) Record(org.jooq.Record) IGNORE(org.jooq.conf.WriteIfReadonly.IGNORE) FIREBIRD(org.jooq.SQLDialect.FIREBIRD) K_ON(org.jooq.impl.Keywords.K_ON) StringUtils(org.jooq.tools.StringUtils) MERGE_SET(org.jooq.Clause.MERGE_SET) K_WHERE(org.jooq.impl.Keywords.K_WHERE) EMPTY_FIELD(org.jooq.impl.Tools.EMPTY_FIELD) MergeNotMatchedValuesStep10(org.jooq.MergeNotMatchedValuesStep10) K_VALUES(org.jooq.impl.Keywords.K_VALUES) UniqueKey(org.jooq.UniqueKey) MergeNotMatchedValuesStep12(org.jooq.MergeNotMatchedValuesStep12) Tools.map(org.jooq.impl.Tools.map) MergeNotMatchedValuesStep11(org.jooq.MergeNotMatchedValuesStep11) MergeKeyStep19(org.jooq.MergeKeyStep19) MergeNotMatchedValuesStep14(org.jooq.MergeNotMatchedValuesStep14) UNotYetImplemented(org.jooq.impl.QOM.UNotYetImplemented) MergeNotMatchedValuesStep13(org.jooq.MergeNotMatchedValuesStep13) MergeNotMatchedValuesStep16(org.jooq.MergeNotMatchedValuesStep16) MergeNotMatchedValuesStep15(org.jooq.MergeNotMatchedValuesStep15) MergeKeyStep15(org.jooq.MergeKeyStep15) MergeKeyStep16(org.jooq.MergeKeyStep16) Table(org.jooq.Table) MergeKeyStep17(org.jooq.MergeKeyStep17) MergeOnConditionStep(org.jooq.MergeOnConditionStep) MergeKeyStep18(org.jooq.MergeKeyStep18) Operator(org.jooq.Operator) MergeKeyStep11(org.jooq.MergeKeyStep11) DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES(org.jooq.impl.Tools.BooleanDataKey.DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES) MergeKeyStep12(org.jooq.MergeKeyStep12) MergeKeyStep13(org.jooq.MergeKeyStep13) SQL(org.jooq.SQL) MergeKeyStep14(org.jooq.MergeKeyStep14) MergeKeyStep10(org.jooq.MergeKeyStep10) Clause(org.jooq.Clause) K_DELETE(org.jooq.impl.Keywords.K_DELETE) DataTypeException(org.jooq.exception.DataTypeException) MergeNotMatchedValuesStep21(org.jooq.MergeNotMatchedValuesStep21) MergeNotMatchedValuesStep20(org.jooq.MergeNotMatchedValuesStep20) MergeOnStep(org.jooq.MergeOnStep) MergeNotMatchedValuesStep22(org.jooq.MergeNotMatchedValuesStep22) MergeNotMatchedSetMoreStep(org.jooq.MergeNotMatchedSetMoreStep) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) Field(org.jooq.Field) MergeKeyStep22(org.jooq.MergeKeyStep22) MergeNotMatchedValuesStep9(org.jooq.MergeNotMatchedValuesStep9) HSQLDB(org.jooq.SQLDialect.HSQLDB) MergeNotMatchedValuesStep8(org.jooq.MergeNotMatchedValuesStep8) List(java.util.List) MergeKeyStep20(org.jooq.MergeKeyStep20) MergeNotMatchedValuesStep7(org.jooq.MergeNotMatchedValuesStep7) K_INSERT(org.jooq.impl.Keywords.K_INSERT) MergeKeyStep21(org.jooq.MergeKeyStep21) MergeNotMatchedValuesStep6(org.jooq.MergeNotMatchedValuesStep6) Context(org.jooq.Context) MergeNotMatchedValuesStep5(org.jooq.MergeNotMatchedValuesStep5) K_SET(org.jooq.impl.Keywords.K_SET) MergeNotMatchedValuesStep4(org.jooq.MergeNotMatchedValuesStep4) K_KEY(org.jooq.impl.Keywords.K_KEY) MergeNotMatchedValuesStep3(org.jooq.MergeNotMatchedValuesStep3) MergeNotMatchedValuesStep2(org.jooq.MergeNotMatchedValuesStep2) Entry(java.util.Map.Entry) MergeNotMatchedValuesStep1(org.jooq.MergeNotMatchedValuesStep1) MergeNotMatchedValuesStep18(org.jooq.MergeNotMatchedValuesStep18) MergeNotMatchedValuesStep17(org.jooq.MergeNotMatchedValuesStep17) MergeNotMatchedValuesStep19(org.jooq.MergeNotMatchedValuesStep19) MERGE_WHEN_NOT_MATCHED_THEN_INSERT(org.jooq.Clause.MERGE_WHEN_NOT_MATCHED_THEN_INSERT) K_UPSERT(org.jooq.impl.Keywords.K_UPSERT) Tools.nullSafe(org.jooq.impl.Tools.nullSafe) K_USING(org.jooq.impl.Keywords.K_USING) HashSet(java.util.HashSet) MergeMatchedDeleteStep(org.jooq.MergeMatchedDeleteStep) DSL.insertInto(org.jooq.impl.DSL.insertInto) TableLike(org.jooq.TableLike) K_WHEN(org.jooq.impl.Keywords.K_WHEN) FALSE(java.lang.Boolean.FALSE) MERGE_VALUES(org.jooq.Clause.MERGE_VALUES) MERGE_USING(org.jooq.Clause.MERGE_USING) Tools.collect(org.jooq.impl.Tools.collect) K_WITH_PRIMARY_KEY(org.jooq.impl.Keywords.K_WITH_PRIMARY_KEY) Configuration(org.jooq.Configuration) H2(org.jooq.SQLDialect.H2) K_MERGE_INTO(org.jooq.impl.Keywords.K_MERGE_INTO) K_THEN(org.jooq.impl.Keywords.K_THEN) Condition(org.jooq.Condition) DSL.trueCondition(org.jooq.impl.DSL.trueCondition) DSL.noCondition(org.jooq.impl.DSL.noCondition) Field(org.jooq.Field)

Example 4 with Clause

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

the class SelectQueryImpl method toSQLReference0.

/**
 * This method renders the main part of a query without the LIMIT clause.
 * This part is common to any type of limited query
 */
@SuppressWarnings("unchecked")
private final void toSQLReference0(Context<?> context, List<Field<?>> originalFields, List<Field<?>> alternativeFields) {
    SQLDialect family = context.family();
    boolean qualify = context.qualify();
    int unionOpSize = unionOp.size();
    boolean unionParensRequired = false;
    boolean unionOpNesting = false;
    // The SQL standard specifies:
    // 
    // <query expression> ::=
    // [ <with clause> ] <query expression body>
    // [ <order by clause> ] [ <result offset clause> ] [ <fetch first clause> ]
    // 
    // Depending on the dialect and on various syntax elements, parts of the above must be wrapped in
    // synthetic parentheses
    boolean wrapQueryExpressionInDerivedTable;
    boolean wrapQueryExpressionBodyInDerivedTable;
    boolean applySeekOnDerivedTable = applySeekOnDerivedTable();
    wrapQueryExpressionInDerivedTable = false;
    if (wrapQueryExpressionInDerivedTable)
        context.visit(K_SELECT).sql(" *").formatSeparator().visit(K_FROM).sql(" (").formatIndentStart().formatNewLine();
    wrapQueryExpressionBodyInDerivedTable = false || // predicate must be applied on a derived table, not on the individual subqueries
    applySeekOnDerivedTable;
    if (wrapQueryExpressionBodyInDerivedTable) {
        context.visit(K_SELECT).sql(' ');
        context.formatIndentStart().formatNewLine().sql("t.*");
        if (alternativeFields != null && originalFields.size() < alternativeFields.size())
            context.sql(", ").formatSeparator().declareFields(true, c -> c.visit(alternativeFields.get(alternativeFields.size() - 1)));
        context.formatIndentEnd().formatSeparator().visit(K_FROM).sql(" (").formatIndentStart().formatNewLine();
    }
    // all databases, we need to wrap relevant subqueries in parentheses.
    if (unionOpSize > 0) {
        if (!TRUE.equals(context.data(DATA_NESTED_SET_OPERATIONS)))
            context.data(DATA_NESTED_SET_OPERATIONS, unionOpNesting = unionOpNesting());
        for (int i = unionOpSize - 1; i >= 0; i--) {
            switch(unionOp.get(i)) {
                case EXCEPT:
                    context.start(SELECT_EXCEPT);
                    break;
                case EXCEPT_ALL:
                    context.start(SELECT_EXCEPT_ALL);
                    break;
                case INTERSECT:
                    context.start(SELECT_INTERSECT);
                    break;
                case INTERSECT_ALL:
                    context.start(SELECT_INTERSECT_ALL);
                    break;
                case UNION:
                    context.start(SELECT_UNION);
                    break;
                case UNION_ALL:
                    context.start(SELECT_UNION_ALL);
                    break;
            }
            // [#3676] There might be cases where nested set operations do not
            // imply required parentheses in some dialects, but better
            // play safe than sorry
            unionParenthesis(context, '(', alternativeFields != null ? alternativeFields : getSelect(), derivedTableRequired(context, this), unionParensRequired = unionOpNesting || unionParensRequired(context));
        }
    }
    traverseJoins(getFrom(), t -> {
        if (t instanceof TableImpl)
            context.scopeRegister(t, true);
    });
    for (Entry<QueryPart, QueryPart> entry : localQueryPartMapping.entrySet()) context.scopeRegister(entry.getKey(), true, entry.getValue());
    // SELECT clause
    // -------------
    context.start(SELECT_SELECT).visit(K_SELECT).separatorRequired(true);
    // [#1493] Oracle hints come directly after the SELECT keyword
    if (!StringUtils.isBlank(hint))
        context.sql(' ').sql(hint).separatorRequired(true);
    if (Tools.isNotEmpty(distinctOn))
        context.visit(K_DISTINCT_ON).sql(" (").visit(distinctOn).sql(')').separatorRequired(true);
    else if (distinct)
        context.visit(K_DISTINCT).separatorRequired(true);
    if (TRUE.equals(context.data(BooleanDataKey.DATA_RENDERING_DATA_CHANGE_DELTA_TABLE)))
        context.qualify(false);
    context.declareFields(true);
    // non-ambiguous column names as ambiguous column names are not allowed in subqueries
    if (alternativeFields != null)
        if (wrapQueryExpressionBodyInDerivedTable && originalFields.size() < alternativeFields.size())
            context.visit(new SelectFieldList<>(alternativeFields.subList(0, originalFields.size())));
        else
            context.visit(new SelectFieldList<>(alternativeFields));
    else
        // The default behaviour
        context.visit(getSelectResolveUnsupportedAsterisks(context.configuration()));
    if (TRUE.equals(context.data(BooleanDataKey.DATA_RENDERING_DATA_CHANGE_DELTA_TABLE)))
        context.qualify(qualify);
    context.declareFields(false).end(SELECT_SELECT);
    // only in top level SELECTs
    if (!context.subquery()) {
        context.start(SELECT_INTO);
        QueryPart actualIntoTable = (QueryPart) context.data(DATA_SELECT_INTO_TABLE);
        if (actualIntoTable == null)
            actualIntoTable = intoTable;
        if (actualIntoTable != null && !TRUE.equals(context.data(DATA_OMIT_INTO_CLAUSE)) && (SUPPORT_SELECT_INTO_TABLE.contains(context.dialect()) || !(actualIntoTable instanceof Table))) {
            context.formatSeparator().visit(K_INTO).sql(' ').visit(actualIntoTable);
        }
        context.end(SELECT_INTO);
    }
    // FROM and JOIN clauses
    // ---------------------
    context.start(SELECT_FROM).declareTables(true);
    // [#....] Some SQL dialects do not require a FROM clause. Others do and
    // jOOQ generates a "DUAL" table or something equivalent.
    // See also org.jooq.impl.Dual for details.
    boolean hasFrom = !getFrom().isEmpty() || !OPTIONAL_FROM_CLAUSE.contains(context.dialect());
    List<Condition> semiAntiJoinPredicates = null;
    ConditionProviderImpl where = getWhere(context);
    if (hasFrom) {
        Object previousCollect = context.data(DATA_COLLECT_SEMI_ANTI_JOIN, true);
        Object previousCollected = context.data(DATA_COLLECTED_SEMI_ANTI_JOIN, null);
        TableList tablelist = getFrom();
        tablelist = transformInlineDerivedTables(tablelist, where);
        context.formatSeparator().visit(K_FROM).separatorRequired(true).visit(tablelist);
        semiAntiJoinPredicates = (List<Condition>) context.data(DATA_COLLECTED_SEMI_ANTI_JOIN, previousCollected);
        context.data(DATA_COLLECT_SEMI_ANTI_JOIN, previousCollect);
    }
    context.declareTables(false).end(SELECT_FROM);
    // WHERE clause
    // ------------
    context.start(SELECT_WHERE);
    if (TRUE.equals(context.data().get(BooleanDataKey.DATA_SELECT_NO_DATA)))
        context.formatSeparator().visit(K_WHERE).sql(' ').visit(falseCondition());
    else if (!where.hasWhere() && semiAntiJoinPredicates == null)
        ;
    else {
        ConditionProviderImpl actual = new ConditionProviderImpl();
        if (semiAntiJoinPredicates != null)
            actual.addConditions(semiAntiJoinPredicates);
        if (where.hasWhere())
            actual.addConditions(where.getWhere());
        context.formatSeparator().visit(K_WHERE).sql(' ').visit(actual);
    }
    context.end(SELECT_WHERE);
    // GROUP BY and HAVING clause
    // --------------------------
    context.start(SELECT_GROUP_BY);
    if (!getGroupBy().isEmpty()) {
        context.formatSeparator().visit(K_GROUP_BY);
        if (groupByDistinct)
            context.sql(' ').visit(K_DISTINCT);
        context.separatorRequired(true);
        context.visit(groupBy);
    }
    context.end(SELECT_GROUP_BY);
    // HAVING clause
    // -------------
    context.start(SELECT_HAVING);
    if (getHaving().hasWhere())
        context.formatSeparator().visit(K_HAVING).sql(' ').visit(getHaving());
    context.end(SELECT_HAVING);
    // WINDOW clause
    // -------------
    context.start(SELECT_WINDOW);
    if (Tools.isNotEmpty(window) && !NO_SUPPORT_WINDOW_CLAUSE.contains(context.dialect()))
        context.formatSeparator().visit(K_WINDOW).separatorRequired(true).declareWindows(true, c -> c.visit(window));
    context.end(SELECT_WINDOW);
    if (getQualify().hasWhere())
        context.formatSeparator().visit(K_QUALIFY).sql(' ').visit(getQualify());
    // ORDER BY clause for local subselect
    // -----------------------------------
    toSQLOrderBy(context, originalFields, alternativeFields, false, wrapQueryExpressionBodyInDerivedTable, orderBy, limit);
    // --------------------------------------------
    if (unionOpSize > 0) {
        unionParenthesis(context, ')', null, derivedTableRequired(context, this), unionParensRequired);
        for (int i = 0; i < unionOpSize; i++) {
            CombineOperator op = unionOp.get(i);
            for (Select<?> other : union.get(i)) {
                boolean derivedTableRequired = derivedTableRequired(context, other);
                context.formatSeparator().visit(op.toKeyword(family));
                if (unionParensRequired)
                    context.sql(' ');
                else
                    context.formatSeparator();
                unionParenthesis(context, '(', other.getSelect(), derivedTableRequired, unionParensRequired);
                context.visit(other);
                unionParenthesis(context, ')', null, derivedTableRequired, unionParensRequired);
            }
            // [#1658] Close parentheses opened previously
            if (i < unionOpSize - 1)
                unionParenthesis(context, ')', null, derivedTableRequired(context, this), unionParensRequired);
            switch(unionOp.get(i)) {
                case EXCEPT:
                    context.end(SELECT_EXCEPT);
                    break;
                case EXCEPT_ALL:
                    context.end(SELECT_EXCEPT_ALL);
                    break;
                case INTERSECT:
                    context.end(SELECT_INTERSECT);
                    break;
                case INTERSECT_ALL:
                    context.end(SELECT_INTERSECT_ALL);
                    break;
                case UNION:
                    context.end(SELECT_UNION);
                    break;
                case UNION_ALL:
                    context.end(SELECT_UNION_ALL);
                    break;
            }
        }
        if (unionOpNesting)
            context.data().remove(DATA_NESTED_SET_OPERATIONS);
    }
    if (wrapQueryExpressionBodyInDerivedTable) {
        context.formatIndentEnd().formatNewLine().sql(") t");
        if (applySeekOnDerivedTable) {
            context.formatSeparator().visit(K_WHERE).sql(' ').qualify(false, c -> c.visit(getSeekCondition()));
        }
    }
    // ORDER BY clause for UNION
    // -------------------------
    context.qualify(false, c -> toSQLOrderBy(context, originalFields, alternativeFields, wrapQueryExpressionInDerivedTable, wrapQueryExpressionBodyInDerivedTable, unionOrderBy, unionLimit));
}
Also used : Internal.isub(org.jooq.impl.Internal.isub) Tools.aliased(org.jooq.impl.Tools.aliased) UnmodifiableList(org.jooq.impl.QOM.UnmodifiableList) DSL.emptyGroupingSet(org.jooq.impl.DSL.emptyGroupingSet) K_BY(org.jooq.impl.Keywords.K_BY) Arrays.asList(java.util.Arrays.asList) DSL.createTable(org.jooq.impl.DSL.createTable) Map(java.util.Map) QualifiedAsterisk(org.jooq.QualifiedAsterisk) SQLDialect(org.jooq.SQLDialect) Scope(org.jooq.Scope) Select(org.jooq.Select) SELECT_START_WITH(org.jooq.Clause.SELECT_START_WITH) DSL.partitionBy(org.jooq.impl.DSL.partitionBy) QueryPartCollectionView.wrap(org.jooq.impl.QueryPartCollectionView.wrap) Tools.isWindow(org.jooq.impl.Tools.isWindow) DataExtendedKey(org.jooq.impl.Tools.DataExtendedKey) DATA_TRANSFORM_ROWNUM_TO_LIMIT(org.jooq.impl.Tools.DataExtendedKey.DATA_TRANSFORM_ROWNUM_TO_LIMIT) TableField(org.jooq.TableField) SUPPORT_NATIVE_EXCEPT(org.jooq.impl.AsteriskImpl.SUPPORT_NATIVE_EXCEPT) DSL.noCondition(org.jooq.impl.DSL.noCondition) K_START_WITH(org.jooq.impl.Keywords.K_START_WITH) DATA_INSERT_SELECT(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT) TRUE(java.lang.Boolean.TRUE) DERBY(org.jooq.SQLDialect.DERBY) EXCEPT_ALL(org.jooq.impl.CombineOperator.EXCEPT_ALL) DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE(org.jooq.impl.Tools.BooleanDataKey.DATA_RENDER_TRAILING_LIMIT_IF_APPLICABLE) DSL.jsonArrayAgg(org.jooq.impl.DSL.jsonArrayAgg) K_WITH_READ_ONLY(org.jooq.impl.Keywords.K_WITH_READ_ONLY) LinkedHashMap(java.util.LinkedHashMap) K_ORDER_BY(org.jooq.impl.Keywords.K_ORDER_BY) Tools.autoAlias(org.jooq.impl.Tools.autoAlias) INTERSECT(org.jooq.impl.CombineOperator.INTERSECT) VARCHAR(org.jooq.impl.SQLDataType.VARCHAR) XML(org.jooq.impl.SQLDataType.XML) DATA_OMIT_INTO_CLAUSE(org.jooq.impl.Tools.BooleanDataKey.DATA_OMIT_INTO_CLAUSE) DATA_DML_TARGET_TABLE(org.jooq.impl.Tools.DataKey.DATA_DML_TARGET_TABLE) MYSQL(org.jooq.SQLDialect.MYSQL) DATA_COLLECTED_SEMI_ANTI_JOIN(org.jooq.impl.Tools.DataKey.DATA_COLLECTED_SEMI_ANTI_JOIN) K_WITH_CHECK_OPTION(org.jooq.impl.Keywords.K_WITH_CHECK_OPTION) K_FROM(org.jooq.impl.Keywords.K_FROM) Comparator(org.jooq.Comparator) SelectFieldOrAsterisk(org.jooq.SelectFieldOrAsterisk) DSL.jsonbArrayAgg(org.jooq.impl.DSL.jsonbArrayAgg) DATA_COLLECT_SEMI_ANTI_JOIN(org.jooq.impl.Tools.BooleanDataKey.DATA_COLLECT_SEMI_ANTI_JOIN) FIREBIRD(org.jooq.SQLDialect.FIREBIRD) K_WHERE(org.jooq.impl.Keywords.K_WHERE) SELECT(org.jooq.Clause.SELECT) DSL.xmlattributes(org.jooq.impl.DSL.xmlattributes) JoinType(org.jooq.JoinType) IGNITE(org.jooq.SQLDialect.IGNITE) MARIADB(org.jooq.SQLDialect.MARIADB) NO_SUPPORT_ABSENT_ON_NULL(org.jooq.impl.JSONNull.NO_SUPPORT_ABSENT_ON_NULL) K_DISTINCT_ON(org.jooq.impl.Keywords.K_DISTINCT_ON) SelectQuery(org.jooq.SelectQuery) DSL.table(org.jooq.impl.DSL.table) INTERSECT_ALL(org.jooq.impl.CombineOperator.INTERSECT_ALL) Row(org.jooq.Row) IntStream.range(java.util.stream.IntStream.range) SELECT_WINDOW(org.jooq.Clause.SELECT_WINDOW) BiFunction(java.util.function.BiFunction) Table(org.jooq.Table) DSL.rowNumber(org.jooq.impl.DSL.rowNumber) Operator(org.jooq.Operator) ForLockWaitMode(org.jooq.impl.ForLock.ForLockWaitMode) SelectLimitPercentStep(org.jooq.SelectLimitPercentStep) Clause(org.jooq.Clause) SELECT_SELECT(org.jooq.Clause.SELECT_SELECT) NO_SUPPORT_UNQUALIFIED_COMBINED(org.jooq.impl.AsteriskImpl.NO_SUPPORT_UNQUALIFIED_COMBINED) JSONB(org.jooq.impl.SQLDataType.JSONB) DataKey(org.jooq.impl.Tools.DataKey) Tools.aliasedFields(org.jooq.impl.Tools.aliasedFields) SELECT_FROM(org.jooq.Clause.SELECT_FROM) K_TOP(org.jooq.impl.Keywords.K_TOP) GroupField(org.jooq.GroupField) OR(org.jooq.Operator.OR) DataType(org.jooq.DataType) DSL.name(org.jooq.impl.DSL.name) K_HAVING(org.jooq.impl.Keywords.K_HAVING) SELECT_CONNECT_BY(org.jooq.Clause.SELECT_CONNECT_BY) Name(org.jooq.Name) Collection(java.util.Collection) SelectLimitStep(org.jooq.SelectLimitStep) Field(org.jooq.Field) DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST(org.jooq.impl.Tools.BooleanDataKey.DATA_INSERT_SELECT_WITHOUT_INSERT_COLUMN_LIST) CUBRID(org.jooq.SQLDialect.CUBRID) SELECT_UNION(org.jooq.Clause.SELECT_UNION) K_QUALIFY(org.jooq.impl.Keywords.K_QUALIFY) EXCEPT(org.jooq.impl.CombineOperator.EXCEPT) K_INTO(org.jooq.impl.Keywords.K_INTO) Tools.containsUnaliasedTable(org.jooq.impl.Tools.containsUnaliasedTable) SelectWithTiesStep(org.jooq.SelectWithTiesStep) JSON(org.jooq.impl.SQLDataType.JSON) Entry(java.util.Map.Entry) K_DISTINCT(org.jooq.impl.Keywords.K_DISTINCT) Tools.anyMatch(org.jooq.impl.Tools.anyMatch) ResultSetMetaData(java.sql.ResultSetMetaData) K_SELECT(org.jooq.impl.Keywords.K_SELECT) K_SIBLINGS(org.jooq.impl.Keywords.K_SIBLINGS) SELECT_HAVING(org.jooq.Clause.SELECT_HAVING) INLINED(org.jooq.conf.ParamType.INLINED) Function(java.util.function.Function) K_CONNECT_BY(org.jooq.impl.Keywords.K_CONNECT_BY) TableLike(org.jooq.TableLike) Tools.fieldArray(org.jooq.impl.Tools.fieldArray) DSL.inline(org.jooq.impl.DSL.inline) K_PERCENT(org.jooq.impl.Keywords.K_PERCENT) SelectHavingStep(org.jooq.SelectHavingStep) DataAccessException(org.jooq.exception.DataAccessException) DATA_NESTED_SET_OPERATIONS(org.jooq.impl.Tools.BooleanDataKey.DATA_NESTED_SET_OPERATIONS) SELECT_INTERSECT(org.jooq.Clause.SELECT_INTERSECT) Consumer(java.util.function.Consumer) SortField(org.jooq.SortField) Multiset.returningClob(org.jooq.impl.Multiset.returningClob) H2(org.jooq.SQLDialect.H2) Tools.unalias(org.jooq.impl.Tools.unalias) K_WINDOW(org.jooq.impl.Keywords.K_WINDOW) Arrays(java.util.Arrays) DSL.orderBy(org.jooq.impl.DSL.orderBy) POSTGRES(org.jooq.SQLDialect.POSTGRES) DATA_UNALIAS_ALIASED_EXPRESSIONS(org.jooq.impl.Tools.BooleanDataKey.DATA_UNALIAS_ALIASED_EXPRESSIONS) JOIN(org.jooq.JoinType.JOIN) Condition(org.jooq.Condition) DSL.trueCondition(org.jooq.impl.DSL.trueCondition) EMULATE_WITH_GROUP_CONCAT(org.jooq.impl.JSONArrayAgg.EMULATE_WITH_GROUP_CONCAT) SelectField(org.jooq.SelectField) Tools.unqualified(org.jooq.impl.Tools.unqualified) CommonTableExpressionList.markTopLevelCteAndAccept(org.jooq.impl.CommonTableExpressionList.markTopLevelCteAndAccept) JSONObjectNullStep(org.jooq.JSONObjectNullStep) K_NOCYCLE(org.jooq.impl.Keywords.K_NOCYCLE) Set(java.util.Set) Tools.camelCase(org.jooq.impl.Tools.camelCase) QueryPart(org.jooq.QueryPart) Tools.traverseJoins(org.jooq.impl.Tools.traverseJoins) SELECT_UNION_ALL(org.jooq.Clause.SELECT_UNION_ALL) Tools.qualify(org.jooq.impl.Tools.qualify) N_LEVEL(org.jooq.impl.Names.N_LEVEL) Materialized(org.jooq.impl.QOM.Materialized) DSL.jsonObject(org.jooq.impl.DSL.jsonObject) K_AND(org.jooq.impl.Keywords.K_AND) DSL.xmlagg(org.jooq.impl.DSL.xmlagg) DATA_SELECT_INTO_TABLE(org.jooq.impl.Tools.DataKey.DATA_SELECT_INTO_TABLE) XML(org.jooq.XML) K_GROUP_BY(org.jooq.impl.Keywords.K_GROUP_BY) CompareCondition(org.jooq.impl.QOM.CompareCondition) DSL.row(org.jooq.impl.DSL.row) DSL.xmlelement(org.jooq.impl.DSL.xmlelement) ArrayList(java.util.ArrayList) Tools.isNotEmpty(org.jooq.impl.Tools.isNotEmpty) SELECT_INTO(org.jooq.Clause.SELECT_INTO) Transformations.transformRownum(org.jooq.impl.Transformations.transformRownum) SQLITE(org.jooq.SQLDialect.SQLITE) SELECT_WHERE(org.jooq.Clause.SELECT_WHERE) Record(org.jooq.Record) RIGHT_OUTER_JOIN(org.jooq.JoinType.RIGHT_OUTER_JOIN) JSONObjectReturningStep(org.jooq.JSONObjectReturningStep) K_MATERIALIZE(org.jooq.impl.Keywords.K_MATERIALIZE) K_ORDER(org.jooq.impl.Keywords.K_ORDER) DATA_TOP_LEVEL_CTE(org.jooq.impl.Tools.DataKey.DATA_TOP_LEVEL_CTE) SELECT_INTERSECT_ALL(org.jooq.Clause.SELECT_INTERSECT_ALL) StringUtils(org.jooq.tools.StringUtils) YUGABYTEDB(org.jooq.SQLDialect.YUGABYTEDB) UNION_ALL(org.jooq.impl.CombineOperator.UNION_ALL) ArrayDeque(java.util.ArrayDeque) ForLockMode(org.jooq.impl.ForLock.ForLockMode) TableOnStep(org.jooq.TableOnStep) Tools.map(org.jooq.impl.Tools.map) WindowDefinition(org.jooq.WindowDefinition) DSL.jsonbObject(org.jooq.impl.DSL.jsonbObject) Transformations.transformQualify(org.jooq.impl.Transformations.transformQualify) SelectOffsetStep(org.jooq.SelectOffsetStep) DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES(org.jooq.impl.Tools.BooleanDataKey.DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES) K_INLINE(org.jooq.impl.Keywords.K_INLINE) DSL.regexpReplaceAll(org.jooq.impl.DSL.regexpReplaceAll) DATA_SELECT_ALIASES(org.jooq.impl.Tools.DataKey.DATA_SELECT_ALIASES) JSONArrayAgg.patchOracleArrayAggBug(org.jooq.impl.JSONArrayAgg.patchOracleArrayAggBug) SELECT_EXCEPT(org.jooq.Clause.SELECT_EXCEPT) DEFAULT(org.jooq.SQLDialect.DEFAULT) Tools.selectQueryImpl(org.jooq.impl.Tools.selectQueryImpl) SELECT_GROUP_BY(org.jooq.Clause.SELECT_GROUP_BY) JooqLogger(org.jooq.tools.JooqLogger) Collections.emptyList(java.util.Collections.emptyList) DSL.falseCondition(org.jooq.impl.DSL.falseCondition) JSONEntry(org.jooq.JSONEntry) DATA_WINDOW_DEFINITIONS(org.jooq.impl.Tools.DataKey.DATA_WINDOW_DEFINITIONS) HSQLDB(org.jooq.SQLDialect.HSQLDB) List(java.util.List) Context(org.jooq.Context) DATA_OVERRIDE_ALIASES_IN_ORDER_BY(org.jooq.impl.Tools.DataKey.DATA_OVERRIDE_ALIASES_IN_ORDER_BY) TablePartitionByStep(org.jooq.TablePartitionByStep) Tools.recordType(org.jooq.impl.Tools.recordType) DSL.key(org.jooq.impl.DSL.key) ForeignKey(org.jooq.ForeignKey) Deque(java.util.Deque) BooleanDataKey(org.jooq.impl.Tools.BooleanDataKey) UNION(org.jooq.impl.CombineOperator.UNION) DSL.asterisk(org.jooq.impl.DSL.asterisk) SELECT_EXCEPT_ALL(org.jooq.Clause.SELECT_EXCEPT_ALL) Tools.hasAmbiguousNames(org.jooq.impl.Tools.hasAmbiguousNames) DSL.unquotedName(org.jooq.impl.DSL.unquotedName) Tools.isEmpty(org.jooq.impl.Tools.isEmpty) DESC(org.jooq.SortOrder.DESC) N_ROWNUM(org.jooq.impl.Names.N_ROWNUM) DSL.one(org.jooq.impl.DSL.one) Configuration(org.jooq.Configuration) TableOptionalOnStep(org.jooq.TableOptionalOnStep) SELECT_ORDER_BY(org.jooq.Clause.SELECT_ORDER_BY) LEFT_OUTER_JOIN(org.jooq.JoinType.LEFT_OUTER_JOIN) DSL.generateSeries(org.jooq.impl.DSL.generateSeries) OrderField(org.jooq.OrderField) Collections(java.util.Collections) DSL.noCondition(org.jooq.impl.DSL.noCondition) Condition(org.jooq.Condition) DSL.trueCondition(org.jooq.impl.DSL.trueCondition) CompareCondition(org.jooq.impl.QOM.CompareCondition) DSL.falseCondition(org.jooq.impl.DSL.falseCondition) DSL.createTable(org.jooq.impl.DSL.createTable) Table(org.jooq.Table) Tools.containsUnaliasedTable(org.jooq.impl.Tools.containsUnaliasedTable) QueryPart(org.jooq.QueryPart) SQLDialect(org.jooq.SQLDialect) DSL.jsonObject(org.jooq.impl.DSL.jsonObject) DSL.jsonbObject(org.jooq.impl.DSL.jsonbObject)

Example 5 with Clause

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

the class FieldMapForUpdate method accept.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public final void accept(Context<?> ctx) {
    if (size() > 0) {
        String separator = "";
        // [#989] Some dialects do not support qualified column references
        // in the UPDATE statement's SET clause
        // [#2055] Other dialects require qualified column references to
        // disambiguated columns in queries like
        // UPDATE t1 JOIN t2 .. SET t1.val = ..., t2.val = ...
        boolean supportsQualify = !NO_SUPPORT_QUALIFY.contains(ctx.dialect()) && ctx.qualify();
        // [#2823] [#10034] Few dialects need bind value casts for UPDATE .. SET
        // Some regressions have been observed e.g. in PostgreSQL with JSON types, so let's be careful.
        CastMode previous = ctx.castMode();
        if (!CASTS_NEEDED.contains(ctx.dialect()))
            ctx.castMode(CastMode.NEVER);
        for (Entry<Field<?>, Field<?>> entry : removeReadonly(ctx, flattenEntrySet(entrySet(), true))) {
            if (!"".equals(separator))
                ctx.sql(separator).formatSeparator();
            ctx.start(assignmentClause).qualify(supportsQualify, c -> c.visit(entry.getKey())).sql(" = ");
            // [#8479] Emulate WHERE clause using CASE
            Condition condition = (Condition) ctx.data(DATA_ON_DUPLICATE_KEY_WHERE);
            if (condition != null)
                ctx.visit(when(condition, (Field) entry.getValue()).else_(entry.getKey()));
            else
                ctx.visit(entry.getValue());
            ctx.end(assignmentClause);
            separator = ",";
        }
        if (!CASTS_NEEDED.contains(ctx.dialect()))
            ctx.castMode(previous);
    } else
        ctx.sql("[ no fields are updated ]");
}
Also used : THROW(org.jooq.conf.WriteIfReadonly.THROW) Row(org.jooq.Row) UNotYetImplemented(org.jooq.impl.QOM.UNotYetImplemented) IGNORE(org.jooq.conf.WriteIfReadonly.IGNORE) Tools.collect(org.jooq.impl.Tools.collect) Set(java.util.Set) Table(org.jooq.Table) Tools.row0(org.jooq.impl.Tools.row0) Field(org.jooq.Field) POSTGRES(org.jooq.SQLDialect.POSTGRES) DSL.when(org.jooq.impl.DSL.when) Condition(org.jooq.Condition) Tools.filter(org.jooq.impl.Tools.filter) YUGABYTEDB(org.jooq.SQLDialect.YUGABYTEDB) DATA_ON_DUPLICATE_KEY_WHERE(org.jooq.impl.Tools.DataKey.DATA_ON_DUPLICATE_KEY_WHERE) Clause(org.jooq.Clause) Context(org.jooq.Context) CastMode(org.jooq.RenderContext.CastMode) SQLITE(org.jooq.SQLDialect.SQLITE) Map(java.util.Map) Tools.flattenEntrySet(org.jooq.impl.Tools.flattenEntrySet) DataTypeException(org.jooq.exception.DataTypeException) SQLDialect(org.jooq.SQLDialect) Tools.anyMatch(org.jooq.impl.Tools.anyMatch) Condition(org.jooq.Condition) Field(org.jooq.Field) CastMode(org.jooq.RenderContext.CastMode)

Aggregations

Clause (org.jooq.Clause)9 List (java.util.List)7 Set (java.util.Set)7 Condition (org.jooq.Condition)7 Context (org.jooq.Context)7 Field (org.jooq.Field)7 SQLDialect (org.jooq.SQLDialect)7 Table (org.jooq.Table)7 Arrays (java.util.Arrays)6 Collection (java.util.Collection)6 Map (java.util.Map)6 Configuration (org.jooq.Configuration)6 QueryPart (org.jooq.QueryPart)6 H2 (org.jooq.SQLDialect.H2)6 Select (org.jooq.Select)6 ArrayList (java.util.ArrayList)5 Operator (org.jooq.Operator)5 Record (org.jooq.Record)5 DERBY (org.jooq.SQLDialect.DERBY)5 DSL.name (org.jooq.impl.DSL.name)5