001/*
002 *  Copyright (c) 2022-2023, 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 java.util.ListIterator;
019import java.util.function.Consumer;
020
021/**
022 * @author michael yang (fuhai999@gmail.com)
023 * @Date: 2020/1/14
024 */
025public class Joiner<M extends QueryWrapper> {
026
027    private final M queryWrapper;
028    private final Join join;
029
030    public Joiner(M queryWrapper, Join join) {
031        this.queryWrapper = queryWrapper;
032        this.join = join;
033    }
034
035    /**
036     * <p>推荐写法:
037     * <pre>
038     * {@code leftJoin(ACCOUNT.as("a")).on(...);}
039     * </pre>
040     * <p>或者:
041     * <pre>{@code
042     * AccountTableDef a = ACCOUNT.as("a");
043     * leftJoin(a).on(...);
044     * }</pre>
045     */
046    @Deprecated
047    public Joiner<M> as(String alias) {
048        join.queryTable = join.getQueryTable().as(alias);
049        ListIterator<QueryTable> itr = queryWrapper.joinTables.listIterator();
050        while (itr.hasNext()) {
051            if (itr.next().isSameTable(join.queryTable)) {
052                itr.set(join.queryTable);
053                break;
054            }
055        }
056        return this;
057    }
058
059    public M on(String on) {
060        join.on(new RawQueryCondition(on));
061        return queryWrapper;
062    }
063
064    public M on(QueryCondition on) {
065        join.on(on);
066        return queryWrapper;
067    }
068
069    public M on(Consumer<QueryWrapper> consumer) {
070        QueryWrapper newWrapper = new QueryWrapper();
071        consumer.accept(newWrapper);
072        join.on(newWrapper.whereQueryCondition);
073        return queryWrapper;
074    }
075
076}
077