1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.core.model.constraint;
7   
8   import dev.metaschema.core.model.constraint.impl.DefaultIndexHasKeyConstraint;
9   import dev.metaschema.core.util.ObjectUtils;
10  import edu.umd.cs.findbugs.annotations.NonNull;
11  
12  /**
13   * Represents a rule that checks that a key generated for a Metaschema data
14   * object exists in a named index that was generated using an
15   * {@link IIndexConstraint}.
16   */
17  public interface IIndexHasKeyConstraint extends IKeyConstraint {
18    @Override
19    default Type getType() {
20      return Type.INDEX_HAS_KEY;
21    }
22  
23    /**
24     * The name of the index used to verify cross references.
25     *
26     * @return the name of the index this constraint uses for lookups
27     */
28    @NonNull
29    String getIndexName();
30  
31    @Override
32    default <T, R> R accept(IConstraintVisitor<T, R> visitor, T state) {
33      return visitor.visitIndexHasKeyConstraint(this, state);
34    }
35  
36    /**
37     * Create a new constraint builder.
38     *
39     * @param useIndex
40     *          the index name
41     * @return the builder
42     */
43    @NonNull
44    static Builder builder(@NonNull String useIndex) {
45      return new Builder(useIndex);
46    }
47  
48    /**
49     * Provides a builder pattern for constructing a new
50     * {@link IIndexHasKeyConstraint}.
51     */
52    final class Builder
53        extends AbstractKeyConstraintBuilder<Builder, IIndexHasKeyConstraint> {
54      @NonNull
55      private final String indexName;
56  
57      private Builder(@NonNull String useIndex) {
58        // disable construction
59        this.indexName = useIndex;
60      }
61  
62      @Override
63      protected Builder getThis() {
64        return this;
65      }
66  
67      @NonNull
68      private String getIndexName() {
69        return indexName;
70      }
71  
72      @Override
73      protected IIndexHasKeyConstraint newInstance() {
74        return new DefaultIndexHasKeyConstraint(
75            getId(),
76            getFormalName(),
77            getDescription(),
78            ObjectUtils.notNull(getSource()),
79            getLevel(),
80            getTarget(),
81            getProperties(),
82            getIndexName(),
83            getKeyFields(),
84            getMessage(),
85            getRemarks());
86      }
87    }
88  }