001/*
002 *  Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.mybatisflex.core.query;
017
018import com.mybatisflex.core.util.LambdaGetter;
019import com.mybatisflex.core.util.LambdaUtil;
020
021import java.util.ListIterator;
022import java.util.function.Consumer;
023
024/**
025 * @author michael yang (fuhai999@gmail.com)
026 * @Date: 2020/1/14
027 */
028public class Joiner<M extends QueryWrapper> {
029
030    private final M queryWrapper;
031    private final Join join;
032
033    public Joiner(M queryWrapper, Join join) {
034        this.queryWrapper = queryWrapper;
035        this.join = join;
036    }
037
038    /**
039     * <p>推荐写法:
040     * <pre>
041     * {@code leftJoin(ACCOUNT.as("a")).on(...);}
042     * </pre>
043     * <p>或者:
044     * <pre>{@code
045     * AccountTableDef a = ACCOUNT.as("a");
046     * leftJoin(a).on(...);
047     * }</pre>
048     */
049    public Joiner<M> as(String alias) {
050        join.queryTable = join.getQueryTable().as(alias);
051        ListIterator<QueryTable> itr = queryWrapper.joinTables.listIterator();
052        while (itr.hasNext()) {
053            if (itr.next().isSameTable(join.queryTable)) {
054                itr.set(join.queryTable);
055                break;
056            }
057        }
058        return this;
059    }
060
061    public M on(String on) {
062        join.on(new RawQueryCondition(on));
063        return queryWrapper;
064    }
065
066    public M on(QueryCondition on) {
067        join.on(on);
068        return queryWrapper;
069    }
070
071    public M on(Consumer<QueryWrapper> consumer) {
072        QueryWrapper newWrapper = new QueryWrapper();
073        consumer.accept(newWrapper);
074        join.on(newWrapper.whereQueryCondition);
075        return queryWrapper;
076    }
077
078    public <T, K> M on(LambdaGetter<T> column1, LambdaGetter<K> column2) {
079        QueryCondition queryCondition = LambdaUtil.getQueryColumn(column1).eq(LambdaUtil.getQueryColumn(column2));
080        join.on(queryCondition);
081        return queryWrapper;
082    }
083
084
085}
086