All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.magicall.sql.Insert Maven / Gradle / Ivy

There is a newer version: 2.13.0
Show newest version
/*
 * Copyright (c) 2024 Liang Wenjian
 * magicall is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package me.magicall.sql;

import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import me.magicall.dear_sun.exception.UnknownException;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Insert implements SqlPart {
	private final Multimap assignments;
	private final boolean ignore;

	private final Set tables;
	private final List> records;

	Insert(final Multimap assignments) {
		this(assignments, false);
	}

	Insert(final Multimap assignments, final boolean ignore) {
		this.assignments = assignments;
		this.ignore = ignore;
		tables = assignments.keySet().stream().map(Col::table).collect(Collectors.toCollection(Sets::newLinkedHashSet));
		if (tables.size() != 1) {//暂时只支持插入一个表。
			throw new UnknownException();
		}
		final var asMap = assignments.asMap();
		final var colCount = asMap.size();
		final var recordCount = asMap.values().stream().mapToInt(Collection::size).max().orElseThrow(UnknownException::new);
		records = IntStream.range(0, recordCount).mapToObj(i -> Arrays.asList(new Object[colCount]))
				.collect(Collectors.toList());
		int i = 0;
		for (final Entry> entry : asMap.entrySet()) {
			int j = 0;
			for (final Object v : entry.getValue()) {
				records.get(j).set(i, v);
				j++;
			}
			i++;
		}
	}

	@Override
	public StringBuilder appendTo(final StringBuilder sb) {
		var s = sb;
		s.append("INSERT ");
		if (ignore) {
			s.append("IGNORE ");
		}
		s.append("INTO ");
		s = tables.iterator().next().appendTo(s);

		s.append('(');
		for (final Col col : assignments.keySet()) {
			s = col.appendTo(s).append(Sql.ITEMS_SEPARATOR);
		}
		SqlKit.removeLastComma(s).append(")VALUES");

		for (final List record : records) {
			s.append('(');
			for (final Object v : record) {
				s = SqlKit.appendVal(s, v).append(Sql.ITEMS_SEPARATOR);
			}
			SqlKit.removeLastComma(s).append(')').append(Sql.ITEMS_SEPARATOR);
		}
		return SqlKit.removeLastComma(s);
	}
}