1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml">
4  <head>
5    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6    <title>Chapter��5.��Secondary Databases</title>
7    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
8    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
9    <link rel="start" href="index.html" title="Getting Started with Berkeley DB" />
10    <link rel="up" href="index.html" title="Getting Started with Berkeley DB" />
11    <link rel="prev" href="CoreCursorUsage.html" title="Cursor Example" />
12    <link rel="next" href="keyCreator.html" title="Implementing Key Extractors" />
13  </head>
14  <body>
15    <div class="navheader">
16      <table width="100%" summary="Navigation header">
17        <tr>
18          <th colspan="3" align="center">Chapter��5.��Secondary Databases</th>
19        </tr>
20        <tr>
21          <td width="20%" align="left"><a accesskey="p" href="CoreCursorUsage.html">Prev</a>��</td>
22          <th width="60%" align="center">��</th>
23          <td width="20%" align="right">��<a accesskey="n" href="keyCreator.html">Next</a></td>
24        </tr>
25      </table>
26      <hr />
27    </div>
28    <div class="chapter" lang="en" xml:lang="en">
29      <div class="titlepage">
30        <div>
31          <div>
32            <h2 class="title"><a id="indexes"></a>Chapter��5.��Secondary Databases</h2>
33          </div>
34        </div>
35      </div>
36      <div class="toc">
37        <p>
38          <b>Table of Contents</b>
39        </p>
40        <dl>
41          <dt>
42            <span class="sect1">
43              <a href="indexes.html#CoreDbAssociate">Opening and Closing Secondary Databases</a>
44            </span>
45          </dt>
46          <dt>
47            <span class="sect1">
48              <a href="keyCreator.html">Implementing Key 
49        
50        <span>Extractors</span>
51        </a>
52            </span>
53          </dt>
54          <dd>
55            <dl>
56              <dt>
57                <span class="sect2">
58                  <a href="keyCreator.html#multikeys">Working with Multiple Keys</a>
59                </span>
60              </dt>
61            </dl>
62          </dd>
63          <dt>
64            <span class="sect1">
65              <a href="readSecondary.html">Reading Secondary Databases</a>
66            </span>
67          </dt>
68          <dt>
69            <span class="sect1">
70              <a href="secondaryDelete.html">Deleting Secondary Database Records</a>
71            </span>
72          </dt>
73          <dt>
74            <span class="sect1">
75              <a href="secondaryCursor.html">
76        
77        <span>Using Cursors with Secondary Databases</span>
78    </a>
79            </span>
80          </dt>
81          <dt>
82            <span class="sect1">
83              <a href="joins.html">Database Joins</a>
84            </span>
85          </dt>
86          <dd>
87            <dl>
88              <dt>
89                <span class="sect2">
90                  <a href="joins.html#joinUsage">Using Join Cursors</a>
91                </span>
92              </dt>
93            </dl>
94          </dd>
95          <dt>
96            <span class="sect1">
97              <a href="coreindexusage.html">Secondary Database Example</a>
98            </span>
99          </dt>
100          <dd>
101            <dl>
102              <dt>
103                <span class="sect2">
104                  <a href="coreindexusage.html#edlWIndexes">Secondary Databases with example_database_load</a>
105                </span>
106              </dt>
107              <dt>
108                <span class="sect2">
109                  <a href="coreindexusage.html#edrWIndexes">Secondary Databases with example_database_read</a>
110                </span>
111              </dt>
112            </dl>
113          </dd>
114        </dl>
115      </div>
116      <p>
117    Usually you find database records by means of the record's key.  However,
118    the key that you use for your record will not always contain the
119    information required to provide you with rapid access to the data that you
120    want to retrieve. For example, suppose your 
121        
122        <span>database</span>
123    contains records related to users. The key might be a string that is some
124    unique identifier for the person, such as a user ID. Each record's data,
125    however, would likely contain a complex object containing details about
126    people such as names, addresses, phone numbers, and so forth.
127    While your application may frequently want to query a person by user
128    ID (that is, by the information stored in the key), it may also on occasion
129    want to locate people by, say, their name.
130  </p>
131      <p>
132    Rather than iterate through all of the records in your database, examining
133    each in turn for a given person's name, you create indexes based on names
134    and then just search that index for the name that you want.  You can do this
135    using secondary databases. In DB, the 
136        
137        <span>database</span> 
138    that contains your data is called a
139    <span class="emphasis"><em>primary database</em></span>. A database that provides an
140    alternative set of keys to access that data is called a <span class="emphasis"><em>secondary
141    database</em></span><span>.</span> In a secondary database, the keys are your alternative 
142    (or secondary) index, and the data corresponds to a primary record's key.
143  </p>
144      <p>
145    You create a secondary database by creating the database, opening it, and
146    then <span class="emphasis"><em>associating</em></span> the database with 
147    the <span class="emphasis"><em>primary</em></span> database (that is, the database for which
148    you are creating the index). As a part of associating
149    the secondary database to the primary, you must provide a callback that is
150    used to create the secondary database keys. Typically this callback creates
151    a key based on data found in the primary database record's key or data.
152  </p>
153      <p>
154  Once opened, DB manages secondary databases for you. Adding or deleting
155  records in your primary database causes DB to update the secondary as
156  necessary. Further, changing a record's data in the primary database may cause
157  DB to modify a record in the secondary, depending on whether the change
158  forces a modification of a key in the secondary database.
159  </p>
160      <p>
161    Note that you can not write directly to a secondary database. 
162
163    
164
165    <span>Any attempt to write to a secondary database
166    results in a non-zero status return.</span>
167    
168    To change the data referenced by a 
169        
170        <span>secondary</span>
171    record, modify the primary database instead. The exception to this rule is
172    that delete operations are allowed on the
173         
174        <span>secondary database.</span> 
175    
176    See <a class="xref" href="secondaryDelete.html" title="Deleting Secondary Database Records">Deleting Secondary Database Records</a> for more
177    information.
178  </p>
179      <div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
180        <h3 class="title">Note</h3>
181        <p>
182
183        Secondary database records are updated/created by DB 
184        only if the 
185            
186            <span>key creator callback function</span>
187        returns 
188             
189            <span><code class="literal">0</code>.</span> 
190        If 
191             
192            <span>a value other than <code class="literal">0</code></span>
193        is returned, then DB will not add the key to the secondary database, and 
194        in the event of a record update it will remove any existing key. 
195
196        <span>Note that the callback can use either
197        <code class="literal">DB_DONOTINDEX</code> or some error code outside of DB's
198        name space to indicate that the entry should not be indexed.</span>
199
200     </p>
201        <p>
202        See <a class="xref" href="keyCreator.html" title="Implementing Key Extractors">Implementing Key 
203        
204        <span>Extractors</span>
205        </a> for more
206            
207            <span>information.</span>
208    
209    </p>
210      </div>
211      <p>
212    When you read a record from a secondary database, DB automatically
213    returns 
214         
215        <span>the data and optionally the key</span> 
216    from the corresponding record in the primary database.
217    
218  </p>
219      <div class="sect1" lang="en" xml:lang="en">
220        <div class="titlepage">
221          <div>
222            <div>
223              <h2 class="title" style="clear: both"><a id="CoreDbAssociate"></a>Opening and Closing Secondary Databases</h2>
224            </div>
225          </div>
226        </div>
227        <p>
228        You manage secondary database opens and closes in the same way as you
229        would any normal database. The only difference is that:
230    </p>
231        <div class="itemizedlist">
232          <ul type="disc">
233            <li>
234              <p>
235                You must associate the secondary to a primary database using
236                    <span><code class="methodname">DB-&gt;associate()</code>.</span>
237                    
238            </p>
239            </li>
240            <li>
241              <p>
242                When closing your databases, it is a good idea to make sure you
243                close your secondaries before closing your primaries. This is
244                particularly true if your database closes are not single
245                threaded.
246            </p>
247            </li>
248          </ul>
249        </div>
250        <p>
251        When you associate a secondary to a primary database, you must provide a
252        callback that is used to generate the secondary's keys. These
253        callbacks are described in the next section.
254     </p>
255        <p>
256        For example, to open a secondary database and associate it to a primary
257        database:
258     </p>
259        <a id="c_index1"></a>
260        <pre class="programlisting">#include &lt;db.h&gt;
261
262...
263
264DB *dbp, *sdbp;    /* Primary and secondary DB handles */
265u_int32_t flags;   /* Primary database open flags */
266int ret;           /* Function return value */
267                                                                                                                                     
268/* Primary */
269ret = db_create(&amp;dbp, NULL, 0);
270if (ret != 0) {
271  /* Error handling goes here */
272}
273                                                                                                                                     
274/* Secondary */
275ret = db_create(&amp;sdbp, NULL, 0);
276if (ret != 0) {
277  /* Error handling goes here */
278}
279
280/* Usually we want to support duplicates for secondary databases */
281ret = sdbp-&gt;set_flags(sdbp, DB_DUPSORT);
282if (ret != 0) {
283  /* Error handling goes here */
284}
285
286
287/* Database open flags */
288flags = DB_CREATE;    /* If the database does not exist,
289                       * create it.*/
290
291/* open the primary database */
292ret = dbp-&gt;open(dbp,        /* DB structure pointer */
293                NULL,       /* Transaction pointer */
294                "my_db.db", /* On-disk file that holds the database. */
295                NULL,       /* Optional logical database name */
296                DB_BTREE,   /* Database access method */
297                flags,      /* Open flags */
298                0);         /* File mode (using defaults) */
299if (ret != 0) {
300  /* Error handling goes here */
301}
302
303/* open the secondary database */
304ret = sdbp-&gt;open(sdbp,          /* DB structure pointer */
305                 NULL,          /* Transaction pointer */
306                 "my_secdb.db", /* On-disk file that holds the database. */
307                 NULL,          /* Optional logical database name */
308                 DB_BTREE,      /* Database access method */
309                 flags,         /* Open flags */
310                 0);            /* File mode (using defaults) */
311if (ret != 0) {
312  /* Error handling goes here */
313}
314
315/* Now associate the secondary to the primary */
316dbp-&gt;associate(dbp,            /* Primary database */
317               NULL,           /* TXN id */
318               sdbp,           /* Secondary database */
319               get_sales_rep,  /* Callback used for key creation. Not 
320                                * defined in this example. See the next
321                                * section. */
322               0);              /* Flags */</pre>
323        <p>
324    Closing the primary and secondary databases is accomplished exactly as you
325    would for any database:
326  </p>
327        <a id="c_index2"></a>
328        <pre class="programlisting">/* Close the secondary before the primary */
329if (sdbp != NULL)
330    sdbp-&gt;close(sdbp, 0);
331if (dbp != NULL)
332    dbp-&gt;close(dbp, 0); </pre>
333      </div>
334    </div>
335    <div class="navfooter">
336      <hr />
337      <table width="100%" summary="Navigation footer">
338        <tr>
339          <td width="40%" align="left"><a accesskey="p" href="CoreCursorUsage.html">Prev</a>��</td>
340          <td width="20%" align="center">��</td>
341          <td width="40%" align="right">��<a accesskey="n" href="keyCreator.html">Next</a></td>
342        </tr>
343        <tr>
344          <td width="40%" align="left" valign="top">Cursor Example��</td>
345          <td width="20%" align="center">
346            <a accesskey="h" href="index.html">Home</a>
347          </td>
348          <td width="40%" align="right" valign="top">��Implementing Key 
349        
350        <span>Extractors</span>
351        </td>
352        </tr>
353      </table>
354    </div>
355  </body>
356</html>
357