001package gudusoft.gsqlparser.catalog.input.model;
002
003import java.util.ArrayList;
004import java.util.Collections;
005import java.util.List;
006import java.util.Objects;
007
008/**
009 * Index entry inside a {@link TableModel}. Plan ยง6.
010 */
011public final class IndexModel {
012
013    private final String name;
014    private final boolean unique;
015    private final List<String> columns;
016
017    private IndexModel(Builder b) {
018        if (b.name == null || b.name.isEmpty()) {
019            throw new IllegalArgumentException("IndexModel.name is required");
020        }
021        if (b.columns.isEmpty()) {
022            throw new IllegalArgumentException(
023                "IndexModel.columns must contain at least one column (index '" + b.name + "')");
024        }
025        this.name = b.name;
026        this.unique = b.unique;
027        this.columns = Collections.unmodifiableList(new ArrayList<String>(b.columns));
028    }
029
030    public static Builder builder() {
031        return new Builder();
032    }
033
034    public String name() {
035        return name;
036    }
037
038    public boolean unique() {
039        return unique;
040    }
041
042    public List<String> columns() {
043        return columns;
044    }
045
046    @Override
047    public boolean equals(Object o) {
048        if (this == o) return true;
049        if (!(o instanceof IndexModel)) return false;
050        IndexModel that = (IndexModel) o;
051        return unique == that.unique
052            && name.equals(that.name)
053            && columns.equals(that.columns);
054    }
055
056    @Override
057    public int hashCode() {
058        return Objects.hash(name, unique, columns);
059    }
060
061    @Override
062    public String toString() {
063        return "IndexModel{name=" + name + ", unique=" + unique + ", columns=" + columns + '}';
064    }
065
066    public static final class Builder {
067
068        private String name;
069        private boolean unique;
070        private final List<String> columns = new ArrayList<String>();
071
072        private Builder() {
073        }
074
075        public Builder name(String v) {
076            this.name = v;
077            return this;
078        }
079
080        public Builder unique(boolean v) {
081            this.unique = v;
082            return this;
083        }
084
085        public Builder addColumn(String v) {
086            if (v == null) {
087                throw new IllegalArgumentException("IndexModel column may not be null");
088            }
089            this.columns.add(v);
090            return this;
091        }
092
093        public IndexModel build() {
094            return new IndexModel(this);
095        }
096    }
097}