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 com.mybatisflex.core.dialect.IDialect;
019import com.mybatisflex.core.exception.FlexExceptions;
020import com.mybatisflex.core.util.CollectionUtil;
021import com.mybatisflex.core.util.StringUtil;
022
023import java.util.ArrayList;
024import java.util.List;
025
026public class WithValuesDetail implements WithDetail {
027
028    private List<Object> values;
029    private QueryWrapper queryWrapper;
030
031    public WithValuesDetail() {
032    }
033
034    public WithValuesDetail(List<Object> values, QueryWrapper queryWrapper) {
035        this.values = values;
036        this.queryWrapper = queryWrapper;
037    }
038
039    public QueryWrapper getQueryWrapper() {
040        return queryWrapper;
041    }
042
043    public void setQueryWrapper(QueryWrapper queryWrapper) {
044        this.queryWrapper = queryWrapper;
045    }
046
047    @Override
048    public String toSql(IDialect dialect) {
049        List<String> stringValues = new ArrayList<>(values.size());
050        for (Object value : values) {
051            stringValues.add(String.valueOf(value));
052        }
053        StringBuilder sql = new StringBuilder("VALUES (")
054            .append(StringUtil.join(", ", stringValues)).append(") ");
055        return sql.append(dialect.buildNoSelectSql(queryWrapper)).toString();
056    }
057
058    @Override
059    public Object[] getParamValues() {
060        return queryWrapper.getAllValueArray();
061    }
062
063    @Override
064    public WithValuesDetail clone() {
065        try {
066            WithValuesDetail clone = (WithValuesDetail) super.clone();
067            // deep clone ...
068            clone.values = CollectionUtil.newArrayList(this.values);
069            clone.queryWrapper = this.queryWrapper.clone();
070            return clone;
071        } catch (CloneNotSupportedException e) {
072            throw FlexExceptions.wrap(e);
073        }
074    }
075
076}