Imported Upstream version 5.3.21
[platform/upstream/libdb.git] / docs / gsg / C / DbUsage.html
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>Database Usage Example</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="DBEntry.html" title="Chapter 3. Database Records" />
11     <link rel="prev" href="cstructs.html" title="Using C Structures with DB" />
12     <link rel="next" href="Cursors.html" title="Chapter 4. Using Cursors" />
13   </head>
14   <body>
15     <div xmlns="" class="navheader">
16       <div class="libver">
17         <p>Library Version 11.2.5.3</p>
18       </div>
19       <table width="100%" summary="Navigation header">
20         <tr>
21           <th colspan="3" align="center">Database Usage Example</th>
22         </tr>
23         <tr>
24           <td width="20%" align="left"><a accesskey="p" href="cstructs.html">Prev</a> </td>
25           <th width="60%" align="center">Chapter 3. Database Records</th>
26           <td width="20%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
27         </tr>
28       </table>
29       <hr />
30     </div>
31     <div class="sect1" lang="en" xml:lang="en">
32       <div class="titlepage">
33         <div>
34           <div>
35             <h2 class="title" style="clear: both"><a id="DbUsage"></a>Database Usage Example</h2>
36           </div>
37         </div>
38       </div>
39       <p>
40         In <a class="xref" href="CoreDbUsage.html" title="Database Example">Database Example</a> we created several
41         functions that will open and close the databases that we will use for
42         our inventory application. We now make use of those functions to load inventory data into
43         the two databases that we use for this application.
44     </p>
45       <p>
46         Again, remember that you can find the complete implementation for these functions
47         in:
48     </p>
49       <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/getting_started</pre>
50       <p>
51         where <code class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></code> is the location where you
52         placed your DB distribution.
53     </p>
54       <div class="example">
55         <a id="VENDORStruct"></a>
56         <p class="title">
57           <b>Example 3.1 VENDOR Structure</b>
58         </p>
59         <div class="example-contents">
60           <p>
61             We want to store data related to an inventory system. There are two
62             types of information that we want to manage: inventory data and related
63             vendor contact information. To manage this information, we could
64             create a structure for each type of data, but to illustrate
65             storing mixed data without a structure we refrain from creating one
66             for the inventory data.
67         </p>
68           <p>
69             For the vendor data, we add the VENDOR structure to the same file as holds 
70             our STOCK_DBS structure. Note that the VENDOR structure uses
71             fixed-length fields. This is not necessary and in fact could
72             represent a waste of resources if the number of vendors stored in
73             our database scales to very large numbers. However, for simplicity we use
74             fixed-length fields anyway, especially 
75             given that our sample data contains so few vendor records.
76         </p>
77           <p>
78             Note that for the inventory data, we will store the data by
79             marshaling it into a buffer, described below.
80         </p>
81           <a id="c_dbt10"></a>
82           <pre class="programlisting">/* File: gettingstarted_common.h */
83 #include &lt;db.h&gt;
84
85 ...
86
87 <strong class="userinput"><code>typedef struct vendor {
88     char name[MAXFIELD];             /* Vendor name */
89     char street[MAXFIELD];           /* Street name and number */
90     char city[MAXFIELD];             /* City */
91     char state[3];                   /* Two-digit US state code */
92     char zipcode[6];                 /* US zipcode */
93     char phone_number[13];           /* Vendor phone number */
94     char sales_rep[MAXFIELD];        /* Name of sales representative */
95     char sales_rep_phone[MAXFIELD];  /* Sales rep's phone number */
96 } VENDOR;</code></strong> </pre>
97         </div>
98       </div>
99       <br class="example-break" />
100       <div class="example">
101         <a id="exampledbload"></a>
102         <p class="title">
103           <b>Example 3.2 example_database_load</b>
104         </p>
105         <div class="example-contents">
106           <p>
107             Our initial sample application will load database information from
108             several flat files. To save space, we won't show all the details of
109             this example program. However, as always you can find the complete
110             implementation for this program here:
111         </p>
112           <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_c/getting_started</pre>
113           <p>
114         where <code class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></code> is the location where you
115         placed your DB distribution.
116     </p>
117           <p>
118         We begin with the normal include directives and forward declarations:
119     </p>
120           <a id="c_dbt11"></a>
121           <pre class="programlisting">/* example_database_load.c */
122 #include "gettingstarted_common.h"
123
124 /* Forward declarations */
125 int load_vendors_database(STOCK_DBS, char *);
126 int pack_string(char *, char *, int);
127 int load_inventory_database(STOCK_DBS, char *); </pre>
128           <p>
129        Next we begin our <code class="function">main()</code> function with the variable
130        declarations and command line parsing that is normal for most command
131        line applications:  
132     </p>
133           <a id="c_dbt12"></a>
134           <pre class="programlisting">/*
135  * Loads the contents of vendors.txt and inventory.txt into
136  * Berkeley DB databases. 
137  */
138 int
139 main(int argc, char *argv[])
140 {
141     STOCK_DBS my_stock;
142     int ret, size;
143     char *basename, *inventory_file, *vendor_file;
144
145     /* Initialize the STOCK_DBS struct */
146     initialize_stockdbs(&amp;my_stock);
147
148    /* 
149     * Initialize the base path. This path is used to 
150     * identify the location of the flat-text data
151     * input files.
152     */
153     basename = "./";
154
155     /* 
156      * Parse the command line arguments here and determine 
157      * the location of the flat text files containing the 
158      * inventory data here. This step is omitted for clarity.
159      */
160
161     /* 
162      * Identify the files that will hold our databases 
163      * This function uses information obtained from the
164      * command line to identify the directory in which
165      * the database files reside.
166      */
167     set_db_filenames(&amp;my_stock);
168
169     /* Find our input files */
170     size = strlen(basename) + strlen(INVENTORY_FILE) + 1;
171     inventory_file = malloc(size);
172     snprintf(inventory_file, size, "%s%s", basename, INVENTORY_FILE);
173
174     size = strlen(basename) + strlen(VENDORS_FILE) + 1;
175     vendor_file = malloc(size);
176     snprintf(vendor_file, size, "%s%s", basename, VENDORS_FILE);
177
178     /* Open all databases */
179     ret = databases_setup(&amp;my_stock, "example_database_load", stderr);
180     if (ret != 0) {
181             fprintf(stderr, "Error opening databases\n");
182             databases_close(&amp;my_stock);
183             return (ret);
184     }
185
186     ret = load_vendors_database(my_stock, vendor_file);
187     if (!ret) {
188         fprintf(stderr, "Error loading vendors database.\n");
189         databases_close(&amp;my_stock);
190         return (ret);
191     }
192     ret = load_inventory_database(my_stock, inventory_file);
193     if (!ret) {
194         fprintf(stderr, "Error loading inventory database.\n");
195         databases_close(&amp;my_stock);
196         return (ret);
197     }
198
199     /* close our environment and databases */
200     databases_close(&amp;my_stock);
201
202     printf("Done loading databases.\n");
203     return (0);
204 }</pre>
205           <p>
206         Notice that there is not a lot to this function because we have pushed
207         off all the database activity to other places. In particular our
208         databases are all opened and configured in 
209         <code class="function">databases_setup()</code> which we implemented in 
210         <a class="xref" href="CoreDbUsage.html#databasesetup" title="Example 2.4 The databases_setup() Function">The databases_setup() Function</a>.
211     </p>
212           <p>
213         Next we show the implementation of
214         <code class="function">load_vendors_database()</code>. We load this data by
215         scanning (line by line) the contents of the
216         <code class="filename">vendors.txt</code> into a VENDOR structure. Once we have a
217         line scanned into the structure, we can store that structure into our
218         vendors database. 
219      </p>
220           <p>
221         Note that we use the vendor's name as the key here. In doing so, we
222         assume that the vendor's name is unique in our database. If it was not,
223         we would either have to select a different key, or architect our
224         application such that it could cope with multiple vendor records with
225         the same name.
226      </p>
227           <a id="c_dbt13"></a>
228           <pre class="programlisting">/*
229  * Loads the contents of the vendors.txt file into
230  * a database.
231  */
232 int
233 load_vendors_database(STOCK_DBS my_stock, char *vendor_file)
234 {
235     DBT key, data;
236     FILE *ifp;
237     VENDOR my_vendor;
238     char buf[MAXLINE];
239
240     /* Open the vendor file for read access */
241     ifp = fopen(vendor_file, "r");
242     if (ifp == NULL) {
243         fprintf(stderr, "Error opening file '%s'\n", vendor_file);
244         return(-1);
245     }
246
247     /* Iterate over the vendor file */
248     while(fgets(buf, MAXLINE, ifp) != NULL) {
249         /* zero out the structure */
250         memset(&amp;my_vendor, 0, sizeof(VENDOR));
251         /* Zero out the DBTs */
252         memset(&amp;key, 0, sizeof(DBT));
253         memset(&amp;data, 0, sizeof(DBT));
254
255         /*
256          * Scan the line into the structure.
257          * Convenient, but not particularly safe.
258          * In a real program, there would be a lot more
259          * defensive code here.
260          */
261         sscanf(buf,
262          "%20[^#]#%20[^#]#%20[^#]#%3[^#]#%6[^#]#%13[^#]#%20[^#]#%20[^\n]",
263          my_vendor.name, my_vendor.street,
264          my_vendor.city, my_vendor.state,
265          my_vendor.zipcode, my_vendor.phone_number,
266          my_vendor.sales_rep, my_vendor.sales_rep_phone);
267
268         /* 
269          * Now that we have our structure we can load it 
270          * into the database. 
271          */
272
273         /* Set up the database record's key */
274         key.data = my_vendor.name;
275         key.size = strlen(my_vendor.name) + 1;
276
277         /* Set up the database record's data */
278         data.data = &amp;my_vendor;
279         data.size = sizeof(my_vendor);
280
281         /*
282          * Note that given the way we built our struct, there are extra
283          * bytes in it. Essentially we're using fixed-width fields with
284          * the unused portion of some fields padded with zeros. This
285          * is the easiest thing to do, but it does result in a bloated
286          * database. Look at load_inventory_data() for an example of how
287          * to avoid this.
288          */
289
290         /* Put the data into the database.
291          * Omitting error handling for clarity.
292          */
293         my_stock.vendor_dbp-&gt;put(my_stock.vendor_dbp, 0, 
294                                    &amp;key, &amp;data, 0);
295     } /* end vendors database while loop */
296
297     /* Close the vendor.txt file */
298     fclose(ifp);
299     return(0);
300 } </pre>
301           <p>
302         Finally, we need to write the
303         <code class="function">load_inventory_database()</code> function. We made this function a
304         bit more complicated than is necessary by avoiding the use of a
305         structure to manage the data. Instead, we manually pack all our inventory
306         data into a single block of memory, and store that data in the
307         database.
308      </p>
309           <p>
310         While this complicates our code somewhat, this approach allows us to
311         use the smallest amount of space possible for the data that we want to
312         store. The result is that our cache can be smaller than it might
313         otherwise be and our database will take less space on disk than if we used
314         a structure with fixed-length fields.
315     </p>
316           <p>
317         For a trivial dataset such as what we use for these examples, these
318         resource savings are negligible. But if we were storing hundreds of
319         millions of records, then the cost savings may become significant.
320     </p>
321           <p>
322         Before we actually implement our inventory loading function, it is useful
323         to create a simple utility function that copies a character array into a
324         buffer at a designated offset:
325     </p>
326           <a id="c_dbt14"></a>
327           <pre class="programlisting">/*
328  * Simple little convenience function that takes a buffer, a string,
329  * and an offset and copies that string into the buffer at the
330  * appropriate location. Used to ensure that all our strings
331  * are contained in a single contiguous chunk of memory.
332  */
333 int
334 pack_string(char *buffer, char *string, int start_pos)
335 {
336     int string_size = strlen(string) + 1;
337
338     memcpy(buffer+start_pos, string, string_size);
339
340     return(start_pos + string_size);
341 } </pre>
342           <p>
343         That done, we can now load the inventory database:    
344     </p>
345           <a id="c_dbt15"></a>
346           <pre class="programlisting">/*
347  * Loads the contents of the inventory.txt file into
348  * a database.
349  */
350 int
351 load_inventory_database(STOCK_DBS my_stock, char *inventory_file)
352 {
353     DBT key, data;
354     char buf[MAXLINE];
355     void *databuf;
356     int bufLen, dataLen;
357     FILE *ifp;
358
359     /*
360      * Rather than lining everything up nicely in a struct, we're being
361      * deliberately a bit sloppy here. This function illustrates how to
362      * store mixed data that might be obtained from various locations
363      * in your application.
364      */
365     float price;
366     int quantity;
367     char category[MAXFIELD], name[MAXFIELD];
368     char vendor[MAXFIELD], sku[MAXFIELD];
369
370     /* Load the inventory database */
371     ifp = fopen(inventory_file, "r");
372     if (ifp == NULL) {
373         fprintf(stderr, "Error opening file '%s'\n", inventory_file);
374         return(-1);
375     }
376
377     /* Get our buffer. MAXDATABUF is some suitably large number */
378     databuf = malloc(MAXDATABUF);
379
380     /* 
381      * Read the inventory.txt file line by line, saving each line off to 
382      * the database as we go.
383      */
384     while(fgets(buf, MAXLINE, ifp) != NULL) {
385         /*
386          * Scan the line into the appropriate buffers and variables.
387          * Convenient, but not particularly safe. In a real
388          * program, there would be a lot more defensive code here.
389          */
390         sscanf(buf,
391           "%20[^#]#%20[^#]#%f#%i#%20[^#]#%20[^\n]",
392           name, sku, &amp;price, &amp;quantity, category, vendor);
393
394         /*
395          * Now pack it into a single contiguous memory location for
396          * storage.
397          */
398         memset(databuf, 0, MAXDATABUF);
399         bufLen = 0;
400         dataLen = 0;
401
402         /* 
403          * We first store the fixed-length elements. This makes our code
404          * to retrieve this data from the database a little bit easier.
405          */
406
407         /* First discover how long the data element is. */
408         dataLen = sizeof(float);
409         /* Then copy it to our buffer */
410         memcpy(databuf, &amp;price, dataLen);
411         /* 
412          * Then figure out how much data is actually in our buffer.
413          * We repeat this pattern for all the data we want to store.
414          */
415         bufLen += dataLen;
416
417         /* Rinse, lather, repeat. */
418         dataLen = sizeof(int);
419         memcpy(databuf + bufLen, &amp;quantity, dataLen);
420         bufLen += dataLen;
421
422         bufLen = pack_string(databuf, name, bufLen);
423         bufLen = pack_string(databuf, sku, bufLen);
424         bufLen = pack_string(databuf, category, bufLen);
425         bufLen = pack_string(databuf, vendor, bufLen);
426
427         /* 
428          * Now actually save the contents of the buffer off 
429          * to our database. 
430          */
431
432         /* Zero out the DBTs */
433         memset(&amp;key, 0, sizeof(DBT));
434         memset(&amp;data, 0, sizeof(DBT));
435
436         /* 
437          * The key is the item's SKU. This is a unique value, so we need 
438          * not support duplicates for this database. 
439          */
440         key.data = sku;
441         key.size = strlen(sku) + 1;
442
443         /* The data is the information that we packed into databuf. */
444         data.data = databuf;
445         data.size = bufLen;
446
447         /* Put the data into the database */
448         my_stock.vendor_dbp-&gt;put(my_stock.inventory_dbp, 0, 
449                                    &amp;key, &amp;data, 0);
450     } /* end vendors database while loop */
451
452     /* Cleanup */
453     fclose(ifp);
454     if (databuf != NULL)
455         free(databuf);
456
457     return(0);
458 } </pre>
459           <p>
460         In the next chapter we provide an example that shows how to read
461         the inventory and vendor databases.
462     </p>
463         </div>
464       </div>
465       <br class="example-break" />
466     </div>
467     <div class="navfooter">
468       <hr />
469       <table width="100%" summary="Navigation footer">
470         <tr>
471           <td width="40%" align="left"><a accesskey="p" href="cstructs.html">Prev</a> </td>
472           <td width="20%" align="center">
473             <a accesskey="u" href="DBEntry.html">Up</a>
474           </td>
475           <td width="40%" align="right"> <a accesskey="n" href="Cursors.html">Next</a></td>
476         </tr>
477         <tr>
478           <td width="40%" align="left" valign="top">Using C Structures with DB </td>
479           <td width="20%" align="center">
480             <a accesskey="h" href="index.html">Home</a>
481           </td>
482           <td width="40%" align="right" valign="top"> Chapter 4. Using Cursors</td>
483         </tr>
484       </table>
485     </div>
486   </body>
487 </html>