Debian Codegraph @

docs/programmer_reference/transapp_put.html

raw symbols SCIP
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>Recoverability and deadlock handling</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="Berkeley DB Programmer's Reference Guide" />
10 <link rel="up" href="transapp.html" title="Chapter 11.  Berkeley DB Transactional Data Store Applications" />
11 <link rel="prev" href="transapp_data_open.html" title="Opening the databases" />
12 <link rel="next" href="transapp_atomicity.html" title="Atomicity" />
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">Recoverability and deadlock handling</th>
22 </tr>
23 <tr>
24 <td width="20%" align="left"><a accesskey="p" href="transapp_data_open.html">Prev</a> </td>
25 <th width="60%" align="center">Chapter 11. 
26 Berkeley DB Transactional Data Store Applications
27 </th>
28 <td width="20%" align="right"> <a accesskey="n" href="transapp_atomicity.html">Next</a></td>
29 </tr>
30 </table>
31 <hr />
32 </div>
33 <div class="sect1" lang="en" xml:lang="en">
34 <div class="titlepage">
35 <div>
36 <div>
37 <h2 class="title" style="clear: both"><a id="transapp_put"></a>Recoverability and deadlock handling</h2>
38 </div>
39 </div>
40 </div>
41 <p>The first reason listed for using transactions was recoverability. Any
42 logical change to a database may require multiple changes to underlying
43 data structures. For example, modifying a record in a Btree may require
44 leaf and internal pages to split, so a single <a href="../api_reference/C/dbput.html" class="olink">DB-&gt;put()</a> method
45 call can potentially require that multiple physical database pages be
46 written. If only some of those pages are written and then the system
47 or application fails, the database is left inconsistent and cannot be
48 used until it has been recovered; that is, until the partially completed
49 changes have been undone.</p>
50 <p><span class="emphasis"><em>Write-ahead-logging</em></span> is the term that describes the underlying
51 implementation that Berkeley DB uses to ensure recoverability. What it means
52 is that before any change is made to a database, information about the
53 change is written to a database log. During recovery, the log is read,
54 and databases are checked to ensure that changes described in the log
55 for committed transactions appear in the database. Changes that appear
56 in the database but are related to aborted or unfinished transactions
57 in the log are undone from the database.</p>
58 <p>For recoverability after application or system failure, operations that
59 modify the database must be protected by transactions. More
60 specifically, operations are not recoverable unless a transaction is
61 begun and each operation is associated with the transaction via the
62 Berkeley DB interfaces, and then the transaction successfully committed. This
63 is true even if logging is turned on in the database environment.</p>
64 <p>Here is an example function that updates a record in a database in a
65 transactionally protected manner. The function takes a key and data
66 items as arguments and then attempts to store them into the database.</p>
67 <pre class="programlisting">int
68 main(int argc, char *argv)
69 {
70 extern int optind;
71 DB *db_cats, *db_color, *db_fruit;
72 DB_ENV *dbenv;
73 int ch;
74
75 while ((ch = getopt(argc, argv, "")) != EOF)
76 switch (ch) {
77 case '?':
78 default:
79 usage();
80 }
81 argc -= optind;
82 argv += optind;
83
84 env_dir_create();
85 env_open(&amp;dbenv);
86
87 /* Open database: Key is fruit class; Data is specific type. */
88 db_open(dbenv, &amp;db_fruit, "fruit", 0);
89
90 /* Open database: Key is a color; Data is an integer. */
91 db_open(dbenv, &amp;db_color, "color", 0);
92
93 /*
94 * Open database:
95 * Key is a name; Data is: company name, cat breeds.
96 */
97 db_open(dbenv, &amp;db_cats, "cats", 1);
98
99 <span class="bold"><strong> add_fruit(dbenv, db_fruit, "apple", "yellow delicious");</strong></span>
100
101 return (0);
102 }
103
104 <span class="bold"><strong>int
105 add_fruit(DB_ENV *dbenv, DB *db, char *fruit, char *name)
106 {
107 DBT key, data;
108 DB_TXN *tid;
109 int fail, ret, t_ret;
110
111 /* Initialization. */
112 memset(&amp;key, 0, sizeof(key));
113 memset(&amp;data, 0, sizeof(data));
114 key.data = fruit;
115 key.size = strlen(fruit);
116 data.data = name;
117 data.size = strlen(name);
118
119 for (fail = 0;;) {
120 /* Begin the transaction. */
121 if ((ret = dbenv-&gt;txn_begin(dbenv, NULL, &amp;tid, 0)) != 0) {
122 dbenv-&gt;err(dbenv, ret, "DB_ENV-&gt;txn_begin");
123 exit (1);
124 }
125
126 /* Store the value. */
127 switch (ret = db-&gt;put(db, tid, &amp;key, &amp;data, 0)) {
128 case 0:
129 /* Success: commit the change. */
130 if ((ret = tid-&gt;commit(tid, 0)) != 0) {
131 dbenv-&gt;err(dbenv, ret, "DB_TXN-&gt;commit");
132 exit (1);
133 }
134 return (0);
135 case DB_LOCK_DEADLOCK:
136 default:
137 /* Retry the operation. */
138 if ((t_ret = tid-&gt;abort(tid)) != 0) {
139 dbenv-&gt;err(dbenv, t_ret, "DB_TXN-&gt;abort");
140 exit (1);
141 }
142 if (fail++ == MAXIMUM_RETRY)
143 return (ret);
144 break;
145 }
146 }
147 }</strong></span></pre>
148 <p>Berkeley DB also uses transactions to recover from deadlock. Database
149 operations (that is, any call to a function underlying the handles
150 returned by <a href="../api_reference/C/dbopen.html" class="olink">DB-&gt;open()</a> and <a href="../api_reference/C/dbcursor.html" class="olink">DB-&gt;cursor()</a>) are usually
151 performed on behalf of a unique locker. Transactions can be used to
152 perform multiple calls on behalf of the same locker within a single
153 thread of control. For example, consider the case in which an
154 application uses a cursor scan to locate a record and then the
155 application accesses another other item in the database, based on the
156 key returned by the cursor, without first closing the cursor. If these
157 operations are done using default locker IDs, they may conflict. If the
158 locks are obtained on behalf of a transaction, using the transaction's
159 locker ID instead of the database handle's locker ID, the operations
160 will not conflict.</p>
161 <p>There is a new error return in this function that you may not have seen
162 before. In transactional (not Concurrent Data Store) applications
163 supporting both readers and writers, or just multiple writers, Berkeley DB
164 functions have an additional possible error return:
165 <a class="link" href="program_errorret.html#program_errorret.DB_LOCK_DEADLOCK">DB_LOCK_DEADLOCK</a>. This means two threads of control deadlocked,
166 and the thread receiving the <code class="literal">DB_LOCK_DEADLOCK</code> error return has
167 been selected to discard its locks in order to resolve the problem.
168 When an application receives a <code class="literal">DB_LOCK_DEADLOCK</code> return, the
169 correct action is to close any cursors involved in the operation and
170 abort any enclosing transaction. In the sample code, any time the
171 <a href="../api_reference/C/dbput.html" class="olink">DB-&gt;put()</a> method returns <code class="literal">DB_LOCK_DEADLOCK</code>, <a href="../api_reference/C/txnabort.html" class="olink">DB_TXN-&gt;abort()</a> is
172 called (which releases the transaction's Berkeley DB resources and undoes any
173 partial changes to the databases), and then the transaction is retried
174 from the beginning.</p>
175 <p>There is no requirement that the transaction be attempted again, but
176 that is a common course of action for applications. Applications may
177 want to set an upper bound on the number of times an operation will be
178 retried because some operations on some data sets may simply be unable
179 to succeed. For example, updating all of the pages on a large Web site
180 during prime business hours may simply be impossible because of the high
181 access rate to the database.</p>
182 <p>The <a href="../api_reference/C/txnabort.html" class="olink">DB_TXN-&gt;abort()</a> method is called in error cases other than deadlock.
183 Any time an error occurs, such that a transactionally protected set of
184 operations cannot complete successfully, the transaction must be
185 aborted. While deadlock is by far the most common of these errors,
186 there are other possibilities; for example, running out of disk space
187 for the filesystem. In Berkeley DB transactional applications, there are
188 three classes of error returns: "expected" errors, "unexpected but
189 recoverable" errors, and a single "unrecoverable" error. Expected
190 errors are errors like
191 <a class="link" href="program_errorret.html#program_errorret.DB_NOTFOUND">DB_NOTFOUND</a>,
192 which indicates that a
193 searched-for key item is not present in the database. Applications may
194 want to explicitly test for and handle this error, or, in the case where
195 the absence of a key implies the enclosing transaction should fail,
196 simply call <a href="../api_reference/C/txnabort.html" class="olink">DB_TXN-&gt;abort()</a>. Unexpected but recoverable errors are
197 errors like
198 <a class="link" href="program_errorret.html#program_errorret.DB_LOCK_DEADLOCK">DB_LOCK_DEADLOCK</a>,
199 which indicates that an operation
200 has been selected to resolve a deadlock, or a system error such as EIO,
201 which likely indicates that the filesystem has no available disk space.
202 Applications must immediately call <a href="../api_reference/C/txnabort.html" class="olink">DB_TXN-&gt;abort()</a> when these returns
203 occur, as it is not possible to proceed otherwise. The only
204 unrecoverable error is
205 <a class="link" href="program_errorret.html#program_errorret.DB_RUNRECOVERY">DB_RUNRECOVERY</a>,
206 which indicates that the
207 system must stop and recovery must be run.</p>
208 <p>The above code can be simplified in the case of a transaction comprised
209 entirely of a single database put or delete operation, as operations
210 occurring in transactional databases are implicitly transaction
211 protected. For example, in a transactional database, the above code
212 could be more simply written as:</p>
213 <pre class="programlisting">
214 <strong class="userinput"><code>for (fail = 0; fail++ &lt;= MAXIMUM_RETRY &amp;&amp;
215 (ret = db-&gt;put(db, NULL, &amp;key, &amp;data, 0)) == DB_LOCK_DEADLOCK;)
216 continue;
217 return (ret == 0 ? 0 : 1);</code></strong></pre>
218 <p>and the underlying transaction would be automatically handled by Berkeley DB.</p>
219 <p>Programmers should not attempt to enumerate all possible error returns
220 in their software. Instead, they should explicitly handle expected
221 returns and default to aborting the transaction for the rest. It is
222 entirely the choice of the programmer whether to check for
223 <a class="link" href="program_errorret.html#program_errorret.DB_RUNRECOVERY">DB_RUNRECOVERY</a>
224 explicitly or not — attempting new Berkeley DB
225 operations after
226 <a class="link" href="program_errorret.html#program_errorret.DB_RUNRECOVERY">DB_RUNRECOVERY</a>
227 is returned does not worsen the
228 situation. Alternatively, using the <a href="../api_reference/C/envevent_notify.html" class="olink">DB_ENV-&gt;set_event_notify()</a> method to
229 handle an unrecoverable error and simply doing some number of
230 abort-and-retry cycles for any unexpected Berkeley DB or system error in the
231 mainline code often results in the simplest and cleanest application
232 code.</p>
233 </div>
234 <div class="navfooter">
235 <hr />
236 <table width="100%" summary="Navigation footer">
237 <tr>
238 <td width="40%" align="left"><a accesskey="p" href="transapp_data_open.html">Prev</a> </td>
239 <td width="20%" align="center">
240 <a accesskey="u" href="transapp.html">Up</a>
241 </td>
242 <td width="40%" align="right"> <a accesskey="n" href="transapp_atomicity.html">Next</a></td>
243 </tr>
244 <tr>
245 <td width="40%" align="left" valign="top">Opening the databases </td>
246 <td width="20%" align="center">
247 <a accesskey="h" href="index.html">Home</a>
248 </td>
249 <td width="40%" align="right" valign="top"> Atomicity</td>
250 </tr>
251 </table>
252 </div>
253 </body>
254 </html>