1/*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2000,2008 Oracle.  All rights reserved.
5 *
6 * $Id: TupleTupleMarshalledKeyCreator.java,v 12.7 2008/02/07 17:12:25 mark Exp $
7 */
8
9package com.sleepycat.bind.tuple;
10
11/**
12 * A concrete key creator that works in conjunction with a {@link
13 * TupleTupleMarshalledBinding}.  This key creator works by calling the
14 * methods of the {@link MarshalledTupleKeyEntity} interface to create and
15 * clear the index key.
16 *
17 * <p>Note that a marshalled tuple key creator is somewhat less efficient
18 * than a non-marshalled key tuple creator because more conversions are
19 * needed.  A marshalled key creator must convert the entry to an object in
20 * order to create the key, while an unmarshalled key creator does not.</p>
21 *
22 * @author Mark Hayes
23 */
24public class TupleTupleMarshalledKeyCreator extends TupleTupleKeyCreator {
25
26    private String keyName;
27    private TupleTupleMarshalledBinding binding;
28
29    /**
30     * Creates a tuple-tuple marshalled key creator.
31     *
32     * @param binding is the binding used for the tuple-tuple entity.
33     *
34     * @param keyName is the key name passed to the {@link
35     * MarshalledTupleKeyEntity#marshalSecondaryKey} method to identify the
36     * index key.
37     */
38    public TupleTupleMarshalledKeyCreator(TupleTupleMarshalledBinding binding,
39                                          String keyName) {
40
41        this.binding = binding;
42        this.keyName = keyName;
43    }
44
45    // javadoc is inherited
46    public boolean createSecondaryKey(TupleInput primaryKeyInput,
47                                      TupleInput dataInput,
48                                      TupleOutput indexKeyOutput) {
49
50        /* The primary key is unmarshalled before marshalling the index key, to
51         * account for cases where the index key includes fields taken from the
52         * primary key.
53         */
54        MarshalledTupleKeyEntity entity = (MarshalledTupleKeyEntity)
55            binding.entryToObject(primaryKeyInput, dataInput);
56
57        return entity.marshalSecondaryKey(keyName, indexKeyOutput);
58    }
59
60    // javadoc is inherited
61    public boolean nullifyForeignKey(TupleInput dataInput,
62                                     TupleOutput dataOutput) {
63
64        MarshalledTupleKeyEntity entity = (MarshalledTupleKeyEntity)
65            binding.entryToObject(null, dataInput);
66        if (entity.nullifyForeignKey(keyName)) {
67            binding.objectToData(entity, dataOutput);
68            return true;
69        } else {
70            return false;
71        }
72    }
73}
74