Debian Codegraph @

doc/manual.xhtml

raw symbols SCIP
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
4
5 <head>
6 <title>C++ Object Persistence with ODB</title>
7
8 <meta name="copyright" content="&copy; 2009-2015 Code Synthesis Tools CC"/>
9 <meta name="keywords" content="odb,c++,object,persistence,ORM,relational,database,RDBMS,ODBMS,OODBMS"/>
10 <meta name="description" content="C++ Object Persistence with ODB"/>
11 <meta name="revision" content="2.4"/>
12 <meta name="version" content="2.4.0"/>
13
14 <!--
15
16 If you make changes to this document, follow these stylistic rules
17 for consistency.
18
19 - Don't use 'object' for instances of non-persistent classes. Use
20 'instance' instead.
21
22 - Each overloaded function should still be referred to as function.
23 When saying that a function is overloaded, use term 'version',
24 for example The persist() function has two overloaded versions.
25 Don't use version to refer to individual functions, use function
26 instead. The same holds for constructors.
27
28 - Use 'object id' and 'object's identifier'. But not other combinations
29 of the two.
30
31 @@ Check that parts TOCs are up to date.
32
33 -->
34
35 <link rel="stylesheet" type="text/css" href="default.css" />
36
37 <style type="text/css">
38 pre {
39 padding : 0 0 0 0em;
40 margin : 0em 0em 0em 0;
41
42 font-size : 102%
43 }
44
45 body {
46 min-width: 48em;
47 }
48
49 h1 {
50 font-weight: bold;
51 font-size: 200%;
52 line-height: 1.2em;
53 }
54
55 h2 {
56 font-weight : bold;
57 font-size : 150%;
58
59 padding-top : 0.8em;
60 }
61
62 h3 {
63 font-size : 140%;
64 padding-top : 0.8em;
65 }
66
67 /* Force page break for both PDF and HTML (when printing). */
68 hr.page-break {
69 height: 0;
70 width: 0;
71 border: 0;
72 visibility: hidden;
73
74 page-break-after: always;
75 }
76
77 /* Adjust indentation for three levels. */
78 #container {
79 max-width: 48em;
80 }
81
82 #content {
83 padding: 0 0.1em 0 4em;
84 /*background-color: red;*/
85 }
86
87 #content h1 {
88 margin-left: -2.06em;
89 }
90
91 #content h2 {
92 margin-left: -1.33em;
93 }
94
95 /* Title page */
96
97 #titlepage {
98 padding: 2em 0 1em 0;
99 border-bottom: 1px solid black;
100 }
101
102 #titlepage .title {
103 font-weight: bold;
104 font-size: 200%;
105 text-align: center;
106 padding: 1em 0 2em 0;
107 }
108
109 #titlepage p {
110 padding-bottom: 1em;
111 }
112
113 #titlepage #revision {
114 padding-bottom: 0em;
115 }
116
117 /* Lists */
118 ul.list li, ol.list li {
119 padding-top : 0.3em;
120 padding-bottom : 0.3em;
121 }
122
123 div.img {
124 text-align: center;
125 padding: 2em 0 2em 0;
126 }
127
128 /* */
129 dl dt {
130 padding : 0.8em 0 0 0;
131 }
132
133 /* TOC */
134 table.toc {
135 border-style : none;
136 border-collapse : separate;
137 border-spacing : 0;
138
139 margin : 0.2em 0 0.2em 0;
140 padding : 0 0 0 0;
141 }
142
143 table.toc tr {
144 padding : 0 0 0 0;
145 margin : 0 0 0 0;
146 }
147
148 table.toc * td, table.toc * th {
149 border-style : none;
150 margin : 0 0 0 0;
151 vertical-align : top;
152 }
153
154 table.toc * th {
155 font-weight : normal;
156 padding : 0em 0.1em 0em 0;
157 text-align : left;
158 white-space : nowrap;
159 }
160
161 table.toc * table.toc th {
162 padding-left : 1em;
163 }
164
165 table.toc * td {
166 padding : 0em 0 0em 0.7em;
167 text-align : left;
168 }
169
170 /* operators table */
171 #operators {
172 margin: 2em 0 2em 0;
173
174 border-collapse : collapse;
175 border : 1px solid;
176 border-color : #000000;
177
178 font-size : 11px;
179 line-height : 14px;
180 }
181
182 #operators th, #operators td {
183 border: 1px solid;
184 padding : 0.9em 0.9em 0.7em 0.9em;
185 }
186
187 #operators th {
188 background : #cde8f6;
189 }
190
191 #operators td {
192 text-align: left;
193 }
194
195 /* scenarios table */
196 .scenarios {
197 margin: 2em 0 2em 0;
198
199 border-collapse : collapse;
200 border : 1px solid;
201 border-color : #000000;
202
203 font-size : 11px;
204 line-height : 14px;
205 }
206
207 .scenarios th, .scenarios td {
208 border: 1px solid;
209 padding : 0.9em 0.9em 0.7em 0.9em;
210 }
211
212 .scenarios th {
213 background : #cde8f6;
214 }
215
216 .scenarios td {
217 text-align: left;
218 }
219
220 /* specifiers table */
221 .specifiers {
222 margin: 2em 0 2em 0;
223
224 border-collapse : collapse;
225 border : 1px solid;
226 border-color : #000000;
227
228 font-size : 11px;
229 line-height : 14px;
230 }
231
232 .specifiers th, .specifiers td {
233 border: 1px solid;
234 padding : 0.9em 0.9em 0.7em 0.9em;
235 }
236
237 .specifiers th {
238 background : #cde8f6;
239 }
240
241 .specifiers td {
242 text-align: left;
243 }
244
245 /* mapping table */
246 #mapping {
247 margin: 2em 0 2em 0;
248
249 border-collapse : collapse;
250 border : 1px solid;
251 border-color : #000000;
252
253 font-size : 11px;
254 line-height : 14px;
255 }
256
257 #mapping th, #mapping td {
258 border: 1px solid;
259 padding : 0.9em 0.9em 0.7em 0.9em;
260 }
261
262 #mapping th {
263 background : #cde8f6;
264 }
265
266 #mapping td {
267 text-align: left;
268 }
269
270 </style>
271
272
273 </head>
274
275 <body>
276 <div id="container">
277 <div id="content">
278
279 <div class="noprint">
280
281 <div id="titlepage">
282 <div class="title">C++ Object Persistence with ODB</div>
283
284 <p>Copyright &copy; 2009-2015 Code Synthesis Tools CC</p>
285
286 <p>Permission is granted to copy, distribute and/or modify this
287 document under the terms of the
288 <a href="http://www.codesynthesis.com/licenses/fdl-1.3.txt">GNU Free
289 Documentation License, version 1.3</a>; with no Invariant Sections,
290 no Front-Cover Texts and no Back-Cover Texts.</p>
291
292 <!-- REMEMBER TO CHANGE VERSIONS IN THE META TAGS ABOVE! -->
293 <p id="revision">Revision 2.4, February 2015</p>
294 <p>This revision of the manual describes ODB 2.4.0 and is available
295 in the following formats:
296 <a href="http://www.codesynthesis.com/products/odb/doc/manual.xhtml">XHTML</a>,
297 <a href="http://www.codesynthesis.com/products/odb/doc/odb-manual.pdf">PDF</a>, and
298 <a href="http://www.codesynthesis.com/products/odb/doc/odb-manual.ps">PostScript</a>.</p>
299 </div>
300
301 <hr class="page-break"/>
302 <h1>Table of Contents</h1>
303
304 <table class="toc">
305 <tr>
306 <th></th><td><a href="#0">Preface</a>
307 <table class="toc">
308 <tr><th></th><td><a href="#0.1">About This Document</a></td></tr>
309 <tr><th></th><td><a href="#0.2">More Information</a></td></tr>
310 </table>
311 </td>
312 </tr>
313
314 <tr>
315 <th colspan="2"><a href="#I">PART I OBJECT-RELATIONAL MAPPING</a></th>
316 </tr>
317
318 <tr>
319 <th>1</th><td><a href="#1">Introduction</a>
320 <table class="toc">
321 <tr><th>1.1</th><td><a href="#1.1">Architecture and Workflow</a></td></tr>
322 <tr><th>1.2</th><td><a href="#1.2">Benefits</a></td></tr>
323 <tr><th>1.3</th><td><a href="#1.3">Supported C++ Standards</a></td></tr>
324 </table>
325 </td>
326 </tr>
327
328 <tr>
329 <th>2</th><td><a href="#2">Hello World Example</a>
330 <table class="toc">
331 <tr><th>2.1</th><td><a href="#2.1">Declaring Persistent Classes</a></td></tr>
332 <tr><th>2.2</th><td><a href="#2.2">Generating Database Support Code</a></td></tr>
333 <tr><th>2.3</th><td><a href="#2.3">Compiling and Running</a></td></tr>
334 <tr><th>2.4</th><td><a href="#2.4">Making Objects Persistent</a></td></tr>
335 <tr><th>2.5</th><td><a href="#2.5">Querying the Database for Objects</a></td></tr>
336 <tr><th>2.6</th><td><a href="#2.6">Updating Persistent Objects</a></td></tr>
337 <tr><th>2.7</th><td><a href="#2.7">Defining and Using Views</a></td></tr>
338 <tr><th>2.8</th><td><a href="#2.8">Deleting Persistent Objects</a></td></tr>
339 <tr><th>2.9</th><td><a href="#2.9">Changing Persistent Classes</a></td></tr>
340 <tr><th>2.10</th><td><a href="#2.10">Accessing Multiple Databases</a></td></tr>
341 <tr><th>2.11</th><td><a href="#2.11">Summary</a></td></tr>
342 </table>
343 </td>
344 </tr>
345
346 <tr>
347 <th>3</th><td><a href="#3">Working with Persistent Objects</a>
348 <table class="toc">
349 <tr><th>3.1</th><td><a href="#3.1">Concepts and Terminology</a></td></tr>
350 <tr><th>3.2</th><td><a href="#3.2">Declaring Persistent Objects and Values</a></td></tr>
351 <tr><th>3.3</th><td><a href="#3.3">Object and View Pointers</a></td></tr>
352 <tr><th>3.4</th><td><a href="#3.4">Database</a></td></tr>
353 <tr><th>3.5</th><td><a href="#3.5">Transactions</a></td></tr>
354 <tr><th>3.6</th><td><a href="#3.6">Connections</a></td></tr>
355 <tr><th>3.7</th><td><a href="#3.7">Error Handling and Recovery</a></td></tr>
356 <tr><th>3.8</th><td><a href="#3.8">Making Objects Persistent</a></td></tr>
357 <tr><th>3.9</th><td><a href="#3.9">Loading Persistent Objects</a></td></tr>
358 <tr><th>3.10</th><td><a href="#3.10">Updating Persistent Objects</a></td></tr>
359 <tr><th>3.11</th><td><a href="#3.11">Deleting Persistent Objects</a></td></tr>
360 <tr><th>3.12</th><td><a href="#3.12">Executing Native SQL Statements</a></td></tr>
361 <tr><th>3.13</th><td><a href="#3.13">Tracing SQL Statement Execution</a></td></tr>
362 <tr><th>3.14</th><td><a href="#3.14">ODB Exceptions</a></td></tr>
363 </table>
364 </td>
365 </tr>
366
367 <tr>
368 <th>4</th><td><a href="#4">Querying the Database</a>
369 <table class="toc">
370 <tr><th>4.1</th><td><a href="#4.1">ODB Query Language</a></td></tr>
371 <tr><th>4.2</th><td><a href="#4.2">Parameter Binding</a></td></tr>
372 <tr><th>4.3</th><td><a href="#4.3">Executing a Query</a></td></tr>
373 <tr><th>4.4</th><td><a href="#4.4">Query Result</a></td></tr>
374 <tr><th>4.5</th><td><a href="#4.5">Prepared Queries</a></td></tr>
375 </table>
376 </td>
377 </tr>
378
379 <tr>
380 <th>5</th><td><a href="#5">Containers</a>
381 <table class="toc">
382 <tr><th>5.1</th><td><a href="#5.1">Ordered Containers</a></td></tr>
383 <tr><th>5.2</th><td><a href="#5.2">Set and Multiset Containers</a></td></tr>
384 <tr><th>5.3</th><td><a href="#5.3">Map and Multimap Containers</a></td></tr>
385 <tr>
386 <th>5.4</th><td><a href="#5.4">Change-Tracking Containers</a>
387 <table class="toc">
388 <tr><th>5.4.1</th><td><a href="#5.4.1">Change-Tracking <code>vector</code></a></td></tr>
389 </table>
390 </td>
391 </tr>
392 <tr><th>5.5</th><td><a href="#5.5">Using Custom Containers</a></td></tr>
393 </table>
394 </td>
395 </tr>
396
397 <tr>
398 <th>6</th><td><a href="#6">Relationships</a>
399 <table class="toc">
400 <tr>
401 <th>6.1</th><td><a href="#6.1">Unidirectional Relationships</a>
402 <table class="toc">
403 <tr><th>6.1.1</th><td><a href="#6.1.1">To-One Relationships</a></td></tr>
404 <tr><th>6.1.2</th><td><a href="#6.1.2">To-Many Relationships</a></td></tr>
405 </table>
406 </td>
407 </tr>
408 <tr>
409 <th>6.2</th><td><a href="#6.2">Bidirectional Relationships</a>
410 <table class="toc">
411 <tr><th>6.2.1</th><td><a href="#6.2.1">One-to-One Relationships</a></td></tr>
412 <tr><th>6.2.2</th><td><a href="#6.2.2">One-to-Many Relationships</a></td></tr>
413 <tr><th>6.2.3</th><td><a href="#6.2.3">Many-to-Many Relationships</a></td></tr>
414 </table>
415 </td>
416 </tr>
417 <tr><th>6.3</th><td><a href="#6.3">Circular Relationships</a></td></tr>
418 <tr><th>6.4</th><td><a href="#6.4">Lazy Pointers</a></td></tr>
419 <tr><th>6.5</th><td><a href="#6.5">Using Custom Smart Pointers</a></td></tr>
420 </table>
421 </td>
422 </tr>
423
424 <tr>
425 <th>7</th><td><a href="#7">Value Types</a>
426 <table class="toc">
427 <tr><th>7.1</th><td><a href="#7.1">Simple Value Types</a></td></tr>
428 <tr>
429 <th>7.2</th><td><a href="#7.2">Composite Value Types</a>
430 <table class="toc">
431 <tr><th>7.2.1</th><td><a href="#7.2.1">Composite Object Ids</a></td></tr>
432 <tr><th>7.2.2</th><td><a href="#7.2.2">Composite Value Column and Table Names</a></td></tr>
433 </table>
434 </td>
435 </tr>
436 <tr><th>7.3</th><td><a href="#7.3">Pointers and <code>NULL</code> Value Semantics</a></td></tr>
437 </table>
438 </td>
439 </tr>
440
441 <tr>
442 <th>8</th><td><a href="#8">Inheritance</a>
443 <table class="toc">
444 <tr><th>8.1</th><td><a href="#8.1">Reuse Inheritance</a></td></tr>
445 <tr>
446 <th>8.2</th><td><a href="#8.2">Polymorphism Inheritance</a>
447 <table class="toc">
448 <tr><th>8.2.1</th><td><a href="#8.2.1">Performance and Limitations</a></td></tr>
449 </table>
450 </td>
451 </tr>
452 <tr><th>8.3</th><td><a href="#8.3">Mixed Inheritance</a></td></tr>
453 </table>
454 </td>
455 </tr>
456
457 <tr>
458 <th>9</th><td><a href="#9">Sections</a>
459 <table class="toc">
460 <tr><th>9.1</th><td><a href="#9.1">Sections and Inheritance</a></td></tr>
461 <tr><th>9.2</th><td><a href="#9.2">Sections and Optimistic Concurrency</a></td></tr>
462 <tr><th>9.3</th><td><a href="#9.3">Sections and Lazy Pointers</a></td></tr>
463 <tr><th>9.4</th><td><a href="#9.4">Sections and Change-Tracking Containers</a></td></tr>
464 </table>
465 </td>
466 </tr>
467
468 <tr>
469 <th>10</th><td><a href="#10">Views</a>
470 <table class="toc">
471 <tr><th>10.1</th><td><a href="#10.1">Object Views</a></td></tr>
472 <tr><th>10.2</th><td><a href="#10.2">Object Loading Views</a></td></tr>
473 <tr><th>10.3</th><td><a href="#10.3">Table Views</a></td></tr>
474 <tr><th>10.4</th><td><a href="#10.4">Mixed Views</a></td></tr>
475 <tr><th>10.5</th><td><a href="#10.5">View Query Conditions</a></td></tr>
476 <tr><th>10.6</th><td><a href="#10.6">Native Views</a></td></tr>
477 <tr><th>10.7</th><td><a href="#10.7">Other View Features and Limitations</a></td></tr>
478 </table>
479 </td>
480 </tr>
481
482 <tr>
483 <th>11</th><td><a href="#11">Session</a>
484 <table class="toc">
485 <tr><th>11.1</th><td><a href="#11.1">Object Cache</a></td></tr>
486 <tr><th>11.2</th><td><a href="#11.2">Custom Sessions</a></td></tr>
487 </table>
488 </td>
489 </tr>
490
491 <tr>
492 <th>12</th><td><a href="#12">Optimistic Concurrency</a></td>
493 </tr>
494
495 <tr>
496 <th>13</th><td><a href="#13">Database Schema Evolution</a>
497 <table class="toc">
498 <tr><th>13.1</th><td><a href="#13.1">Object Model Version and Changelog</a></td></tr>
499 <tr><th>13.2</th><td><a href="#13.2">Schema Migration</a></td></tr>
500 <tr>
501 <th>13.3</th><td><a href="#13.3">Data Migration</a>
502 <table class="toc">
503 <tr><th>13.3.1</th><td><a href="#13.3.1">Immediate Data Migration</a></td></tr>
504 <tr><th>13.3.2</th><td><a href="#13.3.2">Gradual Data Migration</a></td></tr>
505 </table>
506 </td>
507 </tr>
508 <tr>
509 <th>13.4</th><td><a href="#13.4">Soft Object Model Changes</a>
510 <table class="toc">
511 <tr><th>13.4.1</th><td><a href="#13.4.1">Reuse Inheritance Changes</a></td></tr>
512 <tr><th>13.4.2</th><td><a href="#13.4.2">Polymorphism Inheritance Changes</a></td></tr>
513 </table>
514 </td>
515 </tr>
516 </table>
517 </td>
518 </tr>
519
520 <tr>
521 <th>14</th><td><a href="#14">ODB Pragma Language</a>
522 <table class="toc">
523 <tr>
524 <th>14.1</th><td><a href="#14.1">Object Type Pragmas</a>
525 <table class="toc">
526 <tr><th>14.1.1</th><td><a href="#14.1.1"><code>table</code></a></td></tr>
527 <tr><th>14.1.2</th><td><a href="#14.1.2"><code>pointer</code></a></td></tr>
528 <tr><th>14.1.3</th><td><a href="#14.1.3"><code>abstract</code></a></td></tr>
529 <tr><th>14.1.4</th><td><a href="#14.1.4"><code>readonly</code></a></td></tr>
530 <tr><th>14.1.5</th><td><a href="#14.1.5"><code>optimistic</code></a></td></tr>
531 <tr><th>14.1.6</th><td><a href="#14.1.6"><code>no_id</code></a></td></tr>
532 <tr><th>14.1.7</th><td><a href="#14.1.7"><code>callback</code></a></td></tr>
533 <tr><th>14.1.8</th><td><a href="#14.1.8"><code>schema</code></a></td></tr>
534 <tr><th>14.1.9</th><td><a href="#14.1.9"><code>polymorphic</code></a></td></tr>
535 <tr><th>14.1.10</th><td><a href="#14.1.10"><code>session</code></a></td></tr>
536 <tr><th>14.1.11</th><td><a href="#14.1.11"><code>definition</code></a></td></tr>
537 <tr><th>14.1.12</th><td><a href="#14.1.12"><code>transient</code></a></td></tr>
538 <tr><th>14.1.13</th><td><a href="#14.1.13"><code>sectionable</code></a></td></tr>
539 <tr><th>14.1.14</th><td><a href="#14.1.14"><code>deleted</code></a></td></tr>
540 <tr><th>14.1.15</th><td><a href="#14.1.15"><code>bulk</code></a></td></tr>
541 </table>
542 </td>
543 </tr>
544 <tr>
545 <th>14.2</th><td><a href="#14.2">View Type Pragmas</a>
546 <table class="toc">
547 <tr><th>14.2.1</th><td><a href="#14.2.1"><code>object</code></a></td></tr>
548 <tr><th>14.2.2</th><td><a href="#14.2.2"><code>table</code></a></td></tr>
549 <tr><th>14.2.3</th><td><a href="#14.2.3"><code>query</code></a></td></tr>
550 <tr><th>14.2.4</th><td><a href="#14.2.4"><code>pointer</code></a></td></tr>
551 <tr><th>14.2.5</th><td><a href="#14.2.5"><code>callback</code></a></td></tr>
552 <tr><th>14.2.6</th><td><a href="#14.2.6"><code>definition</code></a></td></tr>
553 <tr><th>14.2.7</th><td><a href="#14.2.7"><code>transient</code></a></td></tr>
554 </table>
555 </td>
556 </tr>
557 <tr>
558 <th>14.3</th><td><a href="#14.3">Value Type Pragmas</a>
559 <table class="toc">
560 <tr><th>14.3.1</th><td><a href="#14.3.1"><code>type</code></a></td></tr>
561 <tr><th>14.3.2</th><td><a href="#14.3.2"><code>id_type</code></a></td></tr>
562 <tr><th>14.3.3</th><td><a href="#14.3.3"><code>null</code>/<code>not_null</code></a></td></tr>
563 <tr><th>14.3.4</th><td><a href="#14.3.4"><code>default</code></a></td></tr>
564 <tr><th>14.3.5</th><td><a href="#14.3.5"><code>options</code></a></td></tr>
565 <tr><th>14.3.6</th><td><a href="#14.3.6"><code>readonly</code></a></td></tr>
566 <tr><th>14.3.7</th><td><a href="#14.3.7"><code>definition</code></a></td></tr>
567 <tr><th>14.3.8</th><td><a href="#14.3.8"><code>transient</code></a></td></tr>
568 <tr><th>14.3.9</th><td><a href="#14.3.9"><code>unordered</code></a></td></tr>
569 <tr><th>14.3.10</th><td><a href="#14.3.10"><code>index_type</code></a></td></tr>
570 <tr><th>14.3.11</th><td><a href="#14.3.11"><code>key_type</code></a></td></tr>
571 <tr><th>14.3.12</th><td><a href="#14.3.12"><code>value_type</code></a></td></tr>
572 <tr><th>14.3.13</th><td><a href="#14.3.13"><code>value_null</code>/<code>value_not_null</code></a></td></tr>
573 <tr><th>14.3.14</th><td><a href="#14.3.14"><code>id_options</code></a></td></tr>
574 <tr><th>14.3.15</th><td><a href="#14.3.15"><code>index_options</code></a></td></tr>
575 <tr><th>14.3.16</th><td><a href="#14.3.16"><code>key_options</code></a></td></tr>
576 <tr><th>14.3.17</th><td><a href="#14.3.17"><code>value_options</code></a></td></tr>
577 <tr><th>14.3.18</th><td><a href="#14.3.18"><code>id_column</code></a></td></tr>
578 <tr><th>14.3.19</th><td><a href="#14.3.19"><code>index_column</code></a></td></tr>
579 <tr><th>14.3.20</th><td><a href="#14.3.20"><code>key_column</code></a></td></tr>
580 <tr><th>14.3.21</th><td><a href="#14.3.21"><code>value_column</code></a></td></tr>
581 </table>
582 </td>
583 </tr>
584 <tr>
585 <th>14.4</th><td><a href="#14.4">Data Member Pragmas</a>
586 <table class="toc">
587 <tr><th>14.4.1</th><td><a href="#14.4.1"><code>id</code></a></td></tr>
588 <tr><th>14.4.2</th><td><a href="#14.4.2"><code>auto</code></a></td></tr>
589 <tr><th>14.4.3</th><td><a href="#14.4.3"><code>type</code></a></td></tr>
590 <tr><th>14.4.4</th><td><a href="#14.4.4"><code>id_type</code></a></td></tr>
591 <tr><th>14.4.5</th><td><a href="#14.4.5"><code>get</code>/<code>set</code>/<code>access</code></a></td></tr>
592 <tr><th>14.4.6</th><td><a href="#14.4.6"><code>null</code>/<code>not_null</code></a></td></tr>
593 <tr><th>14.4.7</th><td><a href="#14.4.7"><code>default</code></a></td></tr>
594 <tr><th>14.4.8</th><td><a href="#14.4.8"><code>options</code></a></td></tr>
595 <tr><th>14.4.9</th><td><a href="#14.4.9"><code>column</code> (object, composite value)</a></td></tr>
596 <tr><th>14.4.10</th><td><a href="#14.4.10"><code>column</code> (view)</a></td></tr>
597 <tr><th>14.4.11</th><td><a href="#14.4.11"><code>transient</code></a></td></tr>
598 <tr><th>14.4.12</th><td><a href="#14.4.12"><code>readonly</code></a></td></tr>
599 <tr><th>14.4.13</th><td><a href="#14.4.13"><code>virtual</code></a></td></tr>
600 <tr><th>14.4.14</th><td><a href="#14.4.14"><code>inverse</code></a></td></tr>
601 <tr><th>14.4.15</th><td><a href="#14.4.15"><code>on_delete</code></a></td></tr>
602 <tr><th>14.4.16</th><td><a href="#14.4.16"><code>version</code></a></td></tr>
603 <tr><th>14.4.17</th><td><a href="#14.4.17"><code>index</code></a></td></tr>
604 <tr><th>14.4.18</th><td><a href="#14.4.18"><code>unique</code></a></td></tr>
605 <tr><th>14.4.19</th><td><a href="#14.4.19"><code>unordered</code></a></td></tr>
606 <tr><th>14.4.20</th><td><a href="#14.4.20"><code>table</code></a></td></tr>
607 <tr><th>14.4.21</th><td><a href="#14.4.21"><code>load</code>/<code>update</code></a></td></tr>
608 <tr><th>14.4.22</th><td><a href="#14.4.22"><code>section</code></a></td></tr>
609 <tr><th>14.4.23</th><td><a href="#14.4.23"><code>added</code></a></td></tr>
610 <tr><th>14.4.24</th><td><a href="#14.4.24"><code>deleted</code></a></td></tr>
611 <tr><th>14.4.25</th><td><a href="#14.4.25"><code>index_type</code></a></td></tr>
612 <tr><th>14.4.26</th><td><a href="#14.4.26"><code>key_type</code></a></td></tr>
613 <tr><th>14.4.27</th><td><a href="#14.4.27"><code>value_type</code></a></td></tr>
614 <tr><th>14.4.28</th><td><a href="#14.4.28"><code>value_null</code>/<code>value_not_null</code></a></td></tr>
615 <tr><th>14.4.29</th><td><a href="#14.4.29"><code>id_options</code></a></td></tr>
616 <tr><th>14.4.30</th><td><a href="#14.4.30"><code>index_options</code></a></td></tr>
617 <tr><th>14.4.31</th><td><a href="#14.4.31"><code>key_options</code></a></td></tr>
618 <tr><th>14.4.32</th><td><a href="#14.4.32"><code>value_options</code></a></td></tr>
619 <tr><th>14.4.33</th><td><a href="#14.4.33"><code>id_column</code></a></td></tr>
620 <tr><th>14.4.34</th><td><a href="#14.4.34"><code>index_column</code></a></td></tr>
621 <tr><th>14.4.35</th><td><a href="#14.4.35"><code>key_column</code></a></td></tr>
622 <tr><th>14.4.36</th><td><a href="#14.4.36"><code>value_column</code></a></td></tr>
623 </table>
624 </td>
625 </tr>
626 <tr>
627 <th>14.5</th><td><a href="#14.5">Namespace Pragmas</a>
628 <table class="toc">
629 <tr><th>14.5.1</th><td><a href="#14.5.1"><code>pointer</code></a></td></tr>
630 <tr><th>14.5.2</th><td><a href="#14.5.2"><code>table</code></a></td></tr>
631 <tr><th>14.5.3</th><td><a href="#14.5.3"><code>schema</code></a></td></tr>
632 <tr><th>14.5.4</th><td><a href="#14.5.4"><code>session</code></a></td></tr>
633 </table>
634 </td>
635 </tr>
636 <tr>
637 <th>14.6</th><td><a href="#14.6">Object Model Pragmas</a>
638 <table class="toc">
639 <tr><th>14.6.1</th><td><a href="#14.6.1"><code>version</code></a></td></tr>
640 </table>
641 </td>
642 </tr>
643 <tr>
644 <th>14.7</th><td><a href="#14.7">Index Definition Pragmas</a></td>
645 </tr>
646 <tr>
647 <th>14.8</th><td><a href="#14.8">Database Type Mapping Pragmas</a></td>
648 </tr>
649 <tr>
650 <th>14.9</th><td><a href="#14.9">C++ Compiler Warnings</a>
651 <table class="toc">
652 <tr><th>14.9.1</th><td><a href="#14.9.1">GNU C++</a></td></tr>
653 <tr><th>14.9.2</th><td><a href="#14.9.2">Visual C++</a></td></tr>
654 <tr><th>14.9.3</th><td><a href="#14.9.3">Sun C++</a></td></tr>
655 <tr><th>14.9.4</th><td><a href="#14.9.4">IBM XL C++</a></td></tr>
656 <tr><th>14.9.5</th><td><a href="#14.9.5">HP aC++</a></td></tr>
657 <tr><th>14.9.6</th><td><a href="#14.9.6">Clang</a></td></tr>
658 </table>
659 </td>
660 </tr>
661 </table>
662 </td>
663 </tr>
664
665 <tr>
666 <th>15</th><td><a href="#15">Advanced Techniques and Mechanisms</a>
667 <table class="toc">
668 <tr><th>15.1</th><td><a href="#15.1">Transaction Callbacks</a></td></tr>
669 <tr><th>15.2</th><td><a href="#15.2">Persistent Class Template Instantiations</a></td></tr>
670 <tr><th>15.3</th><td><a href="#15.3">Bulk Database Operations</a></td></tr>
671 </table>
672 </td>
673 </tr>
674
675 <tr>
676 <th colspan="2"><a href="#II">PART II DATABASE SYSTEMS</a></th>
677 </tr>
678
679 <tr>
680 <th>16</th><td><a href="#16">Multi-Database Support</a>
681 <table class="toc">
682 <tr><th>16.1</th><td><a href="#16.1">Static Multi-Database Support</a></td></tr>
683 <tr>
684 <th>16.2</th><td><a href="#16.2">Dynamic Multi-Database Support</a>
685 <table class="toc">
686 <tr><th>16.2.2</th><td><a href="#16.2.2">16.2.2 Dynamic Loading of Database Support Code</a></td></tr>
687 </table>
688 </td>
689 </tr>
690 </table>
691 </td>
692 </tr>
693
694 <tr>
695 <th>17</th><td><a href="#17">MySQL Database</a>
696 <table class="toc">
697 <tr>
698 <th>17.1</th><td><a href="#17.1">MySQL Type Mapping</a>
699 <table class="toc">
700 <tr><th>17.1.1</th><td><a href="#17.1.1">String Type Mapping</a></td></tr>
701 <tr><th>17.1.2</th><td><a href="#17.1.2">Binary Type Mapping</a></td></tr>
702 </table>
703 </td>
704 </tr>
705 <tr><th>17.2</th><td><a href="#17.2">MySQL Database Class</a></td></tr>
706 <tr><th>17.3</th><td><a href="#17.3">MySQL Connection and Connection Factory</a></td></tr>
707 <tr><th>17.4</th><td><a href="#17.4">MySQL Exceptions</a></td></tr>
708 <tr>
709 <th>17.5</th><td><a href="#17.5">MySQL Limitations</a>
710 <table class="toc">
711 <tr><th>17.5.1</th><td><a href="#17.5.1">Foreign Key Constraints</a></td></tr>
712 </table>
713 </td>
714 </tr>
715 <tr><th>17.6</th><td><a href="#17.6">MySQL Index Definition</a></td></tr>
716 <tr><th>17.7</th><td><a href="#17.7">MySQL Stored Procedures</a></td></tr>
717 </table>
718 </td>
719 </tr>
720
721 <tr>
722 <th>18</th><td><a href="#18">SQLite Database</a>
723 <table class="toc">
724 <tr>
725 <th>18.1</th><td><a href="#18.1">SQLite Type Mapping</a>
726 <table class="toc">
727 <tr><th>18.1.1</th><td><a href="#18.1.1">String Type Mapping</a></td></tr>
728 <tr><th>18.1.2</th><td><a href="#18.1.2">Binary Type Mapping</a></td></tr>
729 </table>
730 </td>
731 </tr>
732 <tr><th>18.2</th><td><a href="#18.2">SQLite Database Class</a></td></tr>
733 <tr><th>18.3</th><td><a href="#18.3">SQLite Connection and Connection Factory</a></td></tr>
734 <tr><th>18.4</th><td><a href="#18.4">SQLite Exceptions</a></td></tr>
735 <tr>
736 <th>18.5</th><td><a href="#18.5">SQLite Limitations</a>
737 <table class="toc">
738 <tr><th>18.5.1</th><td><a href="#18.5.1">Query Result Caching</a></td></tr>
739 <tr><th>18.5.2</th><td><a href="#18.5.2">Automatic Assignment of Object Ids</a></td></tr>
740 <tr><th>18.5.3</th><td><a href="#18.5.3">Foreign Key Constraints</a></td></tr>
741 <tr><th>18.5.4</th><td><a href="#18.5.4">Constraint Violations</a></td></tr>
742 <tr><th>18.5.5</th><td><a href="#18.5.5">Sharing of Queries</a></td></tr>
743 <tr><th>18.5.6</th><td><a href="#18.5.6">Forced Rollback</a></td></tr>
744 <tr><th>18.5.7</th><td><a href="#18.5.7">Database Schema Evolution</a></td></tr>
745 </table>
746 </td>
747 </tr>
748 <tr><th>18.6</th><td><a href="#18.6">SQLite Index Definition</a></td></tr>
749 </table>
750 </td>
751 </tr>
752
753 <tr>
754 <th>19</th><td><a href="#19">PostgreSQL Database</a>
755 <table class="toc">
756 <tr>
757 <th>19.1</th><td><a href="#19.1">PostgreSQL Type Mapping</a>
758 <table class="toc">
759 <tr><th>19.1.1</th><td><a href="#19.1.1">String Type Mapping</a></td></tr>
760 <tr><th>19.1.2</th><td><a href="#19.1.2">Binary Type and <code>UUID</code> Mapping</a></td></tr>
761 </table>
762 </td>
763 </tr>
764 <tr><th>19.2</th><td><a href="#19.2">PostgreSQL Database Class</a></td></tr>
765 <tr><th>19.3</th><td><a href="#19.3">PostgreSQL Connection and Connection Factory</a></td></tr>
766 <tr><th>19.4</th><td><a href="#19.4">PostgreSQL Exceptions</a></td></tr>
767 <tr>
768 <th>19.5</th><td><a href="#19.5">PostgreSQL Limitations</a>
769 <table class="toc">
770 <tr><th>19.5.1</th><td><a href="#19.5.1">Query Result Caching</a></td></tr>
771 <tr><th>19.5.2</th><td><a href="#19.5.2">Foreign Key Constraints</a></td></tr>
772 <tr><th>19.5.3</th><td><a href="#19.5.3">Unique Constraint Violations</a></td></tr>
773 <tr><th>19.5.4</th><td><a href="#19.5.4">Date-Time Format</a></td></tr>
774 <tr><th>19.5.5</th><td><a href="#19.5.5">Timezones</a></td></tr>
775 <tr><th>19.5.6</th><td><a href="#19.5.6"><code>NUMERIC</code> Type Support</a></td></tr>
776 </table>
777 </td>
778 </tr>
779 <tr><th>19.6</th><td><a href="#19.6">PostgreSQL Index Definition</a></td></tr>
780 </table>
781 </td>
782 </tr>
783
784 <tr>
785 <th>20</th><td><a href="#20">Oracle Database</a>
786 <table class="toc">
787 <tr>
788 <th>20.1</th><td><a href="#20.1">Oracle Type Mapping</a>
789 <table class="toc">
790 <tr><th>20.1.1</th><td><a href="#20.1.1">String Type Mapping</a></td></tr>
791 <tr><th>20.1.2</th><td><a href="#20.1.2">Binary Type Mapping</a></td></tr>
792 </table>
793 </td>
794 </tr>
795 <tr><th>20.2</th><td><a href="#20.2">Oracle Database Class</a></td></tr>
796 <tr><th>20.3</th><td><a href="#20.3">Oracle Connection and Connection Factory</a></td></tr>
797 <tr><th>20.4</th><td><a href="#20.4">Oracle Exceptions</a></td></tr>
798 <tr>
799 <th>20.5</th><td><a href="#20.5">Oracle Limitations</a>
800 <table class="toc">
801 <tr><th>20.5.1</th><td><a href="#20.5.1">Identifier Truncation</a></td></tr>
802 <tr><th>20.5.2</th><td><a href="#20.5.2">Query Result Caching</a></td></tr>
803 <tr><th>20.5.3</th><td><a href="#20.5.3">Foreign Key Constraints</a></td></tr>
804 <tr><th>20.5.4</th><td><a href="#20.5.4">Unique Constraint Violations</a></td></tr>
805 <tr><th>20.5.5</th><td><a href="#20.5.5">Large <code>FLOAT</code> and <code>NUMBER</code> Types</a></td></tr>
806 <tr><th>20.5.6</th><td><a href="#20.5.6">Timezones</a></td></tr>
807 <tr><th>20.5.7</th><td><a href="#20.5.7"><code>LONG</code> Types</a></td></tr>
808 <tr><th>20.5.8</th><td><a href="#20.5.8">LOB Types and By-Value Accessors/Modifiers</a></td></tr>
809 <tr><th>20.5.9</th><td><a href="#20.5.9">Database Schema Evolution</a></td></tr>
810 </table>
811 </td>
812 </tr>
813 <tr><th>20.6</th><td><a href="#20.6">Oracle Index Definition</a></td></tr>
814 </table>
815 </td>
816 </tr>
817
818 <tr>
819 <th>21</th><td><a href="#21">Microsoft SQL Server Database</a>
820 <table class="toc">
821 <tr>
822 <th>21.1</th><td><a href="#21.1">SQL Server Type Mapping</a>
823 <table class="toc">
824 <tr><th>21.1.1</th><td><a href="#21.1.1">String Type Mapping</a></td></tr>
825 <tr><th>21.1.2</th><td><a href="#21.1.2">Binary Type and <code>UNIQUEIDENTIFIER</code> Mapping</a></td></tr>
826 <tr><th>21.1.3</th><td><a href="#21.1.3"><code>ROWVERSION</code> Mapping</a></td></tr>
827 <tr><th>21.1.4</th><td><a href="#21.1.4">Long String and Binary Types</a></td></tr>
828 </table>
829 </td>
830 </tr>
831 <tr><th>21.2</th><td><a href="#21.2">SQL Server Database Class</a></td></tr>
832 <tr><th>21.3</th><td><a href="#21.3">SQL Server Connection and Connection Factory</a></td></tr>
833 <tr><th>21.4</th><td><a href="#21.4">SQL Server Exceptions</a></td></tr>
834 <tr>
835 <th>21.5</th><td><a href="#21.5">SQL Server Limitations</a>
836 <table class="toc">
837 <tr><th>21.5.1</th><td><a href="#21.5.1">Query Result Caching</a></td></tr>
838 <tr><th>21.5.2</th><td><a href="#21.5.2">Foreign Key Constraints</a></td></tr>
839 <tr><th>21.5.3</th><td><a href="#21.5.3">Unique Constraint Violations</a></td></tr>
840 <tr><th>21.5.4</th><td><a href="#21.5.4">Multi-threaded Windows Applications</a></td></tr>
841 <tr><th>21.5.5</th><td><a href="#21.5.5">Affected Row Count and DDL Statements</a></td></tr>
842 <tr><th>21.5.6</th><td><a href="#21.5.6">Long Data and Auto Object Ids, <code>ROWVERSION</code></a></td></tr>
843 <tr><th>21.5.7</th><td><a href="#21.5.7">Long Data and By-Value Accessors/Modifiers</a></td></tr>
844 <tr><th>21.5.8</th><td><a href="#21.5.8">Bulk Update and <code>ROWVERSION</code></a></td></tr>
845 </table>
846 </td>
847 </tr>
848 <tr><th>21.6</th><td><a href="#21.6">SQL Server Index Definition</a></td></tr>
849 <tr><th>21.7</th><td><a href="#21.7">SQL Server Stored Procedures</a></td></tr>
850 </table>
851 </td>
852 </tr>
853
854 <tr>
855 <th colspan="2"><a href="#III">PART III PROFILES</a></th>
856 </tr>
857
858 <tr>
859 <th>22</th><td><a href="#22">Profiles Introduction</a></td>
860 </tr>
861
862 <tr>
863 <th>23</th><td><a href="#23">Boost Profile</a>
864 <table class="toc">
865 <tr><th>23.1</th><td><a href="#23.1">Smart Pointers Library</a></td></tr>
866 <tr><th>23.2</th><td><a href="#23.2">Unordered Containers Library</a></td></tr>
867 <tr><th>23.3</th><td><a href="#23.3">Multi-Index Container Library</a></td></tr>
868 <tr><th>23.4</th><td><a href="#23.4">Optional Library</a></td></tr>
869 <tr>
870 <th>23.5</th><td><a href="#23.5">Date Time Library</a>
871 <table class="toc">
872 <tr><th>23.5.1</th><td><a href="#23.5.1">MySQL Database Type Mapping</a></td></tr>
873 <tr><th>23.5.2</th><td><a href="#23.5.2">SQLite Database Type Mapping</a></td></tr>
874 <tr><th>23.5.3</th><td><a href="#23.5.3">PostgreSQL Database Type Mapping</a></td></tr>
875 <tr><th>23.5.4</th><td><a href="#23.5.4">Oracle Database Type Mapping</a></td></tr>
876 <tr><th>23.5.5</th><td><a href="#23.5.5">SQL Server Database Type Mapping</a></td></tr>
877 </table>
878 </td>
879 </tr>
880 <tr>
881 <th>23.6</th><td><a href="#23.6">Uuid Library</a>
882 <table class="toc">
883 <tr><th>23.6.1</th><td><a href="#23.6.1">MySQL Database Type Mapping</a></td></tr>
884 <tr><th>23.6.2</th><td><a href="#23.6.2">SQLite Database Type Mapping</a></td></tr>
885 <tr><th>23.6.3</th><td><a href="#23.6.3">PostgreSQL Database Type Mapping</a></td></tr>
886 <tr><th>23.6.4</th><td><a href="#23.6.4">Oracle Database Type Mapping</a></td></tr>
887 <tr><th>23.6.5</th><td><a href="#23.6.5">SQL Server Database Type Mapping</a></td></tr>
888 </table>
889 </td>
890 </tr>
891 </table>
892 </td>
893 </tr>
894
895 <tr>
896 <th>24</th><td><a href="#24">Qt Profile</a>
897 <table class="toc">
898 <tr>
899 <th>24.1</th><td><a href="#24.1">Basic Types Library</a>
900 <table class="toc">
901 <tr><th>24.1.1</th><td><a href="#24.1.1">MySQL Database Type Mapping</a></td></tr>
902 <tr><th>24.1.2</th><td><a href="#24.1.2">SQLite Database Type Mapping</a></td></tr>
903 <tr><th>24.1.3</th><td><a href="#24.1.3">PostgreSQL Database Type Mapping</a></td></tr>
904 <tr><th>24.1.4</th><td><a href="#24.1.4">Oracle Database Type Mapping</a></td></tr>
905 <tr><th>24.1.5</th><td><a href="#24.1.5">SQL Server Database Type Mapping</a></td></tr>
906 </table>
907 </td>
908 </tr>
909 <tr><th>24.2</th><td><a href="#24.2">Smart Pointers Library</a></td></tr>
910 <tr>
911 <th>24.3</th><td><a href="#24.3">Containers Library</a>
912 <table class="toc">
913 <tr><th>24.3.1</th><td><a href="#24.3.1">Change-Tracking <code>QList</code></a></td></tr>
914 </table>
915 </td>
916 </tr>
917 <tr>
918 <th>24.4</th><td><a href="#24.4">Date Time Library</a>
919 <table class="toc">
920 <tr><th>24.4.1</th><td><a href="#24.4.1">MySQL Database Type Mapping</a></td></tr>
921 <tr><th>24.4.2</th><td><a href="#24.4.2">SQLite Database Type Mapping</a></td></tr>
922 <tr><th>24.4.3</th><td><a href="#24.4.3">PostgreSQL Database Type Mapping</a></td></tr>
923 <tr><th>24.4.4</th><td><a href="#24.4.4">Oracle Database Type Mapping</a></td></tr>
924 <tr><th>24.4.5</th><td><a href="#24.4.5">SQL Server Database Type Mapping</a></td></tr>
925 </table>
926 </td>
927 </tr>
928 </table>
929 </td>
930 </tr>
931
932 </table>
933 </div>
934
935 <hr class="page-break"/>
936 <h1><a name="0">Preface</a></h1>
937
938 <p>As more critical aspects of our lives become dependant on software
939 systems, more and more applications are required to save the data
940 they work on in persistent and reliable storage. Database management
941 systems and, in particular, relational database management systems
942 (RDBMS) are commonly used for such storage. However, while the
943 application development techniques and programming languages have
944 evolved significantly over the past decades, the relational database
945 technology in this area stayed relatively unchanged. In particular,
946 this led to the now infamous mismatch between the object-oriented
947 model used by many modern applications and the relational model still
948 used by RDBMS.</p>
949
950 <p>While relational databases may be inconvenient to use from modern
951 programming languages, they are still the main choice for many
952 applications due to their maturity, reliability, as well as the
953 availability of tools and alternative implementations.</p>
954
955 <p>To allow application developers to utilize relational databases
956 from their object-oriented applications, a technique called
957 object-relational mapping (ORM) is often used. It involves a
958 conversion layer that maps between objects in the application's
959 memory and their relational representation in the database. While
960 the object-relational mapping code can be written manually,
961 automated ORM systems are available for most object-oriented
962 programming languages in use today.</p>
963
964 <p>ODB is an ORM system for the C++ programming language. It was
965 designed and implemented with the following main goals:</p>
966
967 <ul class="list">
968 <li>Provide a fully-automatic ORM system. In particular, the
969 application developer should not have to manually write any
970 mapping code, neither for persistent classes nor for their
971 data member. </li>
972
973 <li>Provide clean and easy to use object-oriented persistence
974 model and database APIs that support the development of realistic
975 applications for a wide variety of domains.</li>
976
977 <li>Provide a portable and thread-safe implementation. ODB should be
978 written in standard C++ and capable of persisting any standard
979 C++ classes.</li>
980
981 <li>Provide profiles that integrate ODB with type systems of
982 widely-used frameworks and libraries such as Qt and Boost.</li>
983
984 <li>Provide a high-performance and low overhead implementation. ODB
985 should make efficient use of database and application resources.</li>
986
987 </ul>
988
989
990 <h2><a name="0.1">About This Document</a></h2>
991
992 <p>The goal of this manual is to provide you with an understanding
993 of the object persistence model and APIs which are implemented by ODB.
994 As such, this document is intended for C++ application developers and
995 software architects who are looking for a C++ object persistence
996 solution. Prior experience with C++ is required to understand
997 this document. A basic understanding of relational database systems
998 is advantageous but not expected or required.</p>
999
1000
1001 <h2><a name="0.2">More Information</a></h2>
1002
1003 <p>Beyond this manual, you may also find the following sources of
1004 information useful:</p>
1005
1006 <ul class="list">
1007 <li><a href="http://www.codesynthesis.com/products/odb/doc/odb.xhtml">ODB
1008 Compiler Command Line Manual.</a></li>
1009
1010 <li>The <code>INSTALL</code> files in the ODB source packages provide
1011 build instructions for various platforms.</li>
1012
1013 <li>The <code>odb-examples</code> package contains a collection of
1014 examples and a README file with an overview of each example.</li>
1015
1016 <li>The <a href="http://www.codesynthesis.com/mailman/listinfo/odb-users">odb-users</a>
1017 mailing list is the place to ask technical questions about ODB.
1018 Furthermore, the searchable
1019 <a href="http://www.codesynthesis.com/pipermail/odb-users/">archives</a>
1020 may already have answers to some of your questions.</li>
1021
1022 </ul>
1023
1024
1025 <!-- PART -->
1026
1027
1028 <hr class="page-break"/>
1029 <h1><a name="I">PART I&nbsp;&nbsp;
1030 <span style="font-weight: normal;">OBJECT-RELATIONAL MAPPING</span></a></h1>
1031
1032 <p>Part I describes the essential database concepts, APIs, and tools that
1033 together comprise the object-relational mapping for C++ as implemented
1034 by ODB. It consists of the following chapters.</p>
1035
1036 <table class="toc">
1037 <tr><th>1</th><td><a href="#1">Introduction</a></td></tr>
1038 <tr><th>2</th><td><a href="#2">Hello World Example</a></td></tr>
1039 <tr><th>3</th><td><a href="#3">Working with Persistent Objects</a></td></tr>
1040 <tr><th>4</th><td><a href="#4">Querying the Database</a></td></tr>
1041 <tr><th>5</th><td><a href="#5">Containers</a></td></tr>
1042 <tr><th>6</th><td><a href="#6">Relationships</a></td></tr>
1043 <tr><th>7</th><td><a href="#7">Value Types</a></td></tr>
1044 <tr><th>8</th><td><a href="#8">Inheritance</a></td></tr>
1045 <tr><th>10</th><td><a href="#10">Views</a></td></tr>
1046 <tr><th>11</th><td><a href="#11">Session</a></td></tr>
1047 <tr><th>12</th><td><a href="#12">Optimistic Concurrency</a></td></tr>
1048 <tr><th>13</th><td><a href="#13">Database Schema Evolution</a></td></tr>
1049 <tr><th>14</th><td><a href="#14">ODB Pragma Language</a></td></tr>
1050 </table>
1051
1052
1053 <!-- CHAPTER -->
1054
1055
1056 <hr class="page-break"/>
1057 <h1><a name="1">1 Introduction</a></h1>
1058
1059 <p>ODB is an object-relational mapping (ORM) system for C++. It provides
1060 tools, APIs, and library support that allow you to persist C++ objects
1061 to a relational database (RDBMS) without having to deal with tables,
1062 columns, or SQL and without manually writing any of the mapping code.</p>
1063
1064 <p>ODB is highly flexible and customizable. It can either completely
1065 hide the relational nature of the underlying database or expose
1066 some of the details as required. For example, you can automatically
1067 map basic C++ types to suitable SQL types, generate the relational
1068 database schema for your persistent classes, and use simple, safe,
1069 and yet powerful object query language instead of SQL. Or you can
1070 assign SQL types to individual data members, use the existing
1071 database schema, run native SQL <code>SELECT</code> queries, and
1072 call stored procedures. In fact, at an extreme, ODB can be used
1073 as <em>just</em> a convenient way to handle results of native SQL
1074 queries.</p>
1075
1076 <p>ODB is not a framework. It does not dictate how you should write
1077 your application. Rather, it is designed to fit into your
1078 style and architecture by only handling object persistence
1079 and not interfering with any other functionality. There is
1080 no common base type that all persistent classes should derive
1081 from nor are there any restrictions on the data member types
1082 in persistent classes. Existing classes can be made persistent
1083 with a few or no modifications.</p>
1084
1085 <p>ODB has been designed for high performance and low memory
1086 overhead. Prepared statements are used to send and receive
1087 object state in binary format instead of text which reduces
1088 the load on the application and the database server. Extensive
1089 caching of connections, prepared statements, and buffers saves
1090 time and resources on connection establishment, statement parsing,
1091 and memory allocations. For each supported database system the
1092 native C API is used instead of ODBC or higher-level wrapper
1093 APIs to reduce overhead and provide the most efficient implementation
1094 for each database operation. Finally, persistent classes have
1095 zero memory overhead. There are no hidden "database" members
1096 that each class must have nor are there per-object data structures
1097 allocated by ODB.</p>
1098
1099 <p>In this chapter we present a high-level overview of ODB.
1100 We will start with the ODB architecture and then outline the
1101 workflow of building an application that uses ODB. We will
1102 then continue by contrasting the drawbacks of the traditional
1103 way of saving C++ objects to relational databases with the
1104 benefits of using ODB for object persistence. We conclude the
1105 chapter by discussing the C++ standards supported by ODB. The
1106 next chapter takes a more hands-on approach and shows the
1107 concrete steps necessary to implement object persistence in
1108 a simple "Hello World" application.</p>
1109
1110 <h2><a name="1.1">1.1 Architecture and Workflow</a></h2>
1111
1112 <p>From the application developer's perspective, ODB
1113 consists of three main components: the ODB compiler, the common
1114 runtime library, called <code>libodb</code>, and the
1115 database-specific runtime libraries, called
1116 <code>libodb-&lt;database></code>, where &lt;database> is
1117 the name of the database system this runtime
1118 is for, for example, <code>libodb-mysql</code>. For instance,
1119 if the application is going to use the MySQL database for
1120 object persistence, then the three ODB components that this
1121 application will use are the ODB compiler, <code>libodb</code>
1122 and <code>libodb-mysql</code>.</p>
1123
1124 <p>The ODB compiler generates the database support code for
1125 persistent classes in your application. The input to the ODB
1126 compiler is one or more C++ header files defining C++ classes
1127 that you want to make persistent. For each input header file
1128 the ODB compiler generates a set of C++ source files implementing
1129 conversion between persistent C++ classes defined in this
1130 header and their database representation. The ODB compiler
1131 can also generate a database schema file that creates tables
1132 necessary to store the persistent classes.</p>
1133
1134 <p>The ODB compiler is a real C++ compiler except that it produces
1135 C++ instead of assembly or machine code. In particular, it is not
1136 an ad-hoc header pre-processor that is only capable of recognizing
1137 a subset of C++. ODB is capable of parsing any standard C++ code.</p>
1138
1139 <p>The common runtime library defines database system-independent
1140 interfaces that your application can use to manipulate persistent
1141 objects. The database-specific runtime library provides implementations
1142 of these interfaces for a concrete database as well as other
1143 database-specific utilities that are used by the generated code.
1144 Normally, the application does not use the database-specific
1145 runtime library directly but rather works with it via the common
1146 interfaces from <code>libodb</code>. The following diagram shows
1147 the object persistence architecture of an application that uses
1148 MySQL as the underlying database system:</p>
1149
1150 <!-- align=center is needed for html2ps -->
1151 <div class="img" align="center"><img src="odb-arch.png"/></div>
1152
1153 <p>The ODB system also defines two special-purpose languages:
1154 the ODB Pragma Language and ODB Query Language. The ODB Pragma
1155 Language is used to communicate various properties of persistent
1156 classes to the ODB compiler by means of special <code>#pragma</code>
1157 directives embedded in the C++ header files. It controls aspects
1158 of the object-relational mapping such as names of tables and columns
1159 that are used for persistent classes and their members or mapping between
1160 C++ types and database types.</p>
1161
1162 <p>The ODB Query Language is an object-oriented database query
1163 language that can be used to search for objects matching
1164 certain criteria. It is modeled after and is integrated into
1165 C++ allowing you to write expressive and safe queries that look
1166 and feel like ordinary C++.</p>
1167
1168 <p>The use of the ODB compiler to generate database support code
1169 adds an additional step to your application build sequence. The
1170 following diagram outlines the typical build workflow of an
1171 application that uses ODB:</p>
1172
1173 <!-- align=center is needed for html2ps -->
1174 <div class="img" align="center"><img src="odb-flow.png"/></div>
1175
1176 <h2><a name="1.2">1.2 Benefits</a></h2>
1177
1178 <p>The traditional way of saving C++ objects to relational databases
1179 requires that you manually write code which converts between the database
1180 and C++ representations of each persistent class. The actions that
1181 such code usually performs include conversion between C++ values and
1182 strings or database types, preparation and execution of SQL queries,
1183 as well as handling the result sets. Writing this code manually has
1184 the following drawbacks:</p>
1185
1186 <ul class="list">
1187 <li><b>Difficult and time consuming.</b> Writing database conversion
1188 code for any non-trivial application requires extensive
1189 knowledge of the specific database system and its APIs.
1190 It can also take a considerable amount of time to write
1191 and maintain. Supporting multi-threaded applications can
1192 complicate this task even further.</li>
1193
1194 <li><b>Suboptimal performance.</b> Optimal conversion often
1195 requires writing large amounts of extra code, such as
1196 parameter binding for prepared statements and caching
1197 of connections, statements, and buffers. Writing code
1198 like this in an ad-hoc manner is often too difficult
1199 and time consuming.</li>
1200
1201 <li><b>Database vendor lock-in.</b> The conversion code is written for
1202 a specific database which makes it hard to switch to another
1203 database vendor.</li>
1204
1205 <li><b>Lack of type safety.</b> It is easy to misspell column names or
1206 pass incompatible values in SQL queries. Such errors will
1207 only be detected at runtime.</li>
1208
1209 <li><b>Complicates the application.</b> The database conversion code
1210 often ends up interspersed throughout the application making it
1211 hard to debug, change, and maintain.</li>
1212 </ul>
1213
1214 <p>In contrast, using ODB for C++ object persistence has the
1215 following benefits:</p>
1216
1217 <ul class="list">
1218 <li><b>Ease of use.</b> ODB automatically generates database conversion
1219 code from your C++ class declarations and allows you to manipulate
1220 persistent objects using simple and thread-safe object-oriented
1221 database APIs.</li>
1222
1223 <li><b>Concise code.</b> With ODB hiding the details of the underlying
1224 database, the application logic is written using the natural object
1225 vocabulary instead of tables, columns and SQL. The resulting code
1226 is simpler and thus easier to read and understand.</li>
1227
1228 <li><b>Optimal performance.</b> ODB has been designed for high performance
1229 and low memory overhead. All the available optimization techniques,
1230 such as prepared statements and extensive connection, statement,
1231 and buffer caching, are used to provide the most efficient
1232 implementation for each database operation.</li>
1233
1234 <li><b>Database portability.</b> Because the database conversion code
1235 is automatically generated, it is easy to switch from one database
1236 vendor to another. In fact, it is possible to test your application
1237 on several database systems before making a choice.</li>
1238
1239 <li><b>Safety.</b> The ODB object persistence and query APIs are
1240 statically typed. You use C++ identifiers instead of strings
1241 to refer to object members and the generated code makes sure
1242 database and C++ types are compatible. All this helps catch
1243 programming errors at compile-time rather than at runtime.</li>
1244
1245 <li><b>Maintainability.</b> Automatic code generation minimizes the
1246 effort needed to adapt the application to changes in persistent
1247 classes. The database support code is kept separately from the
1248 class declarations and application logic. This makes the
1249 application easier to debug and maintain.</li>
1250 </ul>
1251
1252 <p>Overall, ODB provides an easy to use yet flexible and powerful
1253 object-relational mapping (ORM) system for C++. Unlike other
1254 ORM implementations for C++ that still require you to write
1255 database conversion or member registration code for each
1256 persistent class, ODB keeps persistent classes purely
1257 declarative. The functional part, the database conversion
1258 code, is automatically generated by the ODB compiler from
1259 these declarations.</p>
1260
1261 <h2><a name="1.3">1.3 Supported C++ Standards</a></h2>
1262
1263 <p>ODB provides support for ISO/IEC C++ 1998/2003 (C++98/03),
1264 ISO/IEC TR 19768 C++ Library Extensions (C++ TR1), and
1265 ISO/IEC C++ 2011 (C++11). While the majority of the examples in
1266 this manual use C++98/03, support for the new functionality and
1267 library components introduced in TR1 and C++11 are discussed
1268 throughout the document. The <code>c++11</code> example in the
1269 <code>odb-examples</code> package also shows ODB support for
1270 various C++11 features.</p>
1271
1272 <!-- CHAPTER -->
1273
1274
1275 <hr class="page-break"/>
1276 <h1><a name="2">2 Hello World Example</a></h1>
1277
1278 <p>In this chapter we will show how to create a simple C++
1279 application that relies on ODB for object persistence using
1280 the traditional "Hello World" example. In particular, we will
1281 discuss how to declare persistent classes, generate database
1282 support code, as well as compile and run our application. We
1283 will also learn how to make objects persistent, load, update
1284 and delete persistent objects, as well as query the database
1285 for persistent objects that match certain criteria. The example
1286 also shows how to define and use views, a mechanism that allows
1287 us to create projections of persistent objects, database tables,
1288 or to handle results of native SQL queries or stored procedure
1289 calls.</p>
1290
1291 <p>The code presented in this chapter is based on the
1292 <code>hello</code> example which can be found in the
1293 <code>odb-examples</code> package of the ODB distribution.</p>
1294
1295 <h2><a name="2.1">2.1 Declaring Persistent Classes</a></h2>
1296
1297 <p>In our "Hello World" example we will depart slightly from
1298 the norm and say hello to people instead of the world. People
1299 in our application will be represented as objects of C++ class
1300 <code>person</code> which is saved in <code>person.hxx</code>:</p>
1301
1302 <pre class="cxx">
1303 // person.hxx
1304 //
1305
1306 #include &lt;string>
1307
1308 class person
1309 {
1310 public:
1311 person (const std::string&amp; first,
1312 const std::string&amp; last,
1313 unsigned short age);
1314
1315 const std::string&amp; first () const;
1316 const std::string&amp; last () const;
1317
1318 unsigned short age () const;
1319 void age (unsigned short);
1320
1321 private:
1322 std::string first_;
1323 std::string last_;
1324 unsigned short age_;
1325 };
1326 </pre>
1327
1328 <p>In order not to miss anyone whom we need to greet, we would like
1329 to save the <code>person</code> objects in a database. To achieve this
1330 we declare the <code>person</code> class as persistent:</p>
1331
1332 <pre class="cxx">
1333 // person.hxx
1334 //
1335
1336 #include &lt;string>
1337
1338 #include &lt;odb/core.hxx> // (1)
1339
1340 #pragma db object // (2)
1341 class person
1342 {
1343 ...
1344
1345 private:
1346 person () {} // (3)
1347
1348 friend class odb::access; // (4)
1349
1350 #pragma db id auto // (5)
1351 unsigned long id_; // (5)
1352
1353 std::string first_;
1354 std::string last_;
1355 unsigned short age_;
1356 };
1357 </pre>
1358
1359 <p>To be able to save the <code>person</code> objects in the database
1360 we had to make five changes, marked with (1) to (5), to the original
1361 class definition. The first change is the inclusion of the ODB
1362 header <code>&lt;odb/core.hxx></code>. This header provides a number
1363 of core ODB declarations, such as <code>odb::access</code>, that
1364 are used to define persistent classes.</p>
1365
1366 <p>The second change is the addition of <code>db&nbsp;object</code>
1367 pragma just before the class definition. This pragma tells the
1368 ODB compiler that the class that follows is persistent. Note
1369 that making a class persistent does not mean that all objects
1370 of this class will automatically be stored in the database.
1371 You would still create ordinary or <em>transient</em> instances
1372 of this class just as you would before. The difference is that
1373 now you can make such transient instances persistent, as we will
1374 see shortly.</p>
1375
1376 <p>The third change is the addition of the default constructor.
1377 The ODB-generated database support code will use this constructor
1378 when instantiating an object from the persistent state. Just as we have
1379 done for the <code>person</code> class, you can make the default
1380 constructor private or protected if you don't want to make it
1381 available to the users of your class. Note also that with some
1382 limitations it is possible to have a persistent class without
1383 the default constructor.</p>
1384
1385 <p>With the fourth change we make the <code>odb::access</code> class a
1386 friend of our <code>person</code> class. This is necessary to make
1387 the default constructor and the data members accessible to the
1388 database support code. If your class has a public default constructor and
1389 either public data members or public accessors and modifiers for the
1390 data members, then the <code>friend</code> declaration is unnecessary.</p>
1391
1392 <p>The final change adds a data member called <code>id_</code> which
1393 is preceded by another pragma. In ODB every persistent object normally
1394 has a unique, within its class, identifier. Or, in other words, no two
1395 persistent instances of the same type have equal identifiers. While it
1396 is possible to define a persistent class without an object id, the number
1397 of database operations that can be performed on such a class is limited.
1398 For our class we use an integer id. The <code>db&nbsp;id auto</code>
1399 pragma that precedes the <code>id_</code> member tells the ODB compiler
1400 that the following member is the object's identifier. The
1401 <code>auto</code> specifier indicates that it is a database-assigned
1402 id. A unique id will be automatically generated by the database and
1403 assigned to the object when it is made persistent.</p>
1404
1405 <p>In this example we chose to add an identifier because none of
1406 the existing members could serve the same purpose. However, if
1407 a class already has a member with suitable properties, then it
1408 is natural to use that member as an identifier. For example,
1409 if our <code>person</code> class contained some form of personal
1410 identification (SSN in the United States or ID/passport number
1411 in other countries), then we could use that as an id. Or, if
1412 we stored an email associated with each person, then we could
1413 have used that if each person is presumed to have a unique
1414 email address.</p>
1415
1416 <p>As another example, consider the following alternative version
1417 of the <code>person</code> class. Here we use one of
1418 the existing data members as id. Also the data members are kept
1419 private and are instead accessed via public accessor and modifier
1420 functions. Finally, the ODB pragmas are grouped together and are
1421 placed after the class definition. They could have also been moved
1422 into a separate header leaving the original class completely
1423 unchanged (for more information on such a non-intrusive conversion
1424 refer to <a href="#14">Chapter 14, "ODB Pragma Language"</a>).</p>
1425
1426 <pre class="cxx">
1427 class person
1428 {
1429 public:
1430 person ();
1431
1432 const std::string&amp; email () const;
1433 void email (const std::string&amp;);
1434
1435 const std::string&amp; get_name () const;
1436 std::string&amp; set_name ();
1437
1438 unsigned short getAge () const;
1439 void setAge (unsigned short);
1440
1441 private:
1442 std::string email_;
1443 std::string name_;
1444 unsigned short age_;
1445 };
1446
1447 #pragma db object(person)
1448 #pragma db member(person::email_) id
1449 </pre>
1450
1451 <p>Now that we have the header file with the persistent class, let's
1452 see how we can generate that database support code.</p>
1453
1454 <h2><a name="2.2">2.2 Generating Database Support Code</a></h2>
1455
1456 <p>The persistent class definition that we created in the previous
1457 section was particularly light on any code that could actually
1458 do the job and store the person's data to a database. There
1459 was no serialization or deserialization code, not even data member
1460 registration, that you would normally have to write by hand in
1461 other ORM libraries for C++. This is because in ODB code
1462 that translates between the database and C++ representations
1463 of an object is automatically generated by the ODB compiler.</p>
1464
1465 <p>To compile the <code>person.hxx</code> header we created in the
1466 previous section and generate the support code for the MySQL
1467 database, we invoke the ODB compiler from a terminal (UNIX) or
1468 a command prompt (Windows):</p>
1469
1470 <pre class="terminal">
1471 odb -d mysql --generate-query person.hxx
1472 </pre>
1473
1474 <p>We will use MySQL as the database of choice in the remainder of
1475 this chapter, though other supported database systems can be used
1476 instead.</p>
1477
1478 <p>If you haven't installed the common ODB runtime library
1479 (<code>libodb</code>) or installed it into a directory where
1480 C++ compilers don't search for headers by default,
1481 then you may get the following error:</p>
1482
1483 <pre class="terminal">
1484 person.hxx:10:24: fatal error: odb/core.hxx: No such file or directory
1485 </pre>
1486
1487 <p>To resolve this you will need to specify the <code>libodb</code> headers
1488 location with the <code>-I</code> preprocessor option, for example:</p>
1489
1490 <pre class="terminal">
1491 odb -I.../libodb -d mysql --generate-query person.hxx
1492 </pre>
1493
1494 <p>Here <code>.../libodb</code> represents the path to the
1495 <code>libodb</code> directory.</p>
1496
1497 <p>The above invocation of the ODB compiler produces three C++ files:
1498 <code>person-odb.hxx</code>, <code>person-odb.ixx</code>,
1499 <code>person-odb.cxx</code>. You normally don't use types
1500 or functions contained in these files directly. Rather, all
1501 you have to do is include <code>person-odb.hxx</code> in
1502 C++ files where you are performing database operations
1503 with classes from <code>person.hxx</code> as well as compile
1504 <code>person-odb.cxx</code> and link the resulting object
1505 file to your application.</p>
1506
1507 <p>You may be wondering what the <code>--generate-query</code>
1508 option is for. It instructs the ODB compiler to generate
1509 optional query support code that we will use later in our
1510 "Hello World" example. Another option that we will find
1511 useful is <code>--generate-schema</code>. This option
1512 makes the ODB compiler generate a fourth file,
1513 <code>person.sql</code>, which is the database schema
1514 for the persistent classes defined in <code>person.hxx</code>:</p>
1515
1516 <pre class="terminal">
1517 odb -d mysql --generate-query --generate-schema person.hxx
1518 </pre>
1519
1520 <p>The database schema file contains SQL statements that creates
1521 tables necessary to store the persistent classes. We will learn
1522 how to use it in the next section.</p>
1523
1524 <p>If you would like to see a list of all the available ODB compiler
1525 options, refer to the
1526 <a href="http://www.codesynthesis.com/products/odb/doc/odb.xhtml">ODB
1527 Compiler Command Line Manual</a>.</p>
1528
1529 <p>Now that we have the persistent class and the database support
1530 code, the only part that is left is the application code that
1531 does something useful with all of this. But before we move on to
1532 the fun part, let's first learn how to build and run an application
1533 that uses ODB. This way when we have some application code
1534 to try, there are no more delays before we can run it.</p>
1535
1536 <h2><a name="2.3">2.3 Compiling and Running</a></h2>
1537
1538 <p>Assuming that the <code>main()</code> function with the application
1539 code is saved in <code>driver.cxx</code> and the database support
1540 code and schema are generated as described in the previous section,
1541 to build our application we will first need to compile all the C++
1542 source files and then link them with two ODB runtime libraries.</p>
1543
1544 <p>On UNIX, the compilation part can be done with the following commands
1545 (substitute <code>c++</code> with your C++ compiler name; for Microsoft
1546 Visual Studio setup, see the <code>odb-examples</code> package):</p>
1547
1548 <pre class="terminal">
1549 c++ -c driver.cxx
1550 c++ -c person-odb.cxx
1551 </pre>
1552
1553 <p>Similar to the ODB compilation, if you get an error stating that
1554 a header in <code>odb/</code> or <code>odb/mysql</code> directory
1555 is not found, you will need to use the <code>-I</code>
1556 preprocessor option to specify the location of the common ODB runtime
1557 library (<code>libodb</code>) and MySQL ODB runtime library
1558 (<code>libodb-mysql</code>).</p>
1559
1560 <p>Once the compilation is done, we can link the application with
1561 the following command:</p>
1562
1563 <pre class="terminal">
1564 c++ -o driver driver.o person-odb.o -lodb-mysql -lodb
1565 </pre>
1566
1567 <p>Notice that we link our application with two ODB libraries:
1568 <code>libodb</code> which is a common runtime library and
1569 <code>libodb-mysql</code> which is a MySQL runtime library
1570 (if you use another database, then the name of this library
1571 will change accordingly). If you get an error saying that
1572 one of these libraries could not be found, then you will need
1573 to use the <code>-L</code> linker option to specify their locations.</p>
1574
1575 <p>Before we can run our application we need to create a database
1576 schema using the generated <code>person.sql</code> file. For MySQL
1577 we can use the <code>mysql</code> client program, for example:</p>
1578
1579 <pre class="terminal">
1580 mysql --user=odb_test --database=odb_test &lt; person.sql
1581 </pre>
1582
1583 <p>The above command will log in to a local MySQL server as user
1584 <code>odb_test</code> without a password and use the database
1585 named <code>odb_test</code>. Beware that after executing this
1586 command, all the data stored in the <code>odb_test</code> database
1587 will be deleted.</p>
1588
1589 <p>Note also that using a standalone generated SQL file is not the
1590 only way to create a database schema in ODB. We can also embed
1591 the schema directly into our application or use custom schemas
1592 that were not generated by the ODB compiler. Refer to
1593 <a href="#3.4">Section 3.4, "Database"</a> for details.</p>
1594
1595 <p>Once the database schema is ready, we run our application
1596 using the same login and database name:</p>
1597
1598 <pre class="terminal">
1599 ./driver --user odb_test --database odb_test
1600 </pre>
1601
1602
1603 <h2><a name="2.4">2.4 Making Objects Persistent</a></h2>
1604
1605 <p>Now that we have the infrastructure work out of the way, it
1606 is time to see our first code fragment that interacts with the
1607 database. In this section we will learn how to make <code>person</code>
1608 objects persistent:</p>
1609
1610 <pre class="cxx">
1611 // driver.cxx
1612 //
1613
1614 #include &lt;memory> // std::auto_ptr
1615 #include &lt;iostream>
1616
1617 #include &lt;odb/database.hxx>
1618 #include &lt;odb/transaction.hxx>
1619
1620 #include &lt;odb/mysql/database.hxx>
1621
1622 #include "person.hxx"
1623 #include "person-odb.hxx"
1624
1625 using namespace std;
1626 using namespace odb::core;
1627
1628 int
1629 main (int argc, char* argv[])
1630 {
1631 try
1632 {
1633 auto_ptr&lt;database> db (new odb::mysql::database (argc, argv));
1634
1635 unsigned long john_id, jane_id, joe_id;
1636
1637 // Create a few persistent person objects.
1638 //
1639 {
1640 person john ("John", "Doe", 33);
1641 person jane ("Jane", "Doe", 32);
1642 person joe ("Joe", "Dirt", 30);
1643
1644 transaction t (db->begin ());
1645
1646 // Make objects persistent and save their ids for later use.
1647 //
1648 john_id = db->persist (john);
1649 jane_id = db->persist (jane);
1650 joe_id = db->persist (joe);
1651
1652 t.commit ();
1653 }
1654 }
1655 catch (const odb::exception&amp; e)
1656 {
1657 cerr &lt;&lt; e.what () &lt;&lt; endl;
1658 return 1;
1659 }
1660 }
1661 </pre>
1662
1663 <p>Let's examine this code piece by piece. At the beginning we include
1664 a bunch of headers. After the standard C++ headers we include
1665 <code>&lt;odb/database.hxx></code>
1666 and <code>&lt;odb/transaction.hxx></code> which define database
1667 system-independent <code>odb::database</code> and
1668 <code>odb::transaction</code> interfaces. Then we include
1669 <code>&lt;odb/mysql/database.hxx></code> which defines the
1670 MySQL implementation of the <code>database</code> interface. Finally,
1671 we include <code>person.hxx</code> and <code>person-odb.hxx</code>
1672 which define our persistent <code>person</code> class.</p>
1673
1674 <p>Then we have two <code>using namespace</code> directives. The first
1675 one brings in the names from the standard namespace and the second
1676 brings in the ODB declarations which we will use later in the file.
1677 Notice that in the second directive we use the <code>odb::core</code>
1678 namespace instead of just <code>odb</code>. The former only brings
1679 into the current namespace the essential ODB names, such as the
1680 <code>database</code> and <code>transaction</code> classes, without
1681 any of the auxiliary objects. This minimizes the likelihood of name
1682 conflicts with other libraries. Note also that you should continue
1683 using the <code>odb</code> namespace when qualifying individual names.
1684 For example, you should write <code>odb::database</code>, not
1685 <code>odb::core::database</code>.</p>
1686
1687 <p>Once we are in <code>main()</code>, the first thing we do is create
1688 the MySQL database object. Notice that this is the last line in
1689 <code>driver.cxx</code> that mentions MySQL explicitly; the rest
1690 of the code works through the common interfaces and is database
1691 system-independent. We use the <code>argc</code>/<code>argv</code>
1692 <code>mysql::database</code> constructor which automatically
1693 extract the database parameters, such as login name, password,
1694 database name, etc., from the command line. In your own applications
1695 you may prefer to use other <code>mysql::database</code>
1696 constructors which allow you to pass this information directly
1697 (<a href="#17.2">Section 17.2, "MySQL Database Class"</a>).</p>
1698
1699 <p>Next, we create three <code>person</code> objects. Right now they are
1700 transient objects, which means that if we terminate the application
1701 at this point, they will be gone without any evidence of them ever
1702 existing. The next line starts a database transaction. We discuss
1703 transactions in detail later in this manual. For now, all we need
1704 to know is that all ODB database operations must be performed within
1705 a transaction and that a transaction is an atomic unit of work; all
1706 database operations performed within a transaction either succeed
1707 (committed) together or are automatically undone (rolled back).</p>
1708
1709 <p>Once we are in a transaction, we call the <code>persist()</code>
1710 database function on each of our <code>person</code> objects.
1711 At this point the state of each object is saved in the database.
1712 However, note that this state is not permanent until and unless
1713 the transaction is committed. If, for example, our application
1714 crashes at this point, there will still be no evidence of our
1715 objects ever existing.</p>
1716
1717 <p>In our case, one more thing happens when we call <code>persist()</code>.
1718 Remember that we decided to use database-assigned identifiers for our
1719 <code>person</code> objects. The call to <code>persist()</code> is
1720 where this assignment happens. Once this function returns, the
1721 <code>id_</code> member contains this object's unique identifier.
1722 As a convenience, the <code>persist()</code> function also returns
1723 a copy of the object's identifier that it made persistent. We
1724 save the returned identifier for each object in a local variable.
1725 We will use these identifiers later in the chapter to perform other
1726 database operations on our persistent objects.</p>
1727
1728 <p>After we have persisted our objects, it is time to commit the
1729 transaction and make the changes permanent. Only after the
1730 <code>commit()</code> function returns successfully, are we
1731 guaranteed that the objects are made persistent. Continuing
1732 with the crash example, if our application terminates after
1733 the commit for whatever reason, the objects' state in the
1734 database will remain intact. In fact, as we will discover
1735 shortly, our application can be restarted and load the
1736 original objects from the database. Note also that a
1737 transaction must be committed explicitly with the
1738 <code>commit()</code> call. If the <code>transaction</code>
1739 object leaves scope without the transaction being
1740 explicitly committed or rolled back, it will automatically be
1741 rolled back. This behavior allows you not to worry about
1742 exceptions being thrown within a transaction; if they
1743 cross the transaction boundary, the transaction will
1744 automatically be rolled back and all the changes made
1745 to the database undone.</p>
1746
1747 <p>The final bit of code in our example is the <code>catch</code>
1748 block that handles the database exceptions. We do this by catching
1749 the base ODB exception (<a href="#3.14">Section 3.14, "ODB
1750 Exceptions"</a>) and printing the diagnostics.</p>
1751
1752 <p>Let's now compile (<a href="#2.3">Section 2.3, "Compiling and
1753 Running"</a>) and then run our first ODB application:</p>
1754
1755 <pre class="terminal">
1756 mysql --user=odb_test --database=odb_test &lt; person.sql
1757 ./driver --user odb_test --database odb_test
1758 </pre>
1759
1760 <p>Our first application doesn't print anything except for error
1761 messages so we can't really tell whether it actually stored the
1762 objects' state in the database. While we will make our application
1763 more entertaining shortly, for now we can use the <code>mysql</code>
1764 client to examine the database content. It will also give us a feel
1765 for how the objects are stored:</p>
1766
1767 <pre class="terminal">
1768 mysql --user=odb_test --database=odb_test
1769
1770 Welcome to the MySQL monitor.
1771
1772 mysql> select * from person;
1773
1774 +----+-------+------+-----+
1775 | id | first | last | age |
1776 +----+-------+------+-----+
1777 | 1 | John | Doe | 33 |
1778 | 2 | Jane | Doe | 32 |
1779 | 3 | Joe | Dirt | 30 |
1780 +----+-------+------+-----+
1781 3 rows in set (0.00 sec)
1782
1783 mysql> quit
1784 </pre>
1785
1786 <p>Another way to get more insight into what's going on under the hood,
1787 is to trace the SQL statements executed by ODB as a result of
1788 each database operation. Here is how we can enable tracing just for
1789 the duration of our transaction:</p>
1790
1791 <pre class="cxx">
1792 // Create a few persistent person objects.
1793 //
1794 {
1795 ...
1796
1797 transaction t (db->begin ());
1798
1799 t.tracer (stderr_tracer);
1800
1801 // Make objects persistent and save their ids for later use.
1802 //
1803 john_id = db->persist (john);
1804 jane_id = db->persist (jane);
1805 joe_id = db->persist (joe);
1806
1807 t.commit ();
1808 }
1809 </pre>
1810
1811 <p>With this modification our application now produces the following
1812 output:</p>
1813
1814 <pre class="terminal">
1815 INSERT INTO `person` (`id`,`first`,`last`,`age`) VALUES (?,?,?,?)
1816 INSERT INTO `person` (`id`,`first`,`last`,`age`) VALUES (?,?,?,?)
1817 INSERT INTO `person` (`id`,`first`,`last`,`age`) VALUES (?,?,?,?)
1818 </pre>
1819
1820 <p>Note that we see question marks instead of the actual values
1821 because ODB uses prepared statements and sends the data to the
1822 database in binary form. For more information on tracing, refer
1823 to <a href="#3.13">Section 3.13, "Tracing SQL Statement Execution"</a>.
1824 In the next section we will see how to access persistent objects
1825 from our application.</p>
1826
1827 <h2><a name="2.5">2.5 Querying the Database for Objects</a></h2>
1828
1829 <p>So far our application doesn't resemble a typical "Hello World"
1830 example. It doesn't print anything except for error messages.
1831 Let's change that and teach our application to say hello to
1832 people from our database. To make it a bit more interesting,
1833 let's say hello only to people over 30:</p>
1834
1835 <pre class="cxx">
1836 // driver.cxx
1837 //
1838
1839 ...
1840
1841 int
1842 main (int argc, char* argv[])
1843 {
1844 try
1845 {
1846 ...
1847
1848 // Create a few persistent person objects.
1849 //
1850 {
1851 ...
1852 }
1853
1854 typedef odb::query&lt;person> query;
1855 typedef odb::result&lt;person> result;
1856
1857 // Say hello to those over 30.
1858 //
1859 {
1860 transaction t (db->begin ());
1861
1862 result r (db->query&lt;person> (query::age > 30));
1863
1864 for (result::iterator i (r.begin ()); i != r.end (); ++i)
1865 {
1866 cout &lt;&lt; "Hello, " &lt;&lt; i->first () &lt;&lt; "!" &lt;&lt; endl;
1867 }
1868
1869 t.commit ();
1870 }
1871 }
1872 catch (const odb::exception&amp; e)
1873 {
1874 cerr &lt;&lt; e.what () &lt;&lt; endl;
1875 return 1;
1876 }
1877 }
1878 </pre>
1879
1880 <p>The first half of our application is the same as before and is
1881 replaced with "..." in the above listing for brevity. Again, let's
1882 examine the rest of it piece by piece.</p>
1883
1884 <p>The two <code>typedef</code>s create convenient aliases for two
1885 template instantiations that will be used a lot in our application.
1886 The first is the query type for the <code>person</code> objects
1887 and the second is the result type for that query.</p>
1888
1889 <p>Then we begin a new transaction and call the <code>query()</code>
1890 database function. We pass a query expression
1891 (<code>query::age > 30</code>) which limits the returned objects
1892 only to those with the age greater than 30. We also save the result
1893 of the query in a local variable.</p>
1894
1895 <p>The next few lines perform a standard for-loop iteration
1896 over the result sequence printing hello for every returned person.
1897 Then we commit the transaction and that's it. Let's see what
1898 this application will print:</p>
1899
1900 <pre class="terminal">
1901 mysql --user=odb_test --database=odb_test &lt; person.sql
1902 ./driver --user odb_test --database odb_test
1903
1904 Hello, John!
1905 Hello, Jane!
1906 </pre>
1907
1908
1909 <p>That looks about right, but how do we know that the query actually
1910 used the database instead of just using some in-memory artifacts of
1911 the earlier <code>persist()</code> calls? One way to test this
1912 would be to comment out the first transaction in our application
1913 and re-run it without re-creating the database schema. This way the
1914 objects that were persisted during the previous run will be returned.
1915 Alternatively, we can just re-run the same application without
1916 re-creating the schema and notice that we now show duplicate
1917 objects:</p>
1918
1919 <pre class="terminal">
1920 ./driver --user odb_test --database odb_test
1921
1922 Hello, John!
1923 Hello, Jane!
1924 Hello, John!
1925 Hello, Jane!
1926 </pre>
1927
1928 <p>What happens here is that the previous run of our application
1929 persisted a set of <code>person</code> objects and when we re-run
1930 the application, we persist another set with the same names but
1931 with different ids. When we later run the query, matches from
1932 both sets are returned. We can change the line where we print
1933 the "Hello" string as follows to illustrate this point:</p>
1934
1935 <pre class="cxx">
1936 cout &lt;&lt; "Hello, " &lt;&lt; i->first () &lt;&lt; " (" &lt;&lt; i->id () &lt;&lt; ")!" &lt;&lt; endl;
1937 </pre>
1938
1939 <p>If we now re-run this modified program, again without re-creating
1940 the database schema, we will get the following output:</p>
1941
1942 <pre class="terminal">
1943 ./driver --user odb_test --database odb_test
1944
1945 Hello, John (1)!
1946 Hello, Jane (2)!
1947 Hello, John (4)!
1948 Hello, Jane (5)!
1949 Hello, John (7)!
1950 Hello, Jane (8)!
1951 </pre>
1952
1953 <p>The identifiers 3, 6, and 9 that are missing from the above list belong
1954 to the "Joe Dirt" objects which are not selected by this query.</p>
1955
1956 <h2><a name="2.6">2.6 Updating Persistent Objects</a></h2>
1957
1958 <p>While making objects persistent and then selecting some of them using
1959 queries are two useful operations, most applications will also need
1960 to change the object's state and then make these changes persistent.
1961 Let's illustrate this by updating Joe's age who just had a birthday:</p>
1962
1963 <pre class="cxx">
1964 // driver.cxx
1965 //
1966
1967 ...
1968
1969 int
1970 main (int argc, char* argv[])
1971 {
1972 try
1973 {
1974 ...
1975
1976 unsigned long john_id, jane_id, joe_id;
1977
1978 // Create a few persistent person objects.
1979 //
1980 {
1981 ...
1982
1983 // Save object ids for later use.
1984 //
1985 john_id = john.id ();
1986 jane_id = jane.id ();
1987 joe_id = joe.id ();
1988 }
1989
1990 // Joe Dirt just had a birthday, so update his age.
1991 //
1992 {
1993 transaction t (db->begin ());
1994
1995 auto_ptr&lt;person> joe (db->load&lt;person> (joe_id));
1996 joe->age (joe->age () + 1);
1997 db->update (*joe);
1998
1999 t.commit ();
2000 }
2001
2002 // Say hello to those over 30.
2003 //
2004 {
2005 ...
2006 }
2007 }
2008 catch (const odb::exception&amp; e)
2009 {
2010 cerr &lt;&lt; e.what () &lt;&lt; endl;
2011 return 1;
2012 }
2013 }
2014 </pre>
2015
2016 <p>The beginning and the end of the new transaction are the same as
2017 the previous two. Once within a transaction, we call the
2018 <code>load()</code> database function to instantiate a
2019 <code>person</code> object with Joe's persistent state. We
2020 pass Joe's object identifier that we stored earlier when we
2021 made this object persistent. While here we use
2022 <code>std::auto_ptr</code> to manage the returned object, we
2023 could have also used another smart pointer, for example
2024 <code>std::unique_ptr</code> from C++11 or <code>shared_ptr</code>
2025 from TR1, C++11, or Boost. For more information
2026 on the object lifetime management and the smart pointers that we
2027 can use for that, see <a href="#3.3">Section 3.3, "Object
2028 and View Pointers"</a>.</p>
2029
2030 <p>With the instantiated object in hand we increment the age
2031 and call the <code>update()</code> function to update
2032 the object's state in the database. Once the transaction is
2033 committed, the changes are made permanent.</p>
2034
2035 <p>If we now run this application, we will see Joe in the output
2036 since he is now over 30:</p>
2037
2038 <pre class="terminal">
2039 mysql --user=odb_test --database=odb_test &lt; person.sql
2040 ./driver --user odb_test --database odb_test
2041
2042 Hello, John!
2043 Hello, Jane!
2044 Hello, Joe!
2045 </pre>
2046
2047 <p>What if we didn't have an identifier for Joe? Maybe this object
2048 was made persistent in another run of our application or by another
2049 application altogether. Provided that we only have one Joe Dirt
2050 in the database, we can use the query facility to come up with
2051 an alternative implementation of the above transaction:</p>
2052
2053 <pre class="cxx">
2054 // Joe Dirt just had a birthday, so update his age. An
2055 // alternative implementation without using the object id.
2056 //
2057 {
2058 transaction t (db->begin ());
2059
2060 // Here we know that there can be only one Joe Dirt in our
2061 // database so we use the query_one() shortcut instead of
2062 // manually iterating over the result returned by query().
2063 //
2064 auto_ptr&lt;person> joe (
2065 db->query_one&lt;person> (query::first == "Joe" &amp;&amp;
2066 query::last == "Dirt"));
2067
2068 if (joe.get () != 0)
2069 {
2070 joe->age (joe->age () + 1);
2071 db->update (*joe);
2072 }
2073
2074 t.commit ();
2075 }
2076 </pre>
2077
2078 <h2><a name="2.7">2.7 Defining and Using Views</a></h2>
2079
2080 <p>Suppose that we need to gather some basic statistics about the people
2081 stored in our database. Things like the total head count, as well as
2082 the minimum and maximum ages. One way to do it would be to query
2083 the database for all the <code>person</code> objects and then
2084 calculate this information as we iterate over the query result.
2085 While this approach may work fine for our database with just three
2086 people in it, it would be very inefficient if we had a large
2087 number of objects.</p>
2088
2089 <p>While it may not be conceptually pure from the object-oriented
2090 programming point of view, a relational database can perform
2091 some computations much faster and much more economically than
2092 if we performed the same operations ourselves in the application's
2093 process.</p>
2094
2095 <p>To support such cases ODB provides the notion of views. An ODB view
2096 is a C++ <code>class</code> that embodies a light-weight, read-only
2097 projection of one or more persistent objects or database tables or
2098 the result of a native SQL query execution or stored procedure
2099 call.</p>
2100
2101 <p>Some of the common applications of views include loading a subset of
2102 data members from objects or columns database tables, executing and
2103 handling results of arbitrary SQL queries, including aggregate
2104 queries, as well as joining multiple objects and/or database
2105 tables using object relationships or custom join conditions.</p>
2106
2107 <p>While you can find a much more detailed description of views in
2108 <a href="#10">Chapter 10, "Views"</a>, here is how we can define
2109 the <code>person_stat</code> view that returns the basic statistics
2110 about the <code>person</code> objects:</p>
2111
2112 <pre class="cxx">
2113 #pragma db view object(person)
2114 struct person_stat
2115 {
2116 #pragma db column("count(" + person::id_ + ")")
2117 std::size_t count;
2118
2119 #pragma db column("min(" + person::age_ + ")")
2120 unsigned short min_age;
2121
2122 #pragma db column("max(" + person::age_ + ")")
2123 unsigned short max_age;
2124 };
2125 </pre>
2126
2127 <p>Normally, to get the result of a view we use the same
2128 <code>query()</code> function as when querying the database for
2129 an object. Here, however, we are executing an aggregate query
2130 which always returns exactly one element. Therefore, instead
2131 of getting the result instance and then iterating over it, we
2132 can use the shortcut <code>query_value()</code> function. Here is
2133 how we can load and print our statistics using the view we have
2134 just created:</p>
2135
2136 <pre class="cxx">
2137 // Print some statistics about all the people in our database.
2138 //
2139 {
2140 transaction t (db->begin ());
2141
2142 // The result of this query always has exactly one element.
2143 //
2144 person_stat ps (db->query_value&lt;person_stat> ());
2145
2146 cout &lt;&lt; "count : " &lt;&lt; ps.count &lt;&lt; endl
2147 &lt;&lt; "min age: " &lt;&lt; ps.min_age &lt;&lt; endl
2148 &lt;&lt; "max age: " &lt;&lt; ps.max_age &lt;&lt; endl;
2149
2150 t.commit ();
2151 }
2152 </pre>
2153
2154 <p>If we now add the <code>person_stat</code> view to the
2155 <code>person.hxx</code> header, the above transaction
2156 to <code>driver.cxx</code>, as well as re-compile and
2157 re-run our example, then we will see the following
2158 additional lines in the output:</p>
2159
2160 <pre class="term">
2161 count : 3
2162 min age: 31
2163 max age: 33
2164 </pre>
2165
2166 <h2><a name="2.8">2.8 Deleting Persistent Objects</a></h2>
2167
2168 <p>The last operation that we will discuss in this chapter is deleting
2169 the persistent object from the database. The following code
2170 fragment shows how we can delete an object given its identifier:</p>
2171
2172 <pre class="cxx">
2173 // John Doe is no longer in our database.
2174 //
2175 {
2176 transaction t (db->begin ());
2177 db->erase&lt;person> (john_id);
2178 t.commit ();
2179 }
2180 </pre>
2181
2182 <p>To delete John from the database we start a transaction, call
2183 the <code>erase()</code> database function with John's object
2184 id, and commit the transaction. After the transaction is committed,
2185 the erased object is no longer persistent.</p>
2186
2187 <p>If we don't have an object id handy, we can use queries to find
2188 and delete the object:</p>
2189
2190 <pre class="cxx">
2191 // John Doe is no longer in our database. An alternative
2192 // implementation without using the object id.
2193 //
2194 {
2195 transaction t (db->begin ());
2196
2197 // Here we know that there can be only one John Doe in our
2198 // database so we use the query_one() shortcut again.
2199 //
2200 auto_ptr&lt;person> john (
2201 db->query_one&lt;person> (query::first == "John" &amp;&amp;
2202 query::last == "Doe"));
2203
2204 if (john.get () != 0)
2205 db->erase (*john);
2206
2207 t.commit ();
2208 }
2209 </pre>
2210
2211 <h2><a name="2.9">2.9 Changing Persistent Classes</a></h2>
2212
2213 <p>When the definition of a transient C++ class is changed, for
2214 example by adding or deleting a data member, we don't have to
2215 worry about any existing instances of this class not matching
2216 the new definition. After all, to make the class changes
2217 effective we have to restart the application and none of the
2218 transient instances will survive this.</p>
2219
2220 <p>Things are not as simple for persistent classes. Because they
2221 are stored in the database and therefore survive application
2222 restarts, we have a new problem: what happens to the state of
2223 existing objects (which correspond to the old definition) once
2224 we change our persistent class?</p>
2225
2226 <p>The problem of working with old objects, called <em>database
2227 schema evolution</em>, is a complex issue and ODB provides
2228 comprehensive support for handling it. While this support
2229 is covered in detail in <a href="#13">Chapter 13,
2230 "Database Schema Evolution"</a>, let us consider a simple
2231 example that should give us a sense of the functionality
2232 provided by ODB in this area.</p>
2233
2234 <p>Suppose that after using our <code>person</code> persistent
2235 class for some time and creating a number of databases
2236 containing its instances, we realized that for some people
2237 we also need to store their middle name. If we go ahead and
2238 just add the new data member, everything will work fine
2239 with new databases. Existing databases, however, have a
2240 table that does not correspond to the new class definition.
2241 Specifically, the generated database support code now
2242 expects there to be a column to store the middle name.
2243 But such a column was never created in the old databases.</p>
2244
2245 <p>ODB can automatically generate SQL statements that will
2246 migrate old databases to match the new class definitions.
2247 But first, we need to enable schema evolution support by
2248 defining a version for our object model:</p>
2249
2250 <pre class="cxx">
2251 // person.hxx
2252 //
2253
2254 #pragma db model version(1, 1)
2255
2256 class person
2257 {
2258 ...
2259
2260 std::string first_;
2261 std::string last_;
2262 unsigned short age_;
2263 };
2264 </pre>
2265
2266 <p>The first number in the <code>version</code> pragma is the
2267 base model version. This is the lowest version we will be
2268 able to migrate from. The second number is the current model
2269 version. Since we haven't made any changes yet to our
2270 persistent class, both of these values are <code>1</code>.</p>
2271
2272 <p>Next we need to re-compile our <code>person.hxx</code> header
2273 file with the ODB compiler, just as we did before:</p>
2274
2275 <pre class="terminal">
2276 odb -d mysql --generate-query --generate-schema person.hxx
2277 </pre>
2278
2279 <p>If we now look at the list of files produced by the ODB compiler,
2280 we will notice a new file: <code>person.xml</code>. This
2281 is a changelog file where the ODB compiler keeps track of the
2282 database changes corresponding to our class changes. Note that
2283 this file is automatically maintained by the ODB compiler and
2284 all we have to do is keep it around between re-compilations.</p>
2285
2286 <p>Now we are ready to add the middle name to our <code>person</code>
2287 class. We also give it a default value (empty string) which
2288 is what will be assigned to existing objects in old databases.
2289 Notice that we have also incremented the current version:</p>
2290
2291 <pre class="cxx">
2292 // person.hxx
2293 //
2294
2295 #pragma db model version(1, 2)
2296
2297 class person
2298 {
2299 ...
2300
2301 std::string first_;
2302
2303 #pragma db default("")
2304 std::string middle_;
2305
2306 std::string last_;
2307 unsigned short age_;
2308 };
2309 </pre>
2310
2311 <p>If we now recompile the <code>person.hxx</code> header again, we will
2312 see two extra generated files: <code>person-002-pre.sql</code>
2313 and <code>person-002-post.sql</code>. These two files contain
2314 schema migration statements from version <code>1</code> to
2315 version <code>2</code>. Similar to schema creation, schema
2316 migration statements can also be embedded into the generated
2317 C++ code.</p>
2318
2319 <p><code>person-002-pre.sql</code> and <code>person-002-post.sql</code>
2320 are the pre and post schema migration files. To migrate
2321 one of our old databases, we first execute the pre migration
2322 file:</p>
2323
2324 <pre class="terminal">
2325 mysql --user=odb_test --database=odb_test &lt; person-002-pre.sql
2326 </pre>
2327
2328 <p>Between the pre and post schema migrations we can run data
2329 migration code, if required. At this stage, we can both
2330 access the old and store the new data. In our case we don't
2331 need any data migration code since we assigned the default
2332 value to the middle name for all the existing objects.</p>
2333
2334 <p>To finish the migration process we execute the post migration
2335 statements:</p>
2336
2337 <pre class="terminal">
2338 mysql --user=odb_test --database=odb_test &lt; person-002-post.sql
2339 </pre>
2340
2341 <h2><a name="2.10">2.10 Working with Multiple Databases</a></h2>
2342
2343 <p>Accessing multiple databases (that is, data stores) is simply a
2344 matter of creating multiple <code>odb::&lt;db>::database</code>
2345 instances representing each database. For example:</p>
2346
2347 <pre class="cxx">
2348 odb::mysql::database db1 ("john", "secret", "test_db1");
2349 odb::mysql::database db2 ("john", "secret", "test_db2");
2350 </pre>
2351
2352 <p>Some database systems also allow attaching multiple databases to
2353 the same instance. A more interesting question is how we access
2354 multiple database systems (that is, database implementations) from
2355 the same application. For example, our application may need to store
2356 some objects in a remote MySQL database and others in a local SQLite
2357 file. Or, our application may need to be able to store its objects
2358 in a database system that is selected by the user at runtime.</p>
2359
2360 <p>ODB provides comprehensive multi-database support that ranges from
2361 tight integration with specific database systems to being able to
2362 write database-agnostic code and loading individual database systems
2363 support dynamically. While all these aspects are covered in detail
2364 in <a href="#16">Chapter 16, "Multi-Database Support"</a>, in this
2365 section we will get a taste of this functionality by extending our
2366 "Hello World" example to be able to store its data either in MySQL
2367 or PostgreSQL (other database systems supported by ODB can be added
2368 in a similar manner).</p>
2369
2370 <p>The first step in adding multi-database support is to re-compile
2371 our <code>person.hxx</code> header to generate database support
2372 code for additional database systems:</p>
2373
2374 <pre class="terminal">
2375 odb --multi-database dynamic -d common -d mysql -d pgsql \
2376 --generate-query --generate-schema person.hxx
2377 </pre>
2378
2379 <p>The <code>--multi-database</code> ODB compiler option turns on
2380 multi-database support. For now it is not important what the
2381 <code>dynamic</code> value that we passed to this option means, but
2382 if you are curious, see <a href="#16">Chapter 16</a>. The result of this
2383 command are three sets of generated files: <code>person-odb.?xx</code>
2384 (common interface; corresponds to the <code>common</code> database),
2385 <code>person-odb-mysql.?xx</code> (MySQL support code), and
2386 <code>person-odb-pgsql.?xx</code> (PostgreSQL support code). There
2387 are also two schema files: <code>person-mysql.sql</code> and
2388 <code>person-pgsql.sql</code>.</p>
2389
2390 <p>The only part that we need to change in <code>driver.cxx</code>
2391 is how we create the database instance. Specifically, this line:</p>
2392
2393 <pre class="cxx">
2394 auto_ptr&lt;database> db (new odb::mysql::database (argc, argv));
2395 </pre>
2396
2397 <p>Now our example is capable of storing its data either in MySQL or
2398 PostgreSQL so we need to somehow allow the caller to specify which
2399 database we must use. To keep things simple, we will make the first
2400 command line argument specify the database system we must use while
2401 the rest will contain the database-specific options which we will
2402 pass to the <code>odb::&lt;db>::database</code> constructor as
2403 before. Let's put all this logic into a separate function which we
2404 will call <code>create_database()</code>. Here is what the beginning
2405 of our modified <code>driver.cxx</code> will look like (the remainder
2406 is unchanged):</p>
2407
2408 <pre class="cxx">
2409 // driver.cxx
2410 //
2411
2412 #include &lt;string>
2413 #include &lt;memory> // std::auto_ptr
2414 #include &lt;iostream>
2415
2416 #include &lt;odb/database.hxx>
2417 #include &lt;odb/transaction.hxx>
2418
2419 #include &lt;odb/mysql/database.hxx>
2420 #include &lt;odb/pgsql/database.hxx>
2421
2422 #include "person.hxx"
2423 #include "person-odb.hxx"
2424
2425 using namespace std;
2426 using namespace odb::core;
2427
2428 auto_ptr&lt;database>
2429 create_database (int argc, char* argv[])
2430 {
2431 auto_ptr&lt;database> r;
2432
2433 if (argc &lt; 2)
2434 {
2435 cerr &lt;&lt; "error: database system name expected" &lt;&lt; endl;
2436 return r;
2437 }
2438
2439 string db (argv[1]);
2440
2441 if (db == "mysql")
2442 r.reset (new odb::mysql::database (argc, argv));
2443 else if (db == "pgsql")
2444 r.reset (new odb::pgsql::database (argc, argv));
2445 else
2446 cerr &lt;&lt; "error: unknown database system " &lt;&lt; db &lt;&lt; endl;
2447
2448 return r;
2449 }
2450
2451 int
2452 main (int argc, char* argv[])
2453 {
2454 try
2455 {
2456 auto_ptr&lt;database> db (create_database (argc, argv));
2457
2458 if (db.get () == 0)
2459 return 1; // Diagnostics has already been issued.
2460
2461 ...
2462 </pre>
2463
2464 <p>And that's it. The only thing left is to build and run our
2465 example:</p>
2466
2467 <pre class="terminal">
2468 c++ -c driver.cxx
2469 c++ -c person-odb.cxx
2470 c++ -c person-odb-mysql.cxx
2471 c++ -c person-odb-pgsql.cxx
2472 c++ -o driver driver.o person-odb.o person-odb-mysql.o \
2473 person-odb-pgsql.o -lodb-mysql -lodb-pgsql -lodb
2474 </pre>
2475
2476 <p>Here is how we can access a MySQL database:</p>
2477
2478 <pre class="terminal">
2479 mysql --user=odb_test --database=odb_test &lt; person-mysql.sql
2480 ./driver mysql --user odb_test --database odb_test
2481 </pre>
2482
2483 <p>Or a PostgreSQL database:</p>
2484
2485 <pre class="terminal">
2486 psql --user=odb_test --dbname=odb_test -f person-pgsql.sql
2487 ./driver pgsql --user odb_test --database odb_test
2488 </pre>
2489
2490 <h2><a name="2.11">2.11 Summary</a></h2>
2491
2492 <p>This chapter presented a very simple application which, nevertheless,
2493 exercised all of the core database functions: <code>persist()</code>,
2494 <code>query()</code>, <code>load()</code>, <code>update()</code>,
2495 and <code>erase()</code>. We also saw that writing an application
2496 that uses ODB involves the following steps:</p>
2497
2498 <ol>
2499 <li>Declare persistent classes in header files.</li>
2500 <li>Compile these headers to generate database support code.</li>
2501 <li>Link the application with the generated code and two ODB runtime
2502 libraries.</li>
2503 </ol>
2504
2505 <p>Do not be concerned if, at this point, much appears unclear. The intent
2506 of this chapter is to give you only a general idea of how to persist C++
2507 objects with ODB. We will cover all the details throughout the remainder
2508 of this manual.</p>
2509
2510
2511 <!-- CHAPTER -->
2512
2513
2514 <hr class="page-break"/>
2515 <h1><a name="3">3 Working with Persistent Objects</a></h1>
2516
2517 <p>The previous chapters gave us a high-level overview of ODB and
2518 showed how to use it to store C++ objects in a database. In this
2519 chapter we will examine the ODB object persistence model as
2520 well as the core database APIs in greater detail. We will
2521 start with basic concepts and terminology in <a href="#3.1">Section
2522 3.1</a> and <a href="#3.3">Section 3.3</a> and continue with the
2523 discussion of the <code>odb::database</code> class in
2524 <a href="#3.4">Section 3.4</a>, transactions in
2525 <a href="#3.5">Section 3.5</a>, and connections in
2526 <a href="#3.6">Section 3.6</a>. The remainder of this chapter
2527 deals with the core database operations and concludes with
2528 the discussion of ODB exceptions.</p>
2529
2530 <p>In this chapter we will continue to use and expand the
2531 <code>person</code> persistent class that we have developed in the
2532 previous chapter.</p>
2533
2534 <h2><a name="3.1">3.1 Concepts and Terminology</a></h2>
2535
2536 <p>The term <em>database</em> can refer to three distinct things:
2537 a general notion of a place where an application stores its data,
2538 a software implementation for managing this data (for example
2539 MySQL), and, finally, some database software implementations
2540 may manage several data stores which are usually distinguished
2541 by name. This name is also commonly referred to as a database.</p>
2542
2543 <p>In this manual, when we use the word <em>database</em>, we
2544 refer to the first meaning above, for example,
2545 "The <code>update()</code> function saves the object's state to
2546 the database." The term Database Management System (DBMS) is
2547 often used to refer to the second meaning of the word database.
2548 In this manual we will use the term <em>database system</em>
2549 for short, for example, "Database system-independent
2550 application code." Finally, to distinguish the third meaning
2551 from the other two, we will use the term <em>database name</em>,
2552 for example, "The second option specifies the database name
2553 that the application should use to store its data."</p>
2554
2555 <p>In C++ there is only one notion of a type and an instance
2556 of a type. For example, a fundamental type, such as <code>int</code>,
2557 is, for the most part, treated the same as a user defined class
2558 type. However, when it comes to persistence, we have to place
2559 certain restrictions and requirements on certain C++ types that
2560 can be stored in the database. As a result, we divide persistent
2561 C++ types into two groups: <em>object types</em> and <em>value
2562 types</em>. An instance of an object type is called an <em>object</em>
2563 and an instance of a value type &mdash; a <em>value</em>.</p>
2564
2565 <p>An object is an independent entity. It can be stored, updated,
2566 and deleted in the database independent of other objects.
2567 Normally, an object has an identifier, called <em>object id</em>,
2568 that is unique among all instances of an object type within a
2569 database. In contrast, a value can only be stored in the database
2570 as part of an object and doesn't have its own unique identifier.</p>
2571
2572 <p>An object consists of data members which are either values
2573 (<a href="#7">Chapter 7, "Value Types"</a>), pointers
2574 to other objects (<a href="#6">Chapter 6, "Relationships"</a>), or
2575 containers of values or pointers to other objects (<a href="#5">Chapter
2576 5, "Containers")</a>. Pointers to other objects and containers can
2577 be viewed as special kinds of values since they also can only
2578 be stored in the database as part of an object.</p>
2579
2580 <p>An object type is a C++ class. Because of this one-to-one
2581 relationship, we will use terms <em>object type</em>
2582 and <em>object class</em> interchangeably. In contrast,
2583 a value type can be a fundamental C++ type, such as
2584 <code>int</code> or a class type, such as <code>std::string</code>.
2585 If a value consists of other values, then it is called a
2586 <em>composite value</em> and its type &mdash; a
2587 <em>composite value type</em> (<a href="#7.2">Section 7.2,
2588 "Composite Value Types"</a>). Otherwise, the value is
2589 called <em>simple value</em> and its type &mdash; a
2590 <em>simple value type</em> (<a href="#7.1">Section 7.1,
2591 "Simple Value Types"</a>). Note that the distinction between
2592 simple and composite values is conceptual rather than
2593 representational. For example, <code>std::string</code>
2594 is a simple value type because conceptually string is a
2595 single value even though the representation of the string
2596 class may contain several data members each of which could be
2597 considered a value. In fact, the same value type can be
2598 viewed (and mapped) as both simple and composite by different
2599 applications.</p>
2600
2601 <p>While not strictly necessary in a purely object-oriented application,
2602 practical considerations often require us to only load a
2603 subset of an object's data members or a combination of members
2604 from several objects. We may also need to factor out some
2605 computations to the relational database instead of performing
2606 them in the application's process. To support such requirements
2607 ODB distinguishes a third kind of C++ types, called <em>views</em>
2608 (<a href="#10">Chapter 10, "Views"</a>). An ODB view is a C++
2609 <code>class</code> that embodies a light-weight, read-only
2610 projection of one or more persistent objects or database
2611 tables or the result of a native SQL query execution.</p>
2612
2613 <p>Understanding how all these concepts map to the relational model
2614 will hopefully make these distinctions clearer. In a relational
2615 database an object type is mapped to a table and a value type is
2616 mapped to one or more columns. A simple value type is mapped
2617 to a single column while a composite value type is mapped to
2618 several columns. An object is stored as a row in this
2619 table and a value is stored as one or more cells in this row.
2620 A simple value is stored in a single cell while a composite
2621 value occupies several cells. A view is not a persistent
2622 entity and it is not stored in the database. Rather, it is a
2623 data structure that is used to capture a single row of an SQL
2624 query result.</p>
2625
2626 <p>Going back to the distinction between simple and composite
2627 values, consider a date type which has three integer
2628 members: year, month, and day. In one application it can be
2629 considered a composite value and each member will get its
2630 own column in a relational database. In another application
2631 it can be considered a simple value and stored in a single
2632 column as a number of days from some predefined date.</p>
2633
2634 <p>Until now, we have been using the term <em>persistent class</em>
2635 to refer to object classes. We will continue to do so even though
2636 a value type can also be a class. The reason for this asymmetry
2637 is the subordinate nature of value types when it comes to
2638 database operations. Remember that values are never stored
2639 directly but rather as part of an object that contains them.
2640 As a result, when we say that we want to make a C++ class
2641 persistent or persist an instance of a class in the database,
2642 we invariably refer to an object class rather than a value
2643 class.</p>
2644
2645 <p>Normally, you would use object types to model real-world entities,
2646 things that have their own identity. For example, in the
2647 previous chapter we created a <code>person</code> class to model
2648 a person, which is a real-world entity. Name and age, which we
2649 used as data members in our <code>person</code> class are clearly
2650 values. It is hard to think of age 31 or name "Joe" as having their
2651 own identities.</p>
2652
2653 <p>A good test to determine whether something is an object or
2654 a value, is to consider if other objects might reference
2655 it. A person is clearly an object because it can be referred
2656 to by other objects such as a spouse, an employer, or a
2657 bank. On the other hand, a person's age or name is not
2658 something that other objects would normally refer to.</p>
2659
2660 <p>Also, when an object represents a real entity, it is easy to
2661 choose a suitable object id. For example, for a
2662 person there is an established notion of an identifier
2663 (SSN, student id, passport number, etc). Another alternative
2664 is to use a person's email address as an identifier.</p>
2665
2666 <p>Note, however, that these are only guidelines. There could
2667 be good reasons to make something that would normally be
2668 a value an object. Consider, for example, a database that
2669 stores a vast number of people. Many of the <code>person</code>
2670 objects in this database have the same names and surnames and
2671 the overhead of storing them in every object may negatively
2672 affect the performance. In this case, we could make the first name
2673 and last name each an object and only store pointers to
2674 these objects in the <code>person</code> class.</p>
2675
2676 <p>An instance of a persistent class can be in one of two states:
2677 <em>transient</em> and <em>persistent</em>. A transient
2678 instance only has a representation in the application's
2679 memory and will cease to exist when the application terminates,
2680 unless it is explicitly made persistent. In other words, a
2681 transient instance of a persistent class behaves just like an
2682 instance of any ordinary C++ class. A persistent instance
2683 has a representation in both the application's memory and the
2684 database. A persistent instance will remain even after the
2685 application terminates unless and until it is explicitly
2686 deleted from the database.</p>
2687
2688 <h2><a name="3.2">3.2 Declaring Persistent Objects and Values</a></h2>
2689
2690 <p>To make a C++ class a persistent object class we declare
2691 it as such using the <code>db&nbsp;object</code> pragma, for
2692 example:</p>
2693
2694 <pre class="cxx">
2695 #pragma db object
2696 class person
2697 {
2698 ...
2699 };
2700 </pre>
2701
2702 <p>The other pragma that we often use is <code>db&nbsp;id</code>
2703 which designates one of the data members as an object id, for
2704 example:</p>
2705
2706 <pre class="cxx">
2707 #pragma db object
2708 class person
2709 {
2710 ...
2711
2712 #pragma db id
2713 unsigned long id_;
2714 };
2715 </pre>
2716
2717 <p>The object id can be of a simple or composite (<a href="#7.2.1">Section
2718 7.2.1, "Composite Object Ids"</a>) value type. This type should be
2719 default-constructible, copy-constructible, and copy-assignable. It
2720 is also possible to declare a persistent class without an object id,
2721 however, such a class will have limited functionality
2722 (<a href="#14.1.6">Section 14.1.6, "<code>no_id</code>"</a>).</p>
2723
2724 <p>The above two pragmas are the minimum required to declare a
2725 persistent class with an object id. Other pragmas can be used to
2726 fine-tune the database-related properties of a class and its
2727 members (<a href="#14">Chapter 14, "ODB Pragma Language"</a>).</p>
2728
2729 <p>Normally, a persistent class should define the default constructor. The
2730 generated database support code uses this constructor when
2731 instantiating an object from the persistent state. If we add the
2732 default constructor only for the database support code, then we
2733 can make it private provided we also make the <code>odb::access</code>
2734 class, defined in the <code>&lt;odb/core.hxx></code> header, a
2735 friend of this object class. For example:</p>
2736
2737 <pre class="cxx">
2738 #include &lt;odb/core.hxx>
2739
2740 #pragma db object
2741 class person
2742 {
2743 ...
2744
2745 private:
2746 friend class odb::access;
2747 person () {}
2748 };
2749 </pre>
2750
2751 <p>It is also possible to have an object class without the default
2752 constructor. However, in this case, the database operations will
2753 only be able to load the persistent state into an existing instance
2754 (<a href="#3.9">Section 3.9, "Loading Persistent Objects"</a>,
2755 <a href="#4.4">Section 4.4, "Query Result"</a>).</p>
2756
2757 <p>The ODB compiler also needs access to the non-transient
2758 (<a href="#14.4.11">Section 14.4.11, "<code>transient</code>"</a>)
2759 data members of a persistent class. The ODB compiler can access
2760 such data members directly if they are public. It can also do
2761 so if they are private or protected and the <code>odb::access</code>
2762 class is declared a friend of the object type. For example:</p>
2763
2764 <pre class="cxx">
2765 #include &lt;odb/core.hxx>
2766
2767 #pragma db object
2768 class person
2769 {
2770 ...
2771
2772 private:
2773 friend class odb::access;
2774 person () {}
2775
2776 #pragma db id
2777 unsigned long id_;
2778
2779 std::string name_;
2780 };
2781 </pre>
2782
2783 <p>If data members are not accessible directly, then the ODB
2784 compiler will try to automatically find suitable accessor and
2785 modifier functions. To accomplish this, the ODB compiler will
2786 try to lookup common accessor and modifier names derived from
2787 the data member name. Specifically, for the <code>name_</code>
2788 data member in the above example, the ODB compiler will look
2789 for accessor functions with names: <code>get_name()</code>,
2790 <code>getName()</code>, <code>getname()</code>, and just
2791 <code>name()</code> as well as for modifier functions with
2792 names: <code>set_name()</code>, <code>setName()</code>,
2793 <code>setname()</code>, and just <code>name()</code>. You can
2794 also add support for custom name derivations with the
2795 <code>--accessor-regex</code> and <code>--modifier-regex</code>
2796 ODB compiler options. Refer to the
2797 <a href="http://www.codesynthesis.com/products/odb/doc/odb.xhtml">ODB
2798 Compiler Command Line Manual</a> for details on these options.
2799 The following example illustrates automatic accessor and modifier
2800 discovery:</p>
2801
2802 <pre class="cxx">
2803 #pragma db object
2804 class person
2805 {
2806 public:
2807 person () {}
2808
2809 ...
2810
2811 unsigned long id () const;
2812 void id (unsigned long);
2813
2814 const std::string&amp; get_name () const;
2815 std::string&amp; set_name ();
2816
2817 private:
2818 #pragma db id
2819 unsigned long id_; // Uses id() for access.
2820
2821 std::string name_; // Uses get_name()/set_name() for access.
2822 };
2823 </pre>
2824
2825 <p>Finally, if a data member is not directly accessible and the
2826 ODB compiler was unable to discover suitable accessor and
2827 modifier functions, then we can provide custom accessor
2828 and modifier expressions using the <code>db&nbsp;get</code>
2829 and <code>db&nbsp;set</code> pragmas. For more information
2830 on custom accessor and modifier expressions refer to
2831 <a href="#14.4.5">Section 14.4.5,
2832 "<code>get</code>/<code>set</code>/<code>access</code>"</a>.</p>
2833
2834 <p>Data members of a persistent class can also be split into
2835 separately-loaded and/or separately-updated sections.
2836 For more information on this functionality, refer to
2837 <a href="#9">Chapter 9, "Sections"</a>.</p>
2838
2839 <p>You may be wondering whether we also have to declare value types
2840 as persistent. We don't need to do anything special for simple value
2841 types such as <code>int</code> or <code>std::string</code> since the
2842 ODB compiler knows how to map them to suitable database types and
2843 how to convert between the two. On the other hand, if a simple value
2844 is unknown to the ODB compiler then we will need to provide the
2845 mapping to the database type and, possibly, the code to
2846 convert between the two. For more information on how to achieve
2847 this refer to the <code>db&nbsp;type</code> pragma description
2848 in <a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>.</p>
2849
2850 <p>Similar to object classes, composite value types have to be
2851 explicitly declared as persistent using the <code>db&nbsp;value</code>
2852 pragma, for example:</p>
2853
2854 <pre class="cxx">
2855 #pragma db value
2856 class name
2857 {
2858 ...
2859
2860 std::string first_;
2861 std::string last_;
2862 };
2863 </pre>
2864
2865 <p>Note that a composite value cannot have a data member designated
2866 as an object id since, as we have discussed earlier, values do
2867 not have a notion of identity. A composite value type also doesn't
2868 have to define the default constructor, unless it is used as an
2869 element of a container. The ODB compiler uses the same mechanisms
2870 to access data members in composite value types as in object types.
2871 Composite value types are discussed in more detail in
2872 <a href="#7.2">Section 7.2, "Composite Value Types"</a>.</p>
2873
2874 <h2><a name="3.3">3.3 Object and View Pointers</a></h2>
2875
2876 <p>As we have seen in the previous chapter, some database operations
2877 create dynamically allocated instances of persistent classes and
2878 return pointers to these instances. As we will see in later chapters,
2879 pointers are also used to establish relationships between objects
2880 (<a href="#6">Chapter 6, "Relationships"</a>) as well as to cache
2881 persistent objects in a session (<a href="#11">Chapter 11,
2882 "Session"</a>). While in most cases you won't need to deal with
2883 pointers to views, it is possible to a obtain a dynamically allocated
2884 instance of a view using the <code>result_iterator::load()</code>
2885 function (<a href="#4.4">Section 4.4, "Query Results"</a>).</p>
2886
2887 <p>By default, all these mechanisms use raw pointers to return
2888 objects and views as well as to pass and cache objects. This
2889 is normally sufficient for applications
2890 that have simple object lifetime requirements and do not use sessions
2891 or object relationships. In particular, a dynamically allocated object
2892 or view that is returned as a raw pointer from a database operation
2893 can be assigned to a smart pointer of our choice, for example
2894 <code>std::auto_ptr</code>, <code>std::unique_ptr</code> from C++11, or
2895 <code>shared_ptr</code> from TR1, C++11, or Boost.</p>
2896
2897 <p>However, to avoid any possibility of a mistake, such as forgetting
2898 to use a smart pointer for a returned object or view, as well as to
2899 simplify the use of more advanced ODB functionality, such as sessions
2900 and bidirectional object relationships, it is recommended that you use
2901 smart pointers with the sharing semantics as object pointers.
2902 The <code>shared_ptr</code> smart pointer from TR1, C++11, or Boost
2903 is a good default choice. However, if sharing is not required and
2904 sessions are not used, then <code>std::unique_ptr</code> or
2905 <code>std::auto_ptr</code> can be used just as well.</p>
2906
2907 <p>ODB provides several mechanisms for changing the object or view pointer
2908 type. To specify the pointer type on the per object or per view basis
2909 we can use the <code>db&nbsp;pointer</code> pragma, for example:</p>
2910
2911 <pre class="cxx">
2912 #pragma db object pointer(std::tr1::shared_ptr)
2913 class person
2914 {
2915 ...
2916 };
2917 </pre>
2918
2919 <p>We can also specify the default pointer for a group of objects or
2920 views at the namespace level:</p>
2921
2922 <pre class="cxx">
2923 #pragma db namespace pointer(std::tr1::shared_ptr)
2924 namespace accounting
2925 {
2926 #pragma db object
2927 class employee
2928 {
2929 ...
2930 };
2931
2932 #pragma db object
2933 class employer
2934 {
2935 ...
2936 };
2937 }
2938 </pre>
2939
2940 <p>Finally, we can use the <code>--default-pointer</code> option to specify
2941 the default pointer for the whole file. Refer to the
2942 <a href="http://www.codesynthesis.com/products/odb/doc/odb.xhtml">ODB
2943 Compiler Command Line Manual</a> for details on this option's argument.
2944 The typical usage is shown below:</p>
2945
2946 <pre class="terminal">
2947 --default-pointer std::tr1::shared_ptr
2948 </pre>
2949
2950 <p>An alternative to this method with the same effect is to specify the
2951 default pointer for the global namespace:</p>
2952
2953 <pre class="terminal">
2954 #pragma db namespace() pointer(std::tr1::shared_ptr)
2955 </pre>
2956
2957 <p>Note that we can always override the default pointer specified
2958 at the namespace level or with the command line option using
2959 the <code>db&nbsp;pointer</code> object or view pragma. For
2960 example:</p>
2961
2962 <pre class="cxx">
2963 #pragma db object pointer(std::shared_ptr)
2964 namespace accounting
2965 {
2966 #pragma db object
2967 class employee
2968 {
2969 ...
2970 };
2971
2972 #pragma db object pointer(std::unique_ptr)
2973 class employer
2974 {
2975 ...
2976 };
2977 }
2978 </pre>
2979
2980 <p>Refer to <a href="#14.1.2">Section 14.1.2, "<code>pointer</code>
2981 (object)"</a>, <a href="#14.2.4">Section 14.2.4, "<code>pointer</code>
2982 (view)"</a>, and <a href="#14.5.1">Section 14.5.1, "<code>pointer</code>
2983 (namespace)"</a> for more information on these mechanisms.</p>
2984
2985 <p>Built-in support that is provided by the ODB runtime library allows us
2986 to use <code>shared_ptr</code> (TR1 or C++11),
2987 <code>std::unique_ptr</code> (C++11), or <code>std::auto_ptr</code> as
2988 pointer types. Plus, ODB profile libraries, that are available for
2989 commonly used frameworks and libraries (such as Boost and Qt),
2990 provide support for smart pointers found in these frameworks and
2991 libraries (<a href="#III">Part III, "Profiles"</a>). It is also
2992 easy to add support for our own smart pointers, as described in
2993 <a href="#6.5"> Section 6.5, "Using Custom Smart Pointers"</a>.</p>
2994
2995 <h2><a name="3.4">3.4 Database</a></h2>
2996
2997 <p>Before an application can make use of persistence services
2998 offered by ODB, it has to create a database class instance. A
2999 database instance is the representation of the place where
3000 the application stores its persistent objects. We create
3001 a database instance by instantiating one of the database
3002 system-specific classes. For example, <code>odb::mysql::database</code>
3003 would be such a class for the MySQL database system. We will
3004 also normally pass a database name as an argument to the
3005 class' constructor. The following code fragment
3006 shows how we can create a database instance for the MySQL
3007 database system:</p>
3008
3009 <pre class="cxx">
3010 #include &lt;odb/database.hxx>
3011 #include &lt;odb/mysql/database.hxx>
3012
3013 auto_ptr&lt;odb::database> db (
3014 new odb::mysql::database (
3015 "test_user" // database login name
3016 "test_password" // database password
3017 "test_database" // database name
3018 ));
3019 </pre>
3020
3021 <p>The <code>odb::database</code> class is a common interface for
3022 all the database system-specific classes provided by ODB. You
3023 would normally work with the database
3024 instance via this interface unless there is a specific
3025 functionality that your application depends on and which is
3026 only exposed by a particular system's <code>database</code>
3027 class. You will need to include the <code>&lt;odb/database.hxx></code>
3028 header file to make this class available in your application.</p>
3029
3030 <p>The <code>odb::database</code> interface defines functions for
3031 starting transactions and manipulating persistent objects.
3032 These are discussed in detail in the remainder of this chapter
3033 as well as the next chapter which is dedicated to the topic of
3034 querying the database for persistent objects. For details on the
3035 system-specific <code>database</code> classes, refer to
3036 <a href="#II">Part II, "Database Systems"</a>.</p>
3037
3038 <p>Before we can persist our objects, the corresponding database schema has
3039 to be created in the database. The schema contains table definitions and
3040 other relational database artifacts that are used to store the state of
3041 persistent objects in the database.</p>
3042
3043 <p>There are several ways to create the database schema. The easiest is to
3044 instruct the ODB compiler to generate the corresponding schema from the
3045 persistent classes (<code>--generate-schema</code> option). The ODB
3046 compiler can generate the schema as a standalone SQL file,
3047 embedded into the generated C++ code, or as a separate C++ source file
3048 (<code>--schema-format</code> option). If we are using the SQL file
3049 to create the database schema, then this file should be executed,
3050 normally only once, before the application is started.</p>
3051
3052 <p>Alternatively, if the schema is embedded directly into the generated
3053 code or produced as a separate C++ source file, then we can use the
3054 <code>odb::schema_catalog</code> class to create it in the database
3055 from within our application, for example:</p>
3056
3057 <pre class="cxx">
3058 #include &lt;odb/schema-catalog.hxx>
3059
3060 odb::transaction t (db->begin ());
3061 odb::schema_catalog::create_schema (*db);
3062 t.commit ();
3063 </pre>
3064
3065 <p>Refer to the next section for information on the
3066 <code>odb::transaction</code> class. The complete version of the above
3067 code fragment is available in the <code>schema/embedded</code> example in
3068 the <code>odb-examples</code> package.</p>
3069
3070 <p>The <code>odb::schema_catalog</code> class has the following interface.
3071 You will need to include the <code>&lt;odb/schema-catalog.hxx></code>
3072 header file to make this class available in your application.</p>
3073
3074 <pre class="cxx">
3075 namespace odb
3076 {
3077 class schema_catalog
3078 {
3079 public:
3080 static void
3081 create_schema (database&amp;,
3082 const std::string&amp; name = "",
3083 bool drop = true);
3084
3085 static void
3086 drop_schema (database&amp;, const std::string&amp; name = "");
3087
3088 static bool
3089 exists (database_id, const std::string&amp; name = "");
3090
3091 static bool
3092 exists (const database&amp;, const std::string&amp; name = "")
3093 };
3094 }
3095 </pre>
3096
3097 <p>The first argument to the <code>create_schema()</code> function
3098 is the database instance that we would like to create the schema in.
3099 The second argument is the schema name. By default, the ODB
3100 compiler generates all embedded schemas with the default schema
3101 name (empty string). However, if your application needs to
3102 have several separate schemas, you can use the
3103 <code>--schema-name</code> ODB compiler option to assign
3104 custom schema names and then use these names as a second argument
3105 to <code>create_schema()</code>. By default, <code>create_schema()</code>
3106 will also delete all the database objects (tables, indexes, etc.) if
3107 they exist prior to creating the new ones. You can change this
3108 behavior by passing <code>false</code> as the third argument. The
3109 <code>drop_schema()</code> function allows you to delete all the
3110 database objects without creating the new ones.</p>
3111
3112 <p>If the schema is not found, the <code>create_schema()</code> and
3113 <code>drop_schema()</code> functions throw the
3114 <code>odb::unknown_schema</code> exception. You can use the
3115 <code>exists()</code> function to check whether a schema for the
3116 specified database and with the specified name exists in the
3117 catalog. Note also that the <code>create_schema()</code> and
3118 <code>drop_schema()</code> functions should be called within a
3119 transaction.</p>
3120
3121 <p>ODB also provides support for database schema evolution. Similar
3122 to schema creation, schema migration statements can be generated
3123 either as standalone SQL files or embedded into the generated C++
3124 code. For more information on schema evolution support, refer to
3125 <a href="#13">Chapter 13, "Database Schema Evolution"</a>.</p>
3126
3127 <p>Finally, we can also use a custom database schema with ODB. This approach
3128 can work similarly to the standalone SQL file described above except that
3129 the database schema is hand-written or produced by another program. Or we
3130 could execute custom SQL statements that create the schema directly from
3131 our application. To map persistent classes to custom database schemas, ODB
3132 provides a wide range of mapping customization pragmas, such
3133 as <code>db&nbsp;table</code>, <code>db&nbsp;column</code>,
3134 and <code>db&nbsp;type</code> (<a href="#14">Chapter 14, "ODB Pragma
3135 Language"</a>). For sample code that shows how to perform such mapping
3136 for various C++ constructs, refer to the <code>schema/custom</code>
3137 example in the <code>odb-examples</code> package.</p>
3138
3139 <h2><a name="3.5">3.5 Transactions</a></h2>
3140
3141 <p>A transaction is an atomic, consistent, isolated and durable
3142 (ACID) unit of work. Database operations can only be
3143 performed within a transaction and each thread of execution
3144 in an application can have only one active transaction at a
3145 time.</p>
3146
3147 <p>By atomicity we mean that when it comes to making changes to
3148 the database state within a transaction,
3149 either all the changes are applied or none at all. Consider,
3150 for example, a transaction that transfers funds between two
3151 objects representing bank accounts. If the debit function
3152 on the first object succeeds but the credit function on
3153 the second fails, the transaction is rolled back and the
3154 database state of the first object remains unchanged.</p>
3155
3156 <p>By consistency we mean that a transaction must take all the
3157 objects stored in the database from one consistent state
3158 to another. For example, if a bank account object must
3159 reference a person object as its owner and we forget to
3160 set this reference before making the object persistent,
3161 the transaction will be rolled back and the database
3162 will remain unchanged.</p>
3163
3164 <p>By isolation we mean that the changes made to the database
3165 state during a transaction are only visible inside this
3166 transaction until and unless it is committed. Using the
3167 above example with the bank transfer, the results of the
3168 debit operation performed on the first object is not
3169 visible to other transactions until the credit operation
3170 is successfully completed and the transaction is committed.</p>
3171
3172 <p>By durability we mean that once the transaction is committed,
3173 the changes that it made to the database state are permanent
3174 and will survive failures such as an application crash. From
3175 now on the only way to alter this state is to execute and commit
3176 another transaction.</p>
3177
3178 <p>A transaction is started by calling either the
3179 <code>database::begin()</code> or <code>connection::begin()</code>
3180 function. The returned transaction handle is stored in
3181 an instance of the <code>odb::transaction</code> class.
3182 You will need to include the <code>&lt;odb/transaction.hxx></code>
3183 header file to make this class available in your application.
3184 For example:</p>
3185
3186 <pre class="cxx">
3187 #include &lt;odb/transaction.hxx>
3188
3189 transaction t (db.begin ())
3190
3191 // Perform database operations.
3192
3193 t.commit ();
3194 </pre>
3195
3196 <p>The <code>odb::transaction</code> class has the following
3197 interface:</p>
3198
3199 <pre class="cxx">
3200 namespace odb
3201 {
3202 class transaction
3203 {
3204 public:
3205 typedef odb::database database_type;
3206 typedef odb::connection connection_type;
3207
3208 explicit
3209 transaction (transaction_impl*, bool make_current = true);
3210
3211 transaction ();
3212
3213 void
3214 reset (transaction_impl*, bool make_current = true);
3215
3216 void
3217 commit ();
3218
3219 void
3220 rollback ();
3221
3222 database_type&amp;
3223 database ();
3224
3225 connection_type&amp;
3226 connection ();
3227
3228 bool
3229 finilized () const;
3230
3231 public:
3232 static bool
3233 has_current ();
3234
3235 static transaction&amp;
3236 current ();
3237
3238 static void
3239 current (transaction&amp;);
3240
3241 static bool
3242 reset_current ();
3243
3244 // Callback API.
3245 //
3246 public:
3247 ...
3248 };
3249 }
3250 </pre>
3251
3252 <p>The <code>commit()</code> function commits a transaction and
3253 <code>rollback()</code> rolls it back. Unless the transaction
3254 has been <em>finalized</em>, that is, explicitly committed or rolled
3255 back, the destructor of the <code>transaction</code> class will
3256 automatically roll it back when the transaction instance goes
3257 out of scope. If we try to commit or roll back a finalized
3258 transaction, the <code>odb::transaction_already_finalized</code>
3259 exception is thrown.</p>
3260
3261 <p>The <code>database()</code> accessor returns the database this
3262 transaction is working on. Similarly, the <code>connection()</code>
3263 accessor returns the database connection this transaction is on
3264 (<a href="#3.6">Section 3.6, "Connections"</a>).</p>
3265
3266 <p>The static <code>current()</code> accessor returns the
3267 currently active transaction for this thread. If there is no active
3268 transaction, this function throws the <code>odb::not_in_transaction</code>
3269 exception. We can check whether there is a transaction in effect in
3270 this thread using the <code>has_current()</code> static function.</p>
3271
3272 <p>The <code>make_current</code> argument in the <code>transaction</code>
3273 constructor as well as the static <code>current()</code> modifier and
3274 <code>reset_current()</code> function give us additional
3275 control over the nomination of the currently active transaction.
3276 If we pass <code>false</code> as the <code>make_current</code>
3277 argument, then the newly created transaction will not
3278 automatically be made the active transaction for this
3279 thread. Later, we can use the static <code>current()</code> modifier
3280 to set this transaction as the active transaction.
3281 The <code>reset_current()</code> static function clears the
3282 currently active transaction. Together, these mechanisms
3283 allow for more advanced use cases, such as multiplexing
3284 two or more transactions on the same thread. For example:</p>
3285
3286 <pre class="cxx">
3287 transaction t1 (db1.begin ()); // Active transaction.
3288 transaction t2 (db2.begin (), false); // Not active.
3289
3290 // Perform database operations on db1.
3291
3292 transaction::current (t2); // Deactivate t1, activate t2.
3293
3294 // Perform database operations on db2.
3295
3296 transaction::current (t1); // Switch back to t1.
3297
3298 // Perform some more database operations on db1.
3299
3300 t1.commit ();
3301
3302 transaction::current (t2); // Switch to t2.
3303
3304 // Perform some more database operations on db2.
3305
3306 t2.commit ();
3307 </pre>
3308
3309 <p>The <code>reset()</code> modifier allows us to reuse the same
3310 <code>transaction</code> instance to complete several database
3311 transactions. Similar to the destructor, <code>reset()</code>
3312 will roll the current transaction back if it hasn't been finalized.
3313 The default <code>transaction</code> constructor creates a finalized
3314 transaction which can later be initialized using <code>reset()</code>.
3315 The <code>finilized()</code> accessor can be used to check whether the
3316 transaction has been finalized. Here is how we can use this functionality
3317 to commit the current transaction and start a new one every time a
3318 certain number of database operations has been performed:</p>
3319
3320 <pre class="cxx">
3321 transaction t (db.begin ());
3322
3323 for (size_t i (0); i &lt; n; ++i)
3324 {
3325 // Perform a database operation, such as persist an object.
3326
3327 // Commit the current transaction and start a new one after
3328 // every 100 operations.
3329 //
3330 if (i % 100 == 0)
3331 {
3332 t.commit ();
3333 t.reset (db.begin ());
3334 }
3335 }
3336
3337 t.commit ();
3338 </pre>
3339
3340 <p>For more information on the transaction callback support, refer
3341 to <a href="#15.1">Section 15.1, "Transaction Callbacks"</a>.</p>
3342
3343 <p>Note that in the above discussion of atomicity, consistency,
3344 isolation, and durability, all of those guarantees only apply
3345 to the object's state in the database as opposed to the object's
3346 state in the application's memory. It is possible to roll
3347 a transaction back but still have changes from this
3348 transaction in the application's memory. An easy way to
3349 avoid this potential inconsistency is to instantiate
3350 persistent objects only within the transaction scope. Consider,
3351 for example, these two implementations of the same transaction:</p>
3352
3353 <pre class="cxx">
3354 void
3355 update_age (database&amp; db, person&amp; p)
3356 {
3357 transaction t (db.begin ());
3358
3359 p.age (p.age () + 1);
3360 db.update (p);
3361
3362 t.commit ();
3363 }
3364 </pre>
3365
3366 <p>In the above implementation, if the <code>update()</code> call fails
3367 and the transaction is rolled back, the state of the <code>person</code>
3368 object in the database and the state of the same object in the
3369 application's memory will differ. Now consider an
3370 alternative implementation which only instantiates the
3371 <code>person</code> object for the duration of the transaction:</p>
3372
3373 <pre class="cxx">
3374 void
3375 update_age (database&amp; db, unsigned long id)
3376 {
3377 transaction t (db.begin ());
3378
3379 auto_ptr&lt;person> p (db.load&lt;person> (id));
3380 p.age (p.age () + 1);
3381 db.update (p);
3382
3383 t.commit ();
3384 }
3385 </pre>
3386
3387 <p>Of course, it may not always be possible to write the
3388 application in this style. Oftentimes we need to access and
3389 modify the application's state of persistent objects out of
3390 transactions. In this case it may make sense to try to
3391 roll back the changes made to the application state if
3392 the transaction was rolled back and the database state
3393 remains unchanged. One way to do this is to re-load
3394 the object's state from the database, for example:</p>
3395
3396 <pre class="cxx">
3397 void
3398 update_age (database&amp; db, person&amp; p)
3399 {
3400 try
3401 {
3402 transaction t (db.begin ());
3403
3404 p.age (p.age () + 1);
3405 db.update (p);
3406
3407 t.commit ();
3408 }
3409 catch (...)
3410 {
3411 transaction t (db.begin ());
3412 db.load (p.id (), p);
3413 t.commit ();
3414
3415 throw;
3416 }
3417 }
3418 </pre>
3419
3420 <p>See also <a href="#15.1">Section 15.1, "Transaction Callbacks"</a>
3421 for an alternative approach.</p>
3422
3423 <h2><a name="3.6">3.6 Connections</a></h2>
3424
3425 <p>The <code>odb::connection</code> class represents a connection
3426 to the database. Normally, you wouldn't work with connections
3427 directly but rather let the ODB runtime obtain and release
3428 connections as needed. However, certain use cases may require
3429 obtaining a connection manually. For completeness, this section
3430 describes the <code>connection</code> class and discusses some
3431 of its use cases. You may want to skip this section if you are
3432 reading through the manual for the first time.</p>
3433
3434 <p>Similar to <code>odb::database</code>, the <code>odb::connection</code>
3435 class is a common interface for all the database system-specific
3436 classes provided by ODB. For details on the system-specific
3437 <code>connection</code> classes, refer to <a href="#II">Part II,
3438 "Database Systems"</a>.</p>
3439
3440 <p>To make the <code>odb::connection</code> class available in your
3441 application you will need to include the <code>&lt;odb/connection.hxx></code>
3442 header file. The <code>odb::connection</code> class has the
3443 following interface:</p>
3444
3445 <pre class="cxx">
3446 namespace odb
3447 {
3448 class connection
3449 {
3450 public:
3451 typedef odb::database database_type;
3452
3453 transaction
3454 begin () = 0;
3455
3456 unsigned long long
3457 execute (const char* statement);
3458
3459 unsigned long long
3460 execute (const std::string&amp; statement);
3461
3462 unsigned long long
3463 execute (const char* statement, std::size_t length);
3464
3465 database_type&amp;
3466 database ();
3467 };
3468
3469 typedef details::shared_ptr&lt;connection> connection_ptr;
3470 }
3471 </pre>
3472
3473 <p>The <code>begin()</code> function is used to start a transaction
3474 on the connection. The <code>execute()</code> functions allow
3475 us to execute native database statements on the connection.
3476 Their semantics are equivalent to the <code>database::execute()</code>
3477 functions (<a href="#3.12">Section 3.12, "Executing Native SQL
3478 Statements"</a>) except that they can be legally called outside
3479 a transaction. Finally, the <code>database()</code> accessor
3480 returns a reference to the <code>odb::database</code> instance
3481 to which this connection corresponds.</p>
3482
3483 <p>To obtain a connection we call the <code>database::connection()</code>
3484 function. The connection is returned as <code>odb::connection_ptr</code>,
3485 which is an implementation-specific smart pointer with the shared
3486 pointer semantics. This, in particular, means that the connection
3487 pointer can be copied and returned from functions. Once the last
3488 instance of <code>connection_ptr</code> pointing to the same
3489 connection is destroyed, the connection is returned to the
3490 <code>database</code> instance. The following code fragment
3491 shows how we can obtain, use, and release a connection:</p>
3492
3493 <pre class="cxx">
3494 using namespace odb::core;
3495
3496 database&amp; db = ...
3497 connection_ptr c (db.connection ());
3498
3499 // Temporarily disable foreign key constraints.
3500 //
3501 c->execute ("SET FOREIGN_KEY_CHECKS = 0");
3502
3503 // Start a transaction on this connection.
3504 //
3505 transaction t (c->begin ());
3506 ...
3507 t.commit ();
3508
3509 // Restore foreign key constraints.
3510 //
3511 c->execute ("SET FOREIGN_KEY_CHECKS = 1");
3512
3513 // When 'c' goes out of scope, the connection is returned to 'db'.
3514 </pre>
3515
3516 <p>Some of the use cases which may require direct manipulation of
3517 connections include out-of-transaction statement execution,
3518 such as the execution of connection configuration statements,
3519 the implementation of a connection-per-thread policy, and making
3520 sure that a set of transactions is executed on the same
3521 connection.</p>
3522
3523 <h2><a name="3.7">3.7 Error Handling and Recovery</a></h2>
3524
3525 <p>ODB uses C++ exceptions to report database operation errors. Most
3526 ODB exceptions signify <em>hard</em> errors or errors that cannot
3527 be corrected without some intervention from the application.
3528 For example, if we try to load an object with an unknown object
3529 id, the <code>odb::object_not_persistent</code> exception is
3530 thrown. Our application may be able to correct this error, for
3531 instance, by obtaining a valid object id and trying again.
3532 The hard errors and corresponding ODB exceptions that can be
3533 thrown by each database function are described in the remainder
3534 of this chapter with <a href="#3.14">Section 3.14, "ODB Exceptions"</a>
3535 providing a quick reference for all the ODB exceptions.</p>
3536
3537 <p>The second group of ODB exceptions signify <em>soft</em> or
3538 <em>recoverable</em> errors. Such errors are temporary
3539 failures which normally can be corrected by simply re-executing
3540 the transaction. ODB defines three such exceptions:
3541 <code>odb::connection_lost</code>, <code>odb::timeout</code>,
3542 and <code>odb::deadlock</code>. All recoverable ODB exceptions
3543 are derived from the common <code>odb::recoverable</code> base
3544 exception which can be used to handle all the recoverable
3545 conditions with a single <code>catch</code> block.</p>
3546
3547 <p>The <code>odb::connection_lost</code> exception is thrown if
3548 a connection to the database is lost in the middle of
3549 a transaction. In this situation the transaction is aborted but
3550 it can be re-tried without any changes. Similarly, the
3551 <code>odb::timeout</code> exception is thrown if one of the
3552 database operations or the whole transaction has timed out.
3553 Again, in this case the transaction is aborted but can be
3554 re-tried as is.</p>
3555
3556 <p>If two or more transactions access or modify more than one object
3557 and are executed concurrently by different applications or by
3558 different threads within the same application, then it is possible
3559 that these transactions will try to access objects in an incompatible
3560 order and deadlock. The canonical example of a deadlock are
3561 two transactions in which the first has modified <code>object1</code>
3562 and is waiting for the second transaction to commit its changes to
3563 <code>object2</code> so that it can also update <code>object2</code>.
3564 At the same time the second transaction has modified <code>object2</code>
3565 and is waiting for the first transaction to commit its changes to
3566 <code>object1</code> because it also needs to modify <code>object1</code>.
3567 As a result, none of the two transactions can be completed.</p>
3568
3569 <p>The database system detects such situations and automatically
3570 aborts the waiting operation in one of the deadlocked transactions.
3571 In ODB this translates to the <code>odb::deadlock</code>
3572 recoverable exception being thrown from one of the database functions.</p>
3573
3574 <p>The following code fragment shows how to handle the recoverable
3575 exceptions by restarting the affected transaction:</p>
3576
3577 <pre class="cxx">
3578 const unsigned short max_retries = 5;
3579
3580 for (unsigned short retry_count (0); ; retry_count++)
3581 {
3582 try
3583 {
3584 transaction t (db.begin ());
3585
3586 ...
3587
3588 t.commit ();
3589 break;
3590 }
3591 catch (const odb::recoverable&amp; e)
3592 {
3593 if (retry_count > max_retries)
3594 throw retry_limit_exceeded (e.what ());
3595 else
3596 continue;
3597 }
3598 }
3599 </pre>
3600
3601 <h2><a name="3.8">3.8 Making Objects Persistent</a></h2>
3602
3603 <p>A newly created instance of a persistent class is transient.
3604 We use the <code>database::persist()</code> function template
3605 to make a transient instance persistent. This function has four
3606 overloaded versions with the following signatures:</p>
3607
3608 <pre class="cxx">
3609 template &lt;typename T>
3610 typename object_traits&lt;T>::id_type
3611 persist (const T&amp; object);
3612
3613 template &lt;typename T>
3614 typename object_traits&lt;T>::id_type
3615 persist (const object_traits&lt;T>::const_pointer_type&amp; object);
3616
3617 template &lt;typename T>
3618 typename object_traits&lt;T>::id_type
3619 persist (T&amp; object);
3620
3621 template &lt;typename T>
3622 typename object_traits&lt;T>::id_type
3623 persist (const object_traits&lt;T>::pointer_type&amp; object);
3624 </pre>
3625
3626 <p>Here and in the rest of the manual,
3627 <code>object_traits&lt;T>::pointer_type</code> and
3628 <code>object_traits&lt;T>::const_pointer_type</code> denote the
3629 unrestricted and constant object pointer types (<a href="#3.3">Section
3630 3.3, "Object and View Pointers"</a>), respectively.
3631 Similarly, <code>object_traits&lt;T>::id_type</code> denotes the object
3632 id type. The <code>odb::object_traits</code> template is part of the
3633 database support code generated by the ODB compiler.</p>
3634
3635 <p>The first <code>persist()</code> function expects a constant reference
3636 to an instance being persisted. The second function expects a constant
3637 object pointer. Both of these functions can only be used on objects with
3638 application-assigned object ids (<a href="#14.4.2">Section 14.4.2,
3639 "<code>auto</code>"</a>).</p>
3640
3641 <p>The second and third <code>persist()</code> functions are similar to the
3642 first two except that they operate on unrestricted references and object
3643 pointers. If the identifier of the object being persisted is assigned
3644 by the database, these functions update the id member of the passed
3645 instance with the assigned value. All four functions return the object
3646 id of the newly persisted object.</p>
3647
3648 <p>If the database already contains an object of this type with this
3649 identifier, the <code>persist()</code> functions throw the
3650 <code>odb::object_already_persistent</code> exception. This should
3651 never happen for database-assigned object ids as long as the
3652 number of objects persisted does not exceed the value space of
3653 the id type.</p>
3654
3655 <p>When calling the <code>persist()</code> functions, we don't need to
3656 explicitly specify the template type since it will be automatically
3657 deduced from the argument being passed. The following example shows
3658 how we can call these functions:</p>
3659
3660 <pre class="cxx">
3661 person john ("John", "Doe", 33);
3662 shared_ptr&lt;person> jane (new person ("Jane", "Doe", 32));
3663
3664 transaction t (db.begin ());
3665
3666 db.persist (john);
3667 unsigned long jane_id (db.persist (jane));
3668
3669 t.commit ();
3670
3671 cerr &lt;&lt; "Jane's id: " &lt;&lt; jane_id &lt;&lt; endl;
3672 </pre>
3673
3674 <p>Notice that in the above code fragment we have created instances
3675 that we were planning to make persistent before starting the
3676 transaction. Likewise, we printed Jane's id after we have committed
3677 the transaction. As a general rule, you should avoid performing
3678 operations within the transaction scope that can be performed
3679 before the transaction starts or after it terminates. An active
3680 transaction consumes both your application's resources, such as
3681 a database connection, as well as the database server's
3682 resources, such as object locks. By following the above rule you
3683 make sure these resources are released and made available to other
3684 threads in your application and to other applications as soon as
3685 possible.</p>
3686
3687 <p>Some database systems support persisting multiple objects with a
3688 single underlying statement execution which can result in significantly
3689 improved performance. For such database systems ODB provides
3690 bulk <code>persist()</code> functions. For details, refer to
3691 <a href="#15.3">Section 15.3, "Bulk Database Operations"</a>.</p>
3692
3693 <h2><a name="3.9">3.9 Loading Persistent Objects</a></h2>
3694
3695 <p>Once an object is made persistent, and you know its object id, it
3696 can be loaded by the application using the <code>database::load()</code>
3697 function template. This function has two overloaded versions with
3698 the following signatures:</p>
3699
3700 <pre class="cxx">
3701 template &lt;typename T>
3702 typename object_traits&lt;T>::pointer_type
3703 load (const typename object_traits&lt;T>::id_type&amp; id);
3704
3705 template &lt;typename T>
3706 void
3707 load (const typename object_traits&lt;T>::id_type&amp; id, T&amp; object);
3708 </pre>
3709
3710 <p>Given an object id, the first function allocates a new instance
3711 of the object class in the dynamic memory, loads its state from
3712 the database, and returns the pointer to the new instance. The
3713 second function loads the object's state into an existing instance.
3714 Both functions throw <code>odb::object_not_persistent</code> if
3715 there is no object of this type with this id in the database.</p>
3716
3717 <p>When we call the first <code>load()</code> function, we need to
3718 explicitly specify the object type. We don't need to do this for
3719 the second function because the object type will be automatically
3720 deduced from the second argument, for example:</p>
3721
3722 <pre class="cxx">
3723 transaction t (db.begin ());
3724
3725 auto_ptr&lt;person> jane (db.load&lt;person> (jane_id));
3726
3727 db.load (jane_id, *jane);
3728
3729 t.commit ();
3730 </pre>
3731
3732 <p>In certain situations it may be necessary to reload the state
3733 of an object from the database. While this is easy to achieve
3734 using the second <code>load()</code> function, ODB provides
3735 the <code>database::reload()</code> function template that
3736 has a number of special properties. This function has two
3737 overloaded versions with the following signatures:</p>
3738
3739 <pre class="cxx">
3740 template &lt;typename T>
3741 void
3742 reload (T&amp; object);
3743
3744 template &lt;typename T>
3745 void
3746 reload (const object_traits&lt;T>::pointer_type&amp; object);
3747 </pre>
3748
3749 <p>The first <code>reload()</code> function expects an object
3750 reference, while the second expects an object pointer. Both
3751 functions expect the id member in the passed object to contain
3752 a valid object identifier and, similar to <code>load()</code>,
3753 both will throw <code>odb::object_not_persistent</code> if
3754 there is no object of this type with this id in the database.</p>
3755
3756 <p>The first special property of <code>reload()</code>
3757 compared to the <code>load()</code> function is that it
3758 does not interact with the session's object cache
3759 (<a href="#11.1">Section 11.1, "Object Cache"</a>). That is, if
3760 the object being reloaded is already in the cache, then it will
3761 remain there after <code>reload()</code> returns. Similarly, if the
3762 object is not in the cache, then <code>reload()</code> won't
3763 put it there either.</p>
3764
3765 <p>The second special property of the <code>reload()</code> function
3766 only manifests itself when operating on an object with the optimistic
3767 concurrency model. In this case, if the states of the object
3768 in the application memory and in the database are the same, then
3769 no reloading will occur. For more information on optimistic
3770 concurrency, refer to <a href="#12">Chapter 12, "Optimistic
3771 Concurrency"</a>.</p>
3772
3773 <p>If we don't know for sure whether an object with a given id
3774 is persistent, we can use the <code>find()</code> function
3775 instead of <code>load()</code>, for example:</p>
3776
3777 <pre class="cxx">
3778 template &lt;typename T>
3779 typename object_traits&lt;T>::pointer_type
3780 find (const typename object_traits&lt;T>::id_type&amp; id);
3781
3782 template &lt;typename T>
3783 bool
3784 find (const typename object_traits&lt;T>::id_type&amp; id, T&amp; object);
3785 </pre>
3786
3787 <p>If an object with this id is not found in the database, the first
3788 <code>find()</code> function returns a <code>NULL</code> pointer
3789 while the second function leaves the passed instance unmodified and
3790 returns <code>false</code>.</p>
3791
3792 <p>If we don't know the object id, then we can use queries to
3793 find the object (or objects) matching some criteria
3794 (<a href="#4">Chapter 4, "Querying the Database"</a>). Note,
3795 however, that loading an object's state using its
3796 identifier can be significantly faster than executing a query.</p>
3797
3798
3799 <h2><a name="3.10">3.10 Updating Persistent Objects</a></h2>
3800
3801 <p>If a persistent object has been modified, we can store the updated
3802 state in the database using the <code>database::update()</code>
3803 function template. This function has three overloaded versions with
3804 the following signatures:</p>
3805
3806 <pre class="cxx">
3807 template &lt;typename T>
3808 void
3809 update (const T&amp; object);
3810
3811 template &lt;typename T>
3812 void
3813 update (const object_traits&lt;T>::const_pointer_type&amp; object);
3814
3815 template &lt;typename T>
3816 void
3817 update (const object_traits&lt;T>::pointer_type&amp; object);
3818 </pre>
3819
3820 <p>The first <code>update()</code> function expects an object reference,
3821 while the other two expect object pointers. If the object passed to
3822 one of these functions does not exist in the database,
3823 <code>update()</code> throws the <code>odb::object_not_persistent</code>
3824 exception (but see a note on optimistic concurrency below).</p>
3825
3826 <p>Below is an example of the funds transfer that we talked about
3827 in the earlier section on transactions. It uses the hypothetical
3828 <code>bank_account</code> persistent class:</p>
3829
3830 <pre class="cxx">
3831 void
3832 transfer (database&amp; db,
3833 unsigned long from_acc,
3834 unsigned long to_acc,
3835 unsigned int amount)
3836 {
3837 bank_account from, to;
3838
3839 transaction t (db.begin ());
3840
3841 db.load (from_acc, from);
3842
3843 if (from.balance () &lt; amount)
3844 throw insufficient_funds ();
3845
3846 db.load (to_acc, to);
3847
3848 to.balance (to.balance () + amount);
3849 from.balance (from.balance () - amount);
3850
3851 db.update (to);
3852 db.update (from);
3853
3854 t.commit ();
3855 }
3856 </pre>
3857
3858 <p>The same can be accomplished using dynamically allocated objects
3859 and the <code>update()</code> function with object pointer argument,
3860 for example:</p>
3861
3862 <pre class="cxx">
3863 transaction t (db.begin ());
3864
3865 shared_ptr&lt;bank_account> from (db.load&lt;bank_account> (from_acc));
3866
3867 if (from->balance () &lt; amount)
3868 throw insufficient_funds ();
3869
3870 shared_ptr&lt;bank_account> to (db.load&lt;bank_account> (to_acc));
3871
3872 to->balance (to->balance () + amount);
3873 from->balance (from->balance () - amount);
3874
3875 db.update (to);
3876 db.update (from);
3877
3878 t.commit ();
3879 </pre>
3880
3881 <p>If any of the <code>update()</code> functions are operating on a
3882 persistent class with the optimistic concurrency model, then they will
3883 throw the <code>odb::object_changed</code> exception if the state of the
3884 object in the database has changed since it was last loaded into the
3885 application memory. Furthermore, for such classes, <code>update()</code>
3886 no longer throws the <code>object_not_persistent</code> exception if
3887 there is no such object in the database. Instead, this condition is
3888 treated as a change of object state and <code>object_changed</code>
3889 is thrown instead. For a more detailed discussion of optimistic
3890 concurrency, refer to <a href="#12">Chapter 12, "Optimistic
3891 Concurrency"</a>.</p>
3892
3893 <p>In ODB, persistent classes, composite value types, as well as individual
3894 data members can be declared read-only (see <a href="#14.1.4">Section
3895 14.1.4, "<code>readonly</code> (object)"</a>, <a href="#14.3.6">Section
3896 14.3.6, "<code>readonly</code> (composite value)"</a>, and
3897 <a href="#14.4.12">Section 14.4.12, "<code>readonly</code>
3898 (data member)"</a>).</p>
3899
3900 <p>If an individual data member is declared read-only, then
3901 any changes to this member will be ignored when updating the database
3902 state of an object using any of the above <code>update()</code>
3903 functions. A <code>const</code> data member is automatically treated
3904 as read-only. If a composite value is declared read-only then all its
3905 data members are treated as read-only.</p>
3906
3907 <p>If the whole object is declared read-only then the database state of
3908 this object cannot be changed. Calling any of the above
3909 <code>update()</code> functions for such an object will result in a
3910 compile-time error.</p>
3911
3912 <p>Similar to <code>persist()</code>, for database systems that support
3913 this functionality, ODB provides bulk <code>update()</code> functions.
3914 For details, refer to <a href="#15.3">Section 15.3, "Bulk Database
3915 Operations"</a>.</p>
3916
3917 <h2><a name="3.11">3.11 Deleting Persistent Objects</a></h2>
3918
3919 <p>To delete a persistent object's state from the database we use the
3920 <code>database::erase()</code> or <code>database::erase_query()</code>
3921 function templates. If the application still has an instance of the
3922 erased object, this instance becomes transient. The <code>erase()</code>
3923 function has the following overloaded versions:</p>
3924
3925 <pre class="cxx">
3926 template &lt;typename T>
3927 void
3928 erase (const T&amp; object);
3929
3930 template &lt;typename T>
3931 void
3932 erase (const object_traits&lt;T>::const_pointer_type&amp; object);
3933
3934 template &lt;typename T>
3935 void
3936 erase (const object_traits&lt;T>::pointer_type&amp; object);
3937
3938 template &lt;typename T>
3939 void
3940 erase (const typename object_traits&lt;T>::id_type&amp; id);
3941 </pre>
3942
3943 <p>The first <code>erase()</code> function uses an object itself, in
3944 the form of an object reference, to delete its state from the
3945 database. The next two functions accomplish the same result but using
3946 object pointers. Note that all three functions leave the passed
3947 object unchanged. It simply becomes transient. The last function
3948 uses the object id to identify the object to be deleted. If the
3949 object does not exist in the database, then all four functions
3950 throw the <code>odb::object_not_persistent</code> exception
3951 (but see a note on optimistic concurrency below).</p>
3952
3953 <p>We have to specify the object type when calling the last
3954 <code>erase()</code> function. The same is unnecessary for the
3955 first three functions because the object type will be automatically
3956 deduced from their arguments. The following example shows how we
3957 can call these functions:</p>
3958
3959 <pre class="cxx">
3960 person&amp; john = ...
3961 shared_ptr&lt;jane> jane = ...
3962 unsigned long joe_id = ...
3963
3964 transaction t (db.begin ());
3965
3966 db.erase (john);
3967 db.erase (jane);
3968 db.erase&lt;person> (joe_id);
3969
3970 t.commit ();
3971 </pre>
3972
3973 <p>If any of the <code>erase()</code> functions except the last one are
3974 operating on a persistent class with the optimistic concurrency
3975 model, then they will throw the <code>odb::object_changed</code> exception
3976 if the state of the object in the database has changed since it was
3977 last loaded into the application memory. Furthermore, for such
3978 classes, <code>erase()</code> no longer throws the
3979 <code>object_not_persistent</code> exception if there is no such
3980 object in the database. Instead, this condition is treated as a
3981 change of object state and <code>object_changed</code> is thrown
3982 instead. For a more detailed discussion of optimistic concurrency,
3983 refer to <a href="#12">Chapter 12, "Optimistic Concurrency"</a>.</p>
3984
3985 <p>Similar to <code>persist()</code> and <code>update()</code>, for
3986 database systems that support this functionality, ODB provides
3987 bulk <code>erase()</code> functions. For details, refer to
3988 <a href="#15.3">Section 15.3, "Bulk Database Operations"</a>.</p>
3989
3990 <p>The <code>erase_query()</code> function allows us to delete
3991 the state of multiple objects matching certain criteria. It uses
3992 the query expression of the <code>database::query()</code> function
3993 (<a href="#4">Chapter 4, "Querying the Database"</a>) and,
3994 because the ODB query facility is optional, it is only available
3995 if the <code>--generate-query</code> ODB compiler option was
3996 specified. The <code>erase_query()</code> function has the
3997 following overloaded versions:</p>
3998
3999 <pre class="cxx">
4000 template &lt;typename T>
4001 unsigned long long
4002 erase_query ();
4003
4004 template &lt;typename T>
4005 unsigned long long
4006 erase_query (const odb::query&lt;T>&amp;);
4007 </pre>
4008
4009 <p>The first <code>erase_query()</code> function is used to delete
4010 the state of all the persistent objects of a given type stored
4011 in the database. The second function uses the passed query instance
4012 to only delete the state of objects matching the query criteria.
4013 Both functions return the number of objects erased. When calling
4014 the <code>erase_query()</code> function, we have to explicitly
4015 specify the object type we are erasing. For example:</p>
4016
4017 <pre class="cxx">
4018 typedef odb::query&lt;person> query;
4019
4020 transaction t (db.begin ());
4021
4022 db.erase_query&lt;person> (query::last == "Doe" &amp;&amp; query::age &lt; 30);
4023
4024 t.commit ();
4025 </pre>
4026
4027 <p>Unlike the <code>query()</code> function, when calling
4028 <code>erase_query()</code> we cannot use members from pointed-to
4029 objects in the query expression. However, we can still use
4030 a member corresponding to a pointer as an ordinary object
4031 member that has the id type of the pointed-to object
4032 (<a href="#6">Chapter 6, "Relationships"</a>). This allows us
4033 to compare object ids as well as test the pointer for
4034 <code>NULL</code>. As an example, the following transaction
4035 makes sure that all the <code>employee</code> objects that
4036 reference an <code>employer</code> object that is about to
4037 be deleted are deleted as well. Here we assume that the
4038 <code>employee</code> class contains a pointer to the
4039 <code>employer</code> class. Refer to <a href="#6">Chapter 6,
4040 "Relationships"</a> for complete definitions of these
4041 classes.</p>
4042
4043 <pre class="cxx">
4044 typedef odb::query&lt;employee> query;
4045
4046 transaction t (db.begin ());
4047
4048 employer&amp; e = ... // Employer object to be deleted.
4049
4050 db.erase_query&lt;employee> (query::employer == e.id ());
4051 db.erase (e);
4052
4053 t.commit ();
4054 </pre>
4055
4056
4057 <h2><a name="3.12">3.12 Executing Native SQL Statements</a></h2>
4058
4059 <p>In some situations we may need to execute native SQL statements
4060 instead of using the object-oriented database API described above.
4061 For example, we may want to tune the database schema generated
4062 by the ODB compiler or take advantage of a feature that is
4063 specific to the database system we are using. The
4064 <code>database::execute()</code> function, which has three
4065 overloaded versions, provides this functionality:</p>
4066
4067 <pre class="cxx">
4068 unsigned long long
4069 execute (const char* statement);
4070
4071 unsigned long long
4072 execute (const std::string&amp; statement);
4073
4074 unsigned long long
4075 execute (const char* statement, std::size_t length)
4076 </pre>
4077
4078 <p>The first <code>execute()</code> function expects the SQL statement
4079 as a zero-terminated C-string. The last version expects the explicit
4080 statement length as the second argument and the statement itself
4081 may contain <code>'\0'</code> characters, for example, to represent
4082 binary data, if the database system supports it. All three functions
4083 return the number of rows that were affected by the statement. For
4084 example:</p>
4085
4086 <pre class="cxx">
4087 transaction t (db.begin ());
4088
4089 db.execute ("DROP TABLE test");
4090 db.execute ("CREATE TABLE test (n INT PRIMARY KEY)");
4091
4092 t.commit ();
4093 </pre>
4094
4095 <p>While these functions must always be called within a transaction,
4096 it may be necessary to execute a native statement outside a
4097 transaction. This can be done using the
4098 <code>connection::execute()</code> functions as described in
4099 <a href="#3.6">Section 3.6, "Connections"</a>.</p>
4100
4101 <h2><a name="3.13">3.13 Tracing SQL Statement Execution</a></h2>
4102
4103 <p>Oftentimes it is useful to understand what SQL statements are
4104 executed as a result of high-level database operations. For
4105 example, we can use this information to figure out why certain
4106 transactions don't produce desired results or why they take
4107 longer than expected.</p>
4108
4109 <p>While this information can usually be obtained from the database
4110 logs, ODB provides an application-side SQL statement tracing
4111 support that is both more convenient and finer-grained.
4112 For example, in a typical situation that calls for tracing
4113 we would like to see the SQL statements executed as a result
4114 of a specific transaction. While it may be difficult to
4115 extract such a subset of statements from the database logs,
4116 it is easy to achieve with ODB tracing support:</p>
4117
4118 <pre class="cxx">
4119 transaction t (db.begin ());
4120 t.tracer (stderr_tracer);
4121
4122 ...
4123
4124 t.commit ();
4125 </pre>
4126
4127 <p>ODB allows us to specify a tracer on the database, connection,
4128 and transaction levels. If specified for the database, then
4129 all the statements executed on this database will be traced.
4130 On the other hand, if a tracer is specified for the
4131 connection, then only the SQL statements executed on this
4132 connection will be traced. Similarly, a tracer specified
4133 for a transaction will only show statements that are
4134 executed as part of this transaction. All three classes
4135 (<code>odb::database</code>, <code>odb::connection</code>,
4136 and <code>odb::transaction</code>) provide the identical
4137 tracing API:</p>
4138
4139 <pre class="cxx">
4140 void
4141 tracer (odb::tracer&amp;);
4142
4143 void
4144 tracer (odb::tracer*);
4145
4146 odb::tracer*
4147 tracer () const;
4148 </pre>
4149
4150 <p>The first two <code>tracer()</code> functions allow us to set
4151 the tracer object with the second one allowing us to clear the
4152 current tracer by passing a <code>NULL</code> pointer. The
4153 last <code>tracer()</code> function allows us to get the
4154 current tracer object. It returns a <code>NULL</code> pointer
4155 if there is no tracer in effect. Note that the tracing API
4156 does not manage the lifetime of the tracer object. The tracer
4157 should be valid for as long as it is being used. Furthermore,
4158 the tracing API is not thread-safe. Trying to set a tracer
4159 from multiple threads simultaneously will result in
4160 undefined behavior.</p>
4161
4162 <p>The <code>odb::tracer</code> class defines a callback interface
4163 that can be used to create custom tracer implementations. The
4164 <code>odb::stderr_tracer</code> and <code>odb::stderr_full_tracer</code>
4165 are built-in tracer implementations provided by the ODB runtime.
4166 They both print SQL statements being executed to the standard error
4167 stream. The full tracer, in addition to tracing statement executions,
4168 also traces their preparations and deallocations. One situation where
4169 the full tracer can be particularly useful is if a statement (for
4170 example a custom query) contains a syntax error. In this case the
4171 error will be detected during preparation and, as a result, the
4172 statement will never be executed. The only way to see such a statement
4173 is by using the full tracing.</p>
4174
4175 <p>The <code>odb::tracer</code> class is defined in the
4176 <code>&lt;odb/tracer.hxx></code> header file which you will need to
4177 include in order to make this class available in your application.
4178 The <code>odb::tracer</code> interface provided the following
4179 callback functions:</p>
4180
4181 <pre class="cxx">
4182 namespace odb
4183 {
4184 class tracer
4185 {
4186 public:
4187 virtual void
4188 prepare (connection&amp;, const statement&amp;);
4189
4190 virtual void
4191 execute (connection&amp;, const statement&amp;);
4192
4193 virtual void
4194 execute (connection&amp;, const char* statement) = 0;
4195
4196 virtual void
4197 deallocate (connection&amp;, const statement&amp;);
4198 };
4199 }
4200 </pre>
4201
4202 <p>The <code>prepare()</code> and <code>deallocate()</code> functions
4203 are called when a prepared statement is created and destroyed,
4204 respectively. The first <code>execute()</code> function is called
4205 when a prepared statement is executed while the second one is called
4206 when a normal statement is executed. The default implementations
4207 for the <code>prepare()</code> and <code>deallocate()</code>
4208 functions do nothing while the first <code>execute()</code> function
4209 calls the second one passing the statement text as the second
4210 argument. As a result, if all you are interested in are the
4211 SQL statements being executed, then you only need to override the
4212 second <code>execute()</code> function.</p>
4213
4214 <p>In addition to the common <code>odb::tracer</code> interface,
4215 each database runtime provides a database-specific version
4216 as <code>odb::&lt;database>::tracer</code>. It has exactly
4217 the same interface as the common version except that the
4218 <code>connection</code> and <code>statement</code> types
4219 are database-specific, which gives us access to additional,
4220 database-specific information.</p>
4221
4222 <p>As an example, consider a more elaborate, PostgreSQL-specific
4223 tracer implementation. Here we rely on the fact that the PostgreSQL
4224 ODB runtime uses names to identify prepared statements and this
4225 information can be obtained from the <code>odb::pgsql::statement</code>
4226 object:</p>
4227
4228 <pre class="cxx">
4229 #include &lt;odb/pgsql/tracer.hxx>
4230 #include &lt;odb/pgsql/database.hxx>
4231 #include &lt;odb/pgsql/connection.hxx>
4232 #include &lt;odb/pgsql/statement.hxx>
4233
4234 class pgsql_tracer: public odb::pgsql::tracer
4235 {
4236 virtual void
4237 prepare (odb::pgsql::connection&amp; c, const odb::pgsql::statement&amp; s)
4238 {
4239 cerr &lt;&lt; c.database ().db () &lt;&lt; ": PREPARE " &lt;&lt; s.name ()
4240 &lt;&lt; " AS " &lt;&lt; s.text () &lt;&lt; endl;
4241 }
4242
4243 virtual void
4244 execute (odb::pgsql::connection&amp; c, const odb::pgsql::statement&amp; s)
4245 {
4246 cerr &lt;&lt; c.database ().db () &lt;&lt; ": EXECUTE " &lt;&lt; s.name () &lt;&lt; endl;
4247 }
4248
4249 virtual void
4250 execute (odb::pgsql::connection&amp; c, const char* statement)
4251 {
4252 cerr &lt;&lt; c.database ().db () &lt;&lt; ": " &lt;&lt; statement &lt;&lt; endl;
4253 }
4254
4255 virtual void
4256 deallocate (odb::pgsql::connection&amp; c, const odb::pgsql::statement&amp; s)
4257 {
4258 cerr &lt;&lt; c.database ().db () &lt;&lt; ": DEALLOCATE " &lt;&lt; s.name () &lt;&lt; endl;
4259 }
4260 };
4261 </pre>
4262
4263 <p>Note also that you can only set a database-specific tracer object
4264 using a database-specific database instance, for example:</p>
4265
4266 <pre class="cxx">
4267 pgsql_tracer tracer;
4268
4269 odb::database&amp; db = ...;
4270 db.tracer (tracer); // Compile error.
4271
4272 odb::pgsql::database&amp; db = ...;
4273 db.tracer (tracer); // Ok.
4274 </pre>
4275
4276 <h2><a name="3.14">3.14 ODB Exceptions</a></h2>
4277
4278 <p>In the previous sections we have already mentioned some of the
4279 exceptions that can be thrown by the database functions. In this
4280 section we will discuss the ODB exception hierarchy and document
4281 all the exceptions that can be thrown by the common ODB
4282 runtime.</p>
4283
4284 <p>The root of the ODB exception hierarchy is the abstract
4285 <code>odb::exception</code> class. This class derives
4286 from <code>std::exception</code> and has the following
4287 interface:</p>
4288
4289 <pre class="cxx">
4290 namespace odb
4291 {
4292 struct exception: std::exception
4293 {
4294 virtual const char*
4295 what () const throw () = 0;
4296 };
4297 }
4298 </pre>
4299
4300 <p>Catching this exception guarantees that we will catch all the
4301 exceptions thrown by ODB. The <code>what()</code> function
4302 returns a human-readable description of the condition that
4303 triggered the exception.</p>
4304
4305 <p>The concrete exceptions that can be thrown by ODB are presented
4306 in the following listing:</p>
4307
4308 <pre class="cxx">
4309 namespace odb
4310 {
4311 struct null_pointer: exception
4312 {
4313 virtual const char*
4314 what () const throw ();
4315 };
4316
4317 // Transaction exceptions.
4318 //
4319 struct already_in_transaction: exception
4320 {
4321 virtual const char*
4322 what () const throw ();
4323 };
4324
4325 struct not_in_transaction: exception
4326 {
4327 virtual const char*
4328 what () const throw ();
4329 };
4330
4331 struct transaction_already_finalized: exception
4332 {
4333 virtual const char*
4334 what () const throw ();
4335 };
4336
4337 // Session exceptions.
4338 //
4339 struct already_in_session: exception
4340 {
4341 virtual const char*
4342 what () const throw ();
4343 };
4344
4345 struct not_in_session: exception
4346 {
4347 virtual const char*
4348 what () const throw ();
4349 };
4350
4351 struct session_required: exception
4352 {
4353 virtual const char*
4354 what () const throw ();
4355 };
4356
4357 // Database operations exceptions.
4358 //
4359 struct recoverable: exception
4360 {
4361 };
4362
4363 struct connection_lost: recoverable
4364 {
4365 virtual const char*
4366 what () const throw ();
4367 };
4368
4369 struct timeout: recoverable
4370 {
4371 virtual const char*
4372 what () const throw ();
4373 };
4374
4375 struct deadlock: recoverable
4376 {
4377 virtual const char*
4378 what () const throw ();
4379 };
4380
4381 struct object_not_persistent: exception
4382 {
4383 virtual const char*
4384 what () const throw ();
4385 };
4386
4387 struct object_already_persistent: exception
4388 {
4389 virtual const char*
4390 what () const throw ();
4391 };
4392
4393 struct object_changed: exception
4394 {
4395 virtual const char*
4396 what () const throw ();
4397 };
4398
4399 struct result_not_cached: exception
4400 {
4401 virtual const char*
4402 what () const throw ();
4403 };
4404
4405 struct database_exception: exception
4406 {
4407 };
4408
4409 // Polymorphism support exceptions.
4410 //
4411 struct abstract_class: exception
4412 {
4413 virtual const char*
4414 what () const throw ();
4415 };
4416
4417 struct no_type_info: exception
4418 {
4419 virtual const char*
4420 what () const throw ();
4421 };
4422
4423 // Prepared query support exceptions.
4424 //
4425 struct prepared_already_cached: exception
4426 {
4427 const char*
4428 name () const;
4429
4430 virtual const char*
4431 what () const throw ();
4432 };
4433
4434 struct prepared_type_mismatch: exception
4435 {
4436 const char*
4437 name () const;
4438
4439 virtual const char*
4440 what () const throw ();
4441 };
4442
4443 // Schema catalog exceptions.
4444 //
4445 struct unknown_schema: exception
4446 {
4447 const std::string&amp;
4448 name () const;
4449
4450 virtual const char*
4451 what () const throw ();
4452 };
4453
4454 struct unknown_schema_version: exception
4455 {
4456 schema_version
4457 version () const;
4458
4459 virtual const char*
4460 what () const throw ();
4461 };
4462
4463 // Section exceptions.
4464 //
4465 struct section_not_loaded: exception
4466 {
4467 virtual const char*
4468 what () const throw ();
4469 };
4470
4471 struct section_not_in_object: exception
4472 {
4473 virtual const char*
4474 what () const throw ();
4475 };
4476
4477 // Bulk operation exceptions.
4478 //
4479 struct multiple_exceptions: exception
4480 {
4481 ...
4482
4483 virtual const char*
4484 what () const throw ();
4485 };
4486 }
4487 </pre>
4488
4489 <p>The <code>null_pointer</code> exception is thrown when a
4490 pointer to a persistent object declared non-<code>NULL</code>
4491 with the <code>db&nbsp;not_null</code> or
4492 <code>db&nbsp;value_not_null</code> pragma has the <code>NULL</code>
4493 value. See <a href="#6">Chapter 6, "Relationships"</a> for details.</p>
4494
4495 <p>The next three exceptions (<code>already_in_transaction</code>,
4496 <code>not_in_transaction</code>,
4497 <code>transaction_already_finalized</code>) are thrown by the
4498 <code>odb::transaction</code> class and are discussed
4499 in <a href="#3.5">Section 3.5, "Transactions"</a>.</p>
4500
4501 <p>The next two exceptions (<code>already_in_session</code>, and
4502 <code>not_in_session</code>) are thrown by the <code>odb::session</code>
4503 class and are discussed in <a href="#11">Chapter 11, "Session"</a>.</p>
4504
4505 <p>The <code>session_required</code> exception is thrown when ODB detects
4506 that correctly loading a bidirectional object relationship requires a
4507 session but one is not used. See <a href="#6.2">Section 6.2,
4508 "Bidirectional Relationships"</a> for more information on this
4509 exception.</p>
4510
4511 <p>The <code>recoverable</code> exception serves as a common base
4512 for all the recoverable exceptions, which are: <code>connection_lost</code>,
4513 <code>timeout</code>, and <code>deadlock</code>. The
4514 <code>connection_lost</code> exception is thrown when a connection
4515 to the database is lost. Similarly, the <code>timeout</code> exception
4516 is thrown if one of the database operations or the whole transaction
4517 has timed out. The <code>deadlock</code> exception is thrown when a
4518 transaction deadlock is detected by the database system. These
4519 exceptions can be thrown by any database function. See
4520 <a href="#3.7">Section 3.7, "Error Handling and Recovery"</a>
4521 for details.</p>
4522
4523 <p>The <code>object_already_persistent</code> exception is thrown
4524 by the <code>persist()</code> database function. See
4525 <a href="#3.8">Section 3.8, "Making Objects Persistent"</a>
4526 for details.</p>
4527
4528 <p>The <code>object_not_persistent</code> exception is thrown
4529 by the <code>load()</code>, <code>update()</code>, and
4530 <code>erase()</code> database functions. Refer to
4531 <a href="#3.9">Section 3.9, "Loading Persistent Objects"</a>,
4532 <a href="#3.10">Section 3.10, "Updating Persistent Objects"</a>, and
4533 <a href="#3.11">Section 3.11, "Deleting Persistent Objects"</a> for
4534 more information.</p>
4535
4536 <p>The <code>object_changed</code> exception is thrown
4537 by the <code>update()</code> database function and certain
4538 <code>erase()</code> database functions when
4539 operating on objects with the optimistic concurrency model. See
4540 <a href="#12">Chapter 12, "Optimistic Concurrency"</a> for details.</p>
4541
4542 <p>The <code>result_not_cached</code> exception is thrown by
4543 the query result class. Refer to <a href="#4.4">Section 4.4,
4544 "Query Result"</a> for details.</p>
4545
4546 <p>The <code>database_exception</code> exception is a base class for all
4547 database system-specific exceptions that are thrown by the
4548 database system-specific runtime library. Refer to <a href="#II">Part
4549 II, "Database Systems"</a> for more information.</p>
4550
4551 <p>The <code>abstract_class</code> exception is thrown by the database
4552 functions when we attempt to persist, update, load, or erase an
4553 instance of a polymorphic abstract class. For more information
4554 on abstract classes, refer to <a href="#14.1.3">Section 14.1.3,
4555 "<code>abstract</code>"</a>.</p>
4556
4557 <p>The <code>no_type_info</code> exception is thrown by the database
4558 functions when we attempt to persist, update, load, or erase an
4559 instance of a polymorphic class for which no type information
4560 is present in the application. This normally means that the
4561 generated database support code for this class has not been
4562 linked (or dynamically loaded) into the application or the
4563 discriminator value has not been mapped to a persistent
4564 class. For more information on polymorphism support, refer to
4565 <a href="#8.2">Section 8.2, "Polymorphism Inheritance"</a>.</p>
4566
4567 <p>The <code>prepared_already_cached</code> exception is thrown by the
4568 <code>cache_query()</code> function if a prepared query with the
4569 specified name is already cached. The <code>prepared_type_mismatch</code>
4570 exception is thrown by the <code>lookup_query()</code> function if
4571 the specified prepared query object type or parameters type
4572 does not match the one in the cache. Refer to <a href="#4.5">Section
4573 4.5, "Prepared Queries"</a> for details.</p>
4574
4575 <p>The <code>unknown_schema</code> exception is thrown by the
4576 <code>odb::schema_catalog</code> class if a schema with the specified
4577 name is not found. Refer to <a href="#3.4">Section 3.4, "Database"</a>
4578 for details. The <code>unknown_schema_version</code> exception is
4579 thrown by the <code>schema_catalog</code> functions that deal with
4580 database schema evolution if the passed version is unknow. Refer
4581 to <a href="#13">Chapter 13, "Database Schema Evolution"</a> for
4582 details.</p>
4583
4584 <p>The <code>section_not_loaded</code> exception is thrown if we
4585 attempt to update an object section that hasn't been loaded.
4586 The <code>section_not_in_object</code> exception is thrown if
4587 the section instance being loaded or updated does not belong
4588 to the corresponding object. See <a href="#9">Chapter 9,
4589 "Sections"</a> for more information on these exceptions.</p>
4590
4591 <p>The <code>multiple_exceptions</code> exception is thrown by the
4592 bulk API functions. Refer to <a href="#15.3">Section 15.3, "Bulk
4593 Database Operations"</a> for details.</p>
4594
4595 <p>The <code>odb::exception</code> class is defined in the
4596 <code>&lt;odb/exception.hxx></code> header file. All the
4597 concrete ODB exceptions are defined in
4598 <code>&lt;odb/exceptions.hxx></code> which also includes
4599 <code>&lt;odb/exception.hxx></code>. Normally you don't
4600 need to include either of these two headers because they are
4601 automatically included by <code>&lt;odb/database.hxx></code>.
4602 However, if the source file that handles ODB exceptions
4603 does not include <code>&lt;odb/database.hxx></code>, then
4604 you will need to explicitly include one of these headers.</p>
4605
4606
4607 <!-- CHAPTER -->
4608
4609
4610 <hr class="page-break"/>
4611 <h1><a name="4">4 Querying the Database</a></h1>
4612
4613 <p>If we don't know the identifiers of the objects that we are looking
4614 for, we can use queries to search the database for objects matching
4615 certain criteria. The ODB query facility is optional and we need to
4616 explicitly request the generation of the necessary database support
4617 code with the <code>--generate-query</code> ODB compiler option.</p>
4618
4619 <p>ODB provides a flexible query API that offers two distinct levels of
4620 abstraction from the database system query language such as SQL.
4621 At the high level we are presented with an easy to use yet powerful
4622 object-oriented query language, called ODB Query Language. This
4623 query language is modeled after and is integrated into C++ allowing
4624 us to write expressive and safe queries that look and feel like
4625 ordinary C++. We have already seen examples of these queries in the
4626 introductory chapters. Below is another, more interesting, example:</p>
4627
4628 <pre class="cxx">
4629 typedef odb::query&lt;person> query;
4630 typedef odb::result&lt;person> result;
4631
4632 unsigned short age;
4633 query q (query::first == "John" &amp;&amp; query::age &lt; query::_ref (age));
4634
4635 for (age = 10; age &lt; 100; age += 10)
4636 {
4637 result r (db.query&lt;person> (q));
4638 ...
4639 }
4640 </pre>
4641
4642 <p>At the low level, queries can be written as predicates using
4643 the database system-native query language such as the
4644 <code>WHERE</code> predicate from the SQL <code>SELECT</code>
4645 statement. This language will be referred to as native query
4646 language. At this level ODB still takes care of converting
4647 query parameters from C++ to the database system format. Below
4648 is the re-implementation of the above example using SQL as
4649 the native query language:</p>
4650
4651 <pre class="cxx">
4652 query q ("first = 'John' AND age = " + query::_ref (age));
4653 </pre>
4654
4655 <p>Note that at this level we lose the static typing of
4656 query expressions. For example, if we wrote something like this:</p>
4657
4658 <pre class="cxx">
4659 query q (query::first == 123 &amp;&amp; query::agee &lt; query::_ref (age));
4660 </pre>
4661
4662 <p>We would get two errors during the C++ compilation. The first would
4663 indicate that we cannot compare <code>query::first</code> to an
4664 integer and the second would pick the misspelling in
4665 <code>query::agee</code>. On the other hand, if we wrote something
4666 like this:</p>
4667
4668 <pre class="cxx">
4669 query q ("first = 123 AND agee = " + query::_ref (age));
4670 </pre>
4671
4672 <p>It would compile fine and would trigger an error only when executed
4673 by the database system.</p>
4674
4675 <p>We can also combine the two query languages in a single query, for
4676 example:</p>
4677
4678 <pre class="cxx">
4679 query q ("first = 'John' AND" + (query::age &lt; query::_ref (age)));
4680 </pre>
4681
4682 <h2><a name="4.1">4.1 ODB Query Language</a></h2>
4683
4684 <p>An ODB query is an expression that tells the database system whether
4685 any given object matches the desired criteria. As such, a query expression
4686 always evaluates as <code>true</code> or <code>false</code>. At
4687 the higher level, an expression consists of other expressions
4688 combined with logical operators such as <code>&amp;&amp;</code> (AND),
4689 <code>||</code> (OR), and <code>!</code> (NOT). For example:</p>
4690
4691 <pre class="cxx">
4692 typedef odb::query&lt;person> query;
4693
4694 query q (query::first == "John" || query::age == 31);
4695 </pre>
4696
4697 <p>At the core of every query expression lie simple expressions which
4698 involve one or more object members, values, or parameters. To
4699 refer to an object member we use an expression such as
4700 <code>query::first</code> above. The names of members in the
4701 <code>query</code> class are derived from the names of data members
4702 in the object class by removing the common member name decorations,
4703 such as leading and trailing underscores, the <code>m_</code> prefix,
4704 etc.</p>
4705
4706 <p>In a simple expression an object member can be compared to a value,
4707 parameter, or another member using a number of predefined operators
4708 and functions. The following table gives an overview of the available
4709 expressions:</p>
4710
4711 <!-- border="1" is necessary for html2ps -->
4712 <table id="operators" border="1">
4713 <tr>
4714 <th>Operator</th>
4715 <th>Description</th>
4716 <th>Example</th>
4717 </tr>
4718
4719 <tr>
4720 <td><code>==</code></td>
4721 <td>equal</td>
4722 <td><code>query::age == 31</code></td>
4723 </tr>
4724
4725 <tr>
4726 <td><code>!=</code></td>
4727 <td>unequal</td>
4728 <td><code>query::age != 31</code></td>
4729 </tr>
4730
4731 <tr>
4732 <td><code>&lt;</code></td>
4733 <td>less than</td>
4734 <td><code>query::age &lt; 31</code></td>
4735 </tr>
4736
4737 <tr>
4738 <td><code>></code></td>
4739 <td>greater than</td>
4740 <td><code>query::age > 31</code></td>
4741 </tr>
4742
4743 <tr>
4744 <td><code>&lt;=</code></td>
4745 <td>less than or equal</td>
4746 <td><code>query::age &lt;= 31</code></td>
4747 </tr>
4748
4749 <tr>
4750 <td><code>>=</code></td>
4751 <td>greater than or equal</td>
4752 <td><code>query::age >= 31</code></td>
4753 </tr>
4754
4755 <tr>
4756 <td><code>in()</code></td>
4757 <td>one of the values</td>
4758 <td><code>query::age.in (30, 32, 34)</code></td>
4759 </tr>
4760
4761 <tr>
4762 <td><code>in_range()</code></td>
4763 <td>one of the values in range</td>
4764 <td><code>query::age.in_range (begin, end)</code></td>
4765 </tr>
4766
4767 <tr>
4768 <td><code>like()</code></td>
4769 <td>matches a pattern</td>
4770 <td><code>query::first.like ("J%")</code></td>
4771 </tr>
4772
4773 <tr>
4774 <td><code>is_null()</code></td>
4775 <td>value is <code>NULL</code></td>
4776 <td><code>query::age.is_null ()</code></td>
4777 </tr>
4778
4779 <tr>
4780 <td><code>is_not_null()</code></td>
4781 <td>value is <code>NOT NULL</code></td>
4782 <td><code>query::age.is_not_null ()</code></td>
4783 </tr>
4784 </table>
4785
4786 <p>The <code>in()</code> function accepts a maximum of five arguments.
4787 Use the <code>in_range()</code> function if you need to compare
4788 to more than five values. This function accepts a pair of
4789 standard C++ iterators and compares to all the values from
4790 the <code>begin</code> position inclusive and until and
4791 excluding the <code>end</code> position. The following
4792 code fragment shows how we can use these functions:</p>
4793
4794 <pre class="cxx">
4795 std::vector&lt;string> names;
4796
4797 names.push_back ("John");
4798 names.push_back ("Jack");
4799 names.push_back ("Jane");
4800
4801 query q1 (query::first.in ("John", "Jack", "Jane"));
4802 query q2 (query::first.in_range (names.begin (), names.end ()));
4803 </pre>
4804
4805 <p>Note that the <code>like()</code> function does not perform any
4806 translation of the database system-specific extensions of the
4807 SQL <code>LIKE</code> operator. As a result, if you would like
4808 your application to be portable among various database systems,
4809 then limit the special characters used in the pattern to
4810 <code>%</code> (matches zero or more characters) and <code>_</code>
4811 (matches exactly one character). It is also possible to specify
4812 the escape character as a second argument to the <code>like()</code>
4813 function. This character can then be used to escape the special
4814 characters (<code>%</code> and <code>_</code>) in the pattern.
4815 For example, the following query will match any two characters
4816 separated by an underscore:</p>
4817
4818 <pre class="cxx">
4819 query q (query::name.like ("_!__", "!"));
4820 </pre>
4821
4822 <p>The operator precedence in the query expressions are the same
4823 as for equivalent C++ operators. We can use parentheses to
4824 make sure the expression is evaluated in the desired order.
4825 For example:</p>
4826
4827 <pre class="cxx">
4828 query q ((query::first == "John" || query::first == "Jane") &amp;&amp;
4829 query::age &lt; 31);
4830 </pre>
4831
4832
4833 <h2><a name="4.2">4.2 Parameter Binding</a></h2>
4834
4835 <p>An instance of the <code>odb::query</code> class encapsulates two
4836 parts of information about the query: the query expression and
4837 the query parameters. Parameters can be bound to C++ variables
4838 either by value or by reference.</p>
4839
4840 <p>If a parameter is bound by value, then the value for this parameter
4841 is copied from the C++ variable to the query instance at the query
4842 construction time. On the other hand, if a parameter is bound by
4843 reference, then the query instance stores a reference to the
4844 bound variable. The actual value of the parameter is only extracted
4845 at the query execution time. Consider, for example, the following
4846 two queries:</p>
4847
4848 <pre class="cxx">
4849 string name ("John");
4850
4851 query q1 (query::first == query::_val (name));
4852 query q2 (query::first == query::_ref (name));
4853
4854 name = "Jane";
4855
4856 db.query&lt;person> (q1); // Find John.
4857 db.query&lt;person> (q2); // Find Jane.
4858 </pre>
4859
4860 <p>The <code>odb::query</code> class provides two special functions,
4861 <code>_val()</code> and <code>_ref()</code>, that allow us to
4862 bind the parameter either by value or by reference, respectively.
4863 In the ODB query language, if the binding is not specified
4864 explicitly, the value semantic is used by default. In the
4865 native query language, binding must always be specified
4866 explicitly. For example:</p>
4867
4868 <pre class="cxx">
4869 query q1 (query::age &lt; age); // By value.
4870 query q2 (query::age &lt; query::_val (age)); // By value.
4871 query q3 (query::age &lt; query::_ref (age)); // By reference.
4872
4873 query q4 ("age &lt; " + age); // Error.
4874 query q5 ("age &lt; " + query::_val (age)); // By value.
4875 query q6 ("age &lt; " + query::_ref (age)); // By reference.
4876 </pre>
4877
4878 <p>A query that only has by-value parameters does not depend on any
4879 other variables and is self-sufficient once constructed. A query
4880 that has one or more by-reference parameters depends on the
4881 bound variables until the query is executed. If one such variable
4882 goes out of scope and we execute the query, the behavior is
4883 undefined.</p>
4884
4885 <h2><a name="4.3">4.3 Executing a Query</a></h2>
4886
4887 <p>Once we have the query instance ready and by-reference parameters
4888 initialized, we can execute the query using the
4889 <code>database::query()</code> function template. It has two
4890 overloaded versions:</p>
4891
4892 <pre class="cxx">
4893 template &lt;typename T>
4894 result&lt;T>
4895 query (bool cache = true);
4896
4897 template &lt;typename T>
4898 result&lt;T>
4899 query (const odb::query&lt;T>&amp;, bool cache = true);
4900 </pre>
4901
4902 <p>The first <code>query()</code> function is used to return all the
4903 persistent objects of a given type stored in the database.
4904 The second function uses the passed query instance to only return
4905 objects matching the query criteria. The <code>cache</code> argument
4906 determines whether the objects' states should be cached in the
4907 application's memory or if they should be returned by the database
4908 system one by one as the iteration over the result progresses. The
4909 result caching is discussed in detail in the next section.</p>
4910
4911 <p>When calling the <code>query()</code> function, we have to
4912 explicitly specify the object type we are querying. For example:</p>
4913
4914 <pre class="cxx">
4915 typedef odb::query&lt;person> query;
4916 typedef odb::result&lt;person> result;
4917
4918 result all (db.query&lt;person> ());
4919 result johns (db.query&lt;person> (query::first == "John"));
4920 </pre>
4921
4922 <p>Note that it is not required to explicitly create a named
4923 query variable before executing it. For example, the following
4924 two queries are equivalent:</p>
4925
4926 <pre class="cxx">
4927 query q (query::first == "John");
4928
4929 result r1 (db.query&lt;person> (q));
4930 result r1 (db.query&lt;person> (query::first == "John"));
4931 </pre>
4932
4933 <p>Normally, we would create a named query instance if we are
4934 planning to run the same query multiple times and would use the
4935 in-line version for those that are executed only once (see also
4936 <a href="#4.5">Section 4.5, "Prepared Queries"</a> for a more
4937 optimal way to re-execute the same query multiple times). A named
4938 query instance that does not have any by-reference parameters is
4939 immutable and can be shared between multiple threads without
4940 synchronization. On the other hand, a query instance with
4941 by-reference parameters is modified every time it is executed.
4942 If such a query is shared among multiple threads, then access
4943 to this query instance must be synchronized from the execution
4944 point and until the completion of the iteration over the result.</p>
4945
4946 <p>It is also possible to create queries from other queries by
4947 combining them using logical operators. For example:</p>
4948
4949 <pre class="cxx">
4950 result
4951 find_minors (database&amp; db, const query&amp; name_query)
4952 {
4953 return db.query&lt;person> (name_query &amp;&amp; query::age &lt; 18);
4954 }
4955
4956 result r (find_minors (db, query::first == "John"));
4957 </pre>
4958
4959 <p>The result of executing a query is zero, one, or more objects
4960 matching the query criteria. The <code>query()</code> function
4961 returns this result as an instance of the <code>odb::result</code>
4962 class template, which provides a stream-like interface and is
4963 discussed in detail in the next section.</p>
4964
4965 <p>In situations where we know that a query produces at most one
4966 element, we can instead use the <code>database::query_one()</code> and
4967 <code>database::query_value()</code> shortcut functions, for example:</p>
4968
4969 <pre class="cxx">
4970 typedef odb::query&lt;person> query;
4971
4972 auto_ptr&lt;person> p (
4973 db.query_one&lt;person> (
4974 query::email == "[email protected]"));
4975 </pre>
4976
4977 <p>The shortcut query functions have the following signatures:</p>
4978
4979 <pre class="cxx">
4980 template &lt;typename T>
4981 typename object_traits&lt;T>::pointer_type
4982 query_one ();
4983
4984 template &lt;typename T>
4985 bool
4986 query_one (T&amp;);
4987
4988 template &lt;typename T>
4989 T
4990 query_value ();
4991
4992 template &lt;typename T>
4993 typename object_traits&lt;T>::pointer_type
4994 query_one (const odb::query&lt;T>&amp;);
4995
4996 template &lt;typename T>
4997 bool
4998 query_one (const odb::query&lt;T>&amp;, T&amp;);
4999
5000 template &lt;typename T>
5001 T
5002 query_value (const odb::query&lt;T>&amp;);
5003 </pre>
5004
5005 <p>Similar to <code>query()</code>, the first three functions are used
5006 to return the only persistent object of a given type stored in the
5007 database. The second three versions use the passed query instance
5008 to only return the object matching the query criteria.</p>
5009
5010 <p>Similar to the <code>database::find()</code> functions
5011 (<a href="#3.9">Section 3.9, "Loading Persistent Objects"</a>),
5012 <code>query_one()</code> can either allocate a new instance of the
5013 object class in the dynamic memory or it can load the object's state
5014 into an existing instance. The <code>query_value()</code> function
5015 allocates and returns the object by value.</p>
5016
5017 <p>The <code>query_one()</code> function allows us to determine
5018 if the query result contains zero or one element. If no objects
5019 matching the query criteria were found in the database, the
5020 first version of <code>query_one()</code> returns the <code>NULL</code>
5021 pointer while the second &mdash; <code>false</code>. If the second
5022 version returns <code>false</code>, then the passed object
5023 remains unchanged. For example:</p>
5024
5025 <pre class="cxx">
5026 if (unique_ptr&lt;person> p = db.query_one&lt;person> (
5027 query::email == "[email protected]"))
5028 {
5029 ...
5030 }
5031
5032 person p;
5033 if (db.query_one&lt;person> (query::email == "[email protected]", p))
5034 {
5035 ...
5036 }
5037 </pre>
5038
5039 <p>If the query executed using <code>query_one()</code> or
5040 <code>query_value()</code> returns more than one element,
5041 then these functions fail with an assertion. Additionally,
5042 <code>query_value()</code> also fails with an assertion if
5043 the query returned no elements.</p>
5044
5045 <p>Common situations where we can use the shortcut functions are a
5046 query condition that uses a data member with the
5047 <code>unique</code> constraint (at most one element returned;
5048 see <a href="#14.7">Section 14.7, "Index Definition Pragmas"</a>)
5049 as well as aggregate queries (exactly one element returned; see
5050 <a href="#10">Chapter 10, "Views"</a>).</p>
5051
5052 <h2><a name="4.4">4.4 Query Result</a></h2>
5053
5054 <p>The <code>database::query()</code> function returns the result of
5055 executing a query as an instance of the <code>odb::result</code>
5056 class template, for example:</p>
5057
5058 <pre class="cxx">
5059 typedef odb::query&lt;person> query;
5060 typedef odb::result&lt;person> result;
5061
5062 result johns (db.query&lt;person> (query::first == "John"));
5063 </pre>
5064
5065 <p>It is best to view an instance of <code>odb::result</code>
5066 as a handle to a stream, such as a file stream. While we can
5067 make a copy of a result or assign one result to another, the
5068 two instances will refer to the same result stream. Advancing
5069 the current position in one instance will also advance it in
5070 another. The result instance is only usable within the transaction
5071 it was created in. Trying to manipulate the result after the
5072 transaction has terminated leads to undefined behavior.</p>
5073
5074 <p>The <code>odb::result</code> class template conforms to the
5075 standard C++ sequence requirements and has the following
5076 interface:</p>
5077
5078 <pre class="cxx">
5079 namespace odb
5080 {
5081 template &lt;typename T>
5082 class result
5083 {
5084 public:
5085 typedef odb::result_iterator&lt;T> iterator;
5086
5087 public:
5088 result ();
5089
5090 result (const result&amp;);
5091
5092 result&amp;
5093 operator= (const result&amp;);
5094
5095 void
5096 swap (result&amp;)
5097
5098 public:
5099 iterator
5100 begin ();
5101
5102 iterator
5103 end ();
5104
5105 public:
5106 void
5107 cache ();
5108
5109 bool
5110 empty () const;
5111
5112 std::size_t
5113 size () const;
5114 };
5115 }
5116 </pre>
5117
5118 <p>The default constructor creates an empty result set. The
5119 <code>cache()</code> function caches the returned objects'
5120 state in the application's memory. We have already mentioned
5121 result caching when we talked about query execution. As you
5122 may remember the <code>database::query()</code> function
5123 caches the result unless instructed not to by the caller.
5124 The <code>cache()</code> function allows us to
5125 cache the result at a later stage if it wasn't already
5126 cached during query execution.</p>
5127
5128 <p>If the result is cached, the database state of all the returned
5129 objects is stored in the application's memory. Note that
5130 the actual objects are still only instantiated on demand
5131 during result iteration. It is the raw database state that
5132 is cached in memory. In contrast, for uncached results
5133 the object's state is sent by the database system one object
5134 at a time as the iteration progresses.</p>
5135
5136 <p>Uncached results can improve the performance of both the application
5137 and the database system in situations where we have a large
5138 number of objects in the result or if we will only examine
5139 a small portion of the returned objects. However, uncached
5140 results have a number of limitations. There can only be one
5141 uncached result in a transaction. Creating another result
5142 (cached or uncached) by calling <code>database::query()</code>
5143 will invalidate the existing uncached result. Furthermore,
5144 calling any other database functions, such as <code>update()</code>
5145 or <code>erase()</code> will also invalidate the uncached result.
5146 It also follows that uncached results cannot be used on objects
5147 with containers (<a href="#5">Chapter 5, "Containers"</a>) since
5148 loading a container would invalidate the uncached result.</p>
5149
5150 <p>The <code>empty()</code> function returns <code>true</code> if
5151 there are no objects in the result and <code>false</code> otherwise.
5152 The <code>size()</code> function can only be called for cached results.
5153 It returns the number of objects in the result. If we call this
5154 function on an uncached result, the <code>odb::result_not_cached</code>
5155 exception is thrown.</p>
5156
5157 <p>To iterate over the objects in a result we use the
5158 <code>begin()</code> and <code>end()</code> functions
5159 together with the <code>odb::result&lt;T>::iterator</code>
5160 type, for example:</p>
5161
5162 <pre class="cxx">
5163 result r (db.query&lt;person> (query::first == "John"));
5164
5165 for (result::iterator i (r.begin ()); i != r.end (); ++i)
5166 {
5167 ...
5168 }
5169 </pre>
5170
5171 <p>In C++11 we can use the <code>auto</code>-typed variabe instead
5172 of spelling the iterator type explicitly, for example:</p>
5173
5174 <pre class="cxx">
5175 for (auto i (r.begin ()); i != r.end (); ++i)
5176 {
5177 ...
5178 }
5179 </pre>
5180
5181 <p>The C++11 range-based <code>for</code>-loop can be used to further
5182 simplify the iteration:</p>
5183
5184 <pre class="cxx">
5185 for (person&amp; p: r)
5186 {
5187 ...
5188 }
5189 </pre>
5190
5191 <p>The result iterator is an input iterator which means that the
5192 only two position operations that it supports are to move to the
5193 next object and to determine whether the end of the result stream
5194 has been reached. In fact, the result iterator can only be in two
5195 states: the current position and the end position. If we have
5196 two iterators pointing to the current position and then we
5197 advance one of them, the other will advance as well. This,
5198 for example, means that it doesn't make sense to store an
5199 iterator that points to some object of interest in the result
5200 stream with the intent of dereferencing it after the iteration
5201 is over. Instead, we would need to store the object itself.</p>
5202
5203 <p>The result iterator has the following dereference functions
5204 that can be used to access the pointed-to object:</p>
5205
5206 <pre class="cxx">
5207 namespace odb
5208 {
5209 template &lt;typename T>
5210 class result_iterator
5211 {
5212 public:
5213 T*
5214 operator-> () const;
5215
5216 T&amp;
5217 operator* () const;
5218
5219 typename object_traits&lt;T>::pointer_type
5220 load ();
5221
5222 void
5223 load (T&amp; x);
5224
5225 typename object_traits&lt;T>::id_type
5226 id ();
5227 };
5228 }
5229 </pre>
5230
5231 <p>When we call the <code>*</code> or <code>-></code> operator,
5232 the iterator will allocate a new instance of the object class
5233 in the dynamic memory, load its state from the database
5234 state, and return a reference or pointer to the new instance. The
5235 iterator maintains the ownership of the returned object and will
5236 return the same pointer for subsequent calls to either of these
5237 operators until it is advanced to the next object or we call
5238 the first <code>load()</code> function (see below). For example:</p>
5239
5240 <pre class="cxx">
5241 result r (db.query&lt;person> (query::first == "John"));
5242
5243 for (result::iterator i (r.begin ()); i != r.end ();)
5244 {
5245 cout &lt;&lt; i->last () &lt;&lt; endl; // Create an object.
5246 person&amp; p (*i); // Reference to the same object.
5247 cout &lt;&lt; p.age () &lt;&lt; endl;
5248 ++i; // Free the object.
5249 }
5250 </pre>
5251
5252 <p>The overloaded <code>result_iterator::load()</code> functions are
5253 similar to <code>database::load()</code>. The first function
5254 returns a dynamically allocated instance of the current
5255 object. As an optimization, if the iterator already owns an object
5256 as a result of an earlier
5257 call to the <code>*</code> or <code>-></code> operator, then it
5258 relinquishes the ownership of this object and returns it instead.
5259 This allows us to write code like this without worrying about
5260 a double allocation:</p>
5261
5262 <pre class="cxx">
5263 result r (db.query&lt;person> (query::first == "John"));
5264
5265 for (result::iterator i (r.begin ()); i != r.end (); ++i)
5266 {
5267 if (i->last == "Doe")
5268 {
5269 auto_ptr p (i.load ());
5270 ...
5271 }
5272 }
5273 </pre>
5274
5275 <p>Note, however, that because of this optimization, a subsequent
5276 to <code>load()</code> call to the <code>*</code> or <code>-></code>
5277 operator results in the allocation of a new object.</p>
5278
5279 <p>The second <code>load()</code> function allows
5280 us to load the current object's state into an existing instance.
5281 For example:</p>
5282
5283 <pre class="cxx">
5284 result r (db.query&lt;person> (query::first == "John"));
5285
5286 person p;
5287 for (result::iterator i (r.begin ()); i != r.end (); ++i)
5288 {
5289 i.load (p);
5290 cout &lt;&lt; p.last () &lt;&lt; endl;
5291 cout &lt;&lt; i.age () &lt;&lt; endl;
5292 }
5293 </pre>
5294
5295 <p>The <code>id()</code> function return the object id of the current
5296 object. While we can achieve the same by loading the object and getting
5297 its id, this function is more efficient since it doesn't actually
5298 create the object. This can be useful when all we need is the object's
5299 identifier. For example:</p>
5300
5301 <pre class="cxx">
5302 std::set&lt;unsigned long> set = ...; // Persons of interest.
5303
5304 result r (db.query&lt;person> (query::first == "John"));
5305
5306 for (result::iterator i (r.begin ()); i != r.end (); ++i)
5307 {
5308 if (set.find (i.id ()) != set.end ()) // No object loaded.
5309 {
5310 cout &lt;&lt; i->first () &lt;&lt; endl; // Object loaded.
5311 }
5312 }
5313 </pre>
5314
5315 <h2><a name="4.5">4.5 Prepared Queries</a></h2>
5316
5317 <p>Most modern relational database systems have the notion of a prepared
5318 statement. Prepared statements allow us to perform the potentially
5319 expensive tasks of parsing SQL, preparing the query execution
5320 plan, etc., once and then executing the same query multiple
5321 times, potentially using different values for parameters in
5322 each execution.</p>
5323
5324 <p>In ODB all the non-query database operations such as
5325 <code>persist()</code>, <code>load()</code>, <code>update()</code>,
5326 etc., are implemented in terms of prepared statements that are cached
5327 and reused. While the <code>query()</code>, <code>query_one()</code>,
5328 and <code>query_one()</code> database operations also use prepared
5329 statements, these statements are not cached or reused by default since
5330 ODB has no knowledge of whether a query will be executed multiple times
5331 or only once. Instead, ODB provides a mechanism, called prepared queries,
5332 that allows us to prepare a query once and execute it multiple
5333 times. In other words, ODB prepared queries are a thin wrapper
5334 around the underlying database's prepared statement functionality.</p>
5335
5336 <p>In most cases ODB shields the application developer from database
5337 connection management and multi-threading issues. However, when it
5338 comes to prepared queries, a basic understanding of how ODB manages
5339 these aspects is required. Conceptually, the <code>odb::database</code>
5340 class represents a specific database, that is, a data store. However,
5341 underneath, it maintains one or more connections to this database.
5342 A connection can be used only by a single thread at a time. When
5343 we start a transaction (by calling <code>database::begin()</code>),
5344 the transaction instance obtains a connection and holds on to it
5345 until the transaction is committed or rolled back. During this time
5346 no other thread can use this connection. When the transaction
5347 releases the connection, it may be closed or reused by another
5348 transaction in this or another thread. What exactly happens to
5349 a connection after it has been released depends on the connection
5350 factory that is used by the <code>odb::database</code> instance.
5351 For more information on connection factories, refer to
5352 <a href="#II">Part II, "Database Systems"</a>.</p>
5353
5354 <p>A query prepared on one connection cannot be executed on another.
5355 In other words, a prepared query is associated with the connection.
5356 One important implication of this restriction is that we cannot
5357 prepare a query in one transaction and then try to execute it
5358 in another without making sure that both transactions use the
5359 same connection.</p>
5360
5361 <p>To enable the prepared query functionality we need to specify
5362 the <code>--generate-prepared</code> ODB compiler option. If
5363 we are planning to always prepare our queries, then we can
5364 disable the once-off query execution support by also specifying
5365 the <code>--omit-unprepared</code> option.</p>
5366
5367 <p>To prepare a query we use the <code>prepare_query()</code> function
5368 template. This function can be called on both the <code>odb::database</code>
5369 and <code>odb::connection</code> instances. The <code>odb::database</code>
5370 version simply obtains the connection used by the currently active
5371 transaction and calls the corresponding <code>odb::connection</code>
5372 version. If no transaction is currently active, then this function
5373 throws the <code>odb::not_in_transaction</code> exception
5374 (<a href="#3.5">Section 3.5, "Transactions"</a>). The
5375 <code>prepare_query()</code> function has the following signature:</p>
5376
5377 <pre class="cxx">
5378 template &lt;typename T>
5379 prepared_query&lt;T>
5380 prepare_query (const char* name, const odb::query&lt;T>&amp;);
5381 </pre>
5382
5383 <p>The first argument to the <code>prepare_query()</code> function is
5384 the prepared query name. This name is used as a key for prepared
5385 query caching (discussed later) and must be unique. For some databases,
5386 notably PostgreSQL, it is also used as a name of the underlying prepared
5387 statement. The name <code>"<i>object</i>_query"</code> (for example,
5388 <code>"person_query"</code>) is reserved for the once-off queries
5389 executed by the <code>database::query()</code> function. Note that
5390 the <code>prepare_query()</code> function makes only a shallow copy
5391 of this argument, which means that the name must be valid for the
5392 lifetime of the returned <code>prepared_query</code> instance.</p>
5393
5394 <p>The second argument to the <code>prepare_query()</code> function
5395 is the query criteria. It has the same semantics as in the
5396 <code>query()</code> function discussed in <a href="#4.3">Section
5397 4.3, "Executing a Query"</a>. Similar to <code>query()</code>, we
5398 also have to explicitly specify the object type that we will be
5399 querying. For example:</p>
5400
5401 <pre class="cxx">
5402 typedef odb::query&lt;person> query;
5403 typedef odb::prepared_query&lt;person> prep_query;
5404
5405 prep_query pq (
5406 db.prepare_query&lt;person> ("person-age-query", query::age > 50));
5407 </pre>
5408
5409 <p>The result of executing the <code>prepare_query()</code> function is
5410 the <code>prepared_query</code> instance that represent the prepared
5411 query. It is best to view <code>prepared_query</code> as a handle to
5412 the underlying prepared statement. While we can make a copy of it or
5413 assign one <code>prepared_query</code> to another, the two instances
5414 will refer to the same prepared statement. Once the last instance of
5415 <code>prepared_query</code> referencing a specific prepared statement
5416 is destroyed, this statement is released. The <code>prepared_query</code>
5417 class template has the following interface:</p>
5418
5419 <pre class="cxx">
5420 namespace odb
5421 {
5422 template &lt;typename T>
5423 struct prepared_query
5424 {
5425 prepared_query ();
5426
5427 prepared_query (const prepared_query&amp;)
5428 prepared_query&amp; operator= (const prepared_query&amp;)
5429
5430 result&lt;T>
5431 execute (bool cache = true);
5432
5433 typename object_traits&lt;T>::pointer_type
5434 execute_one ();
5435
5436 bool
5437 execute_one (T&amp; object);
5438
5439 T
5440 execute_value ();
5441
5442 const char*
5443 name () const;
5444
5445 statement&amp;
5446 statement () const;
5447
5448 operator unspecified_bool_type () const;
5449 };
5450 }
5451 </pre>
5452
5453 <p>The default constructor creates an empty <code>prepared_query</code>
5454 instance, that is, an instance that does not reference a prepared
5455 statement and therefore cannot be executed. The only way to create
5456 a non-empty prepared query is by calling the <code>prepare_query()</code>
5457 function discussed above. To test whether the prepared query is empty,
5458 we can use the implicit conversion operator to a boolean type. For
5459 example:</p>
5460
5461 <pre class="cxx">
5462 prepared_query&lt;person> pq;
5463
5464 if (pq)
5465 {
5466 // Not empty.
5467 ...
5468 }
5469 </pre>
5470
5471 <p>The <code>execute()</code> function executes the query and returns
5472 the result instance. The <code>cache</code> argument indicates
5473 whether the result should be cached and has the same semantics
5474 as in the <code>query()</code> function. In fact, conceptually,
5475 <code>prepare_query()</code> and <code>execute()</code> are just
5476 the <code>query()</code> function split into two:
5477 <code>prepare_query()</code> takes the first
5478 <code>query()</code> argument (the query condition) while
5479 <code>execute()</code> takes the second (the cache flag). Note
5480 also that re-executing a prepared query invalidates the
5481 previous execution result, whether cached or uncached. </p>
5482
5483 <p>The <code>execute_one()</code> and <code>execute_value()</code>
5484 functions can be used as shortcuts to execute a query that is
5485 known to return at most one or exactly one object, respectively.
5486 The arguments and return values in these functions have the same
5487 semantics as in <code>query_one()</code> and <code>query_value()</code>.
5488 And similar to <code>execute()</code> above, <code>prepare_query()</code>
5489 and <code>execute_one/value()</code> can be seen as the
5490 <code>query_one/value()</code> function split into two:
5491 <code>prepare_query()</code> takes the first
5492 <code>query_one/value()</code> argument (the query condition) while
5493 <code>execute_one/value()</code> takes the second argument (if any)
5494 and returns the result. Note also that <code>execute_one/value()</code>
5495 never caches its result but invalidates the result of any previous
5496 <code>execute()</code> call on the same prepared query.</p>
5497
5498 <p>The <code>name()</code> function returns the prepared query name.
5499 This is the same name as was passed as the first argument in the
5500 <code>prepare_query()</code> call. The <code>statement()</code>
5501 function returns a reference to the underlying prepared statement.
5502 Note also that calling any of these functions on an empty
5503 <code>prepared_query</code> instance results in undefined behavior.</p>
5504
5505 <p>The simplest use-case for a prepared query is the need to
5506 execute the same query multiple times within a single transaction.
5507 Consider the following example that queries for people that are older
5508 than a number of different ages. This and subsequent code fragments
5509 are taken from the <code>prepared</code> example in the
5510 <code>odb-examples</code> package.</p>
5511
5512 <pre class="cxx">
5513 typedef odb::query&lt;person> query;
5514 typedef odb::prepared_query&lt;person> prep_query;
5515 typedef odb::result&lt;person> result;
5516
5517 transaction t (db.begin ());
5518
5519 unsigned short age;
5520 query q (query::age > query::_ref (age));
5521 prep_query pq (db.prepare_query&lt;person> ("person-age-query", q));
5522
5523 for (age = 90; age > 40; age -= 10)
5524 {
5525 result r (pq.execute ());
5526 ...
5527 }
5528
5529 t.commit ();
5530 </pre>
5531
5532 <p>Another scenario is the need to reuse the same query in multiple
5533 transactions that are executed at once. As was mentioned above,
5534 in this case we need to make sure that the prepared query and
5535 all the transactions use the same connection. Consider an
5536 alternative version of the above example that executes each
5537 query in a separate transaction:</p>
5538
5539 <pre class="cxx">
5540 connection_ptr conn (db.connection ());
5541
5542 unsigned short age;
5543 query q (query::age > query::_ref (age));
5544 prep_query pq (conn->prepare_query&lt;person> ("person-age-query", q));
5545
5546 for (age = 90; age > 40; age -= 10)
5547 {
5548 transaction t (conn->begin ());
5549
5550 result r (pq.execute ());
5551 ...
5552
5553 t.commit ();
5554 }
5555 </pre>
5556
5557
5558 <p>Note that with this approach we hold on to the database connection
5559 until all the transactions involving the prepared query are
5560 executed. In particular, this means that while we are busy, the
5561 connection cannot be reused by another thread. Therefore, this
5562 approach is only recommended if all the transactions are executed
5563 close to each other. Also note that an uncached (see below)
5564 prepared query is invalidated once we release the connection
5565 on which it was prepared.</p>
5566
5567 <p>If we need to reuse a prepared query in transactions that are
5568 executed at various times, potentially in different threads, then
5569 the recommended approach is to cache the prepared query on the
5570 connection. To support this functionality the <code>odb::database</code>
5571 and <code>odb::connection</code> classes provide the following
5572 function templates. Similar to <code>prepare_query()</code>,
5573 the <code>odb::database</code> versions of the below
5574 functions call the corresponding <code>odb::connection</code>
5575 versions using the currently active transaction to resolve
5576 the connection.</p>
5577
5578 <pre class="cxx">
5579 template &lt;typename T>
5580 void
5581 cache_query (const prepared_query&lt;T>&amp;);
5582
5583 template &lt;typename T, typename P>
5584 void
5585 cache_query (const prepared_query&lt;T>&amp;,
5586 std::[auto|unique]_ptr&lt;P> params);
5587
5588 template &lt;typename T>
5589 prepared_query&lt;T>
5590 lookup_query (const char* name) const;
5591
5592 template &lt;typename T, typename P>
5593 prepared_query&lt;T>
5594 lookup_query (const char* name, P*&amp; params) const;
5595 </pre>
5596
5597 <p>The <code>cache_query()</code> function caches the passed prepared
5598 query on the connection. The second overloaded version of
5599 <code>cache_query()</code> also takes a pointer to the
5600 by-reference query parameters. In C++98/03 it should be
5601 <code>std::auto_ptr</code> while in C++11 <code>std::auto_ptr</code>
5602 or <code>std::unique_ptr</code> can be used. The
5603 <code>cache_query()</code> function assumes ownership of the
5604 passed <code>params</code> argument. If a prepared query
5605 with the same name is already cached on this connection,
5606 then the <code>odb::prepared_already_cached</code> exception
5607 is thrown.</p>
5608
5609 <p>The <code>lookup_query()</code> function looks up a previously
5610 cached prepared query given its name. The second overloaded
5611 version of <code>lookup_query()</code> also returns a pointer
5612 to the by-reference query parameters. If a prepared query
5613 with this name has not been cached, then an empty
5614 <code>prepared_query</code> instance is returned. If a
5615 prepared query with this name has been cached but either
5616 the object type or the parameters type does not match
5617 that which was cached, then the <code>odb::prepared_type_mismatch</code>
5618 exception is thrown.</p>
5619
5620 <p>As a first example of the prepared query cache functionality,
5621 consider the case that does not use any by-reference parameters:</p>
5622
5623 <pre class="cxx">
5624 for (unsigned short i (0); i &lt; 5; ++i)
5625 {
5626 transaction t (db.begin ());
5627
5628 prep_query pq (db.lookup_query&lt;person> ("person-age-query"));
5629
5630 if (!pq)
5631 {
5632 pq = db.prepare_query&lt;person> (
5633 "person-val-age-query", query::age > 50);
5634 db.cache_query (pq);
5635 }
5636
5637 result r (pq.execute ());
5638 ...
5639
5640 t.commit ();
5641
5642 // Do some other work.
5643 //
5644 ...
5645 }
5646 </pre>
5647
5648 <p>The following example shows how to do the same but for a query that
5649 includes by-reference parameters. In this case the parameters are
5650 cached together with the prepared query.</p>
5651
5652 <pre class="cxx">
5653 for (unsigned short age (90); age > 40; age -= 10)
5654 {
5655 transaction t (db.begin ());
5656
5657 unsigned short* age_param;
5658 prep_query pq (
5659 db.lookup_query&lt;person> ("person-age-query", age_param));
5660
5661 if (!pq)
5662 {
5663 auto_ptr&lt;unsigned short> p (new unsigned short);
5664 age_param = p.get ();
5665 query q (query::age > query::_ref (*age_param));
5666 pq = db.prepare_query&lt;person> ("person-age-query", q);
5667 db.cache_query (pq, p); // Assumes ownership of p.
5668 }
5669
5670 *age_param = age; // Initialize the parameter.
5671 result r (pq.execute ());
5672 ...
5673
5674 t.commit ();
5675
5676 // Do some other work.
5677 //
5678 ...
5679 }
5680 </pre>
5681
5682 <p>As is evident from the above examples, when we use a prepared
5683 query cache, each transaction that executes a query must also
5684 include code that prepares and caches this query if it hasn't already
5685 been done. If a prepared query is used in a single place in the
5686 application, then this is normally not an issue since all the
5687 relevant code is kept in one place. However, if the same query
5688 is used in several different places in the application, then
5689 we may end up duplicating the same preparation and caching
5690 code, which makes it hard to maintain.</p>
5691
5692 <p>To resolve this issue ODB allows us to register a prepared
5693 query factory that will be called to prepare and cache a
5694 query during the call to <code>lookup_query()</code>. To
5695 register a factory we use the <code>database::query_factory()</code>
5696 function. In C++98/03 it has the following signature:</p>
5697
5698 <pre class="cxx">
5699 void
5700 query_factory (const char* name,
5701 void (*factory) (const char* name, connection&amp;));
5702 </pre>
5703
5704 <p>While in C++11 it uses the <code>std::function</code> class
5705 template:</p>
5706
5707 <pre class="cxx">
5708 void
5709 query_factory (const char* name,
5710 std::function&lt;void (const char* name, connection&amp;)>);
5711 </pre>
5712
5713 <p>The first argument to the <code>query_factory()</code> function is
5714 the prepared query name that this factory will be called to prepare
5715 and cache. An empty name is treated as a fallback wildcard factory
5716 that is capable of preparing any query. The second argument is the
5717 factory function or, in C++11, function object or lambda.</p>
5718
5719 <p>The example fragment shows how we can use the prepared query
5720 factory:</p>
5721
5722 <pre class="cxx">
5723 struct params
5724 {
5725 unsigned short age;
5726 string first;
5727 };
5728
5729 static void
5730 query_factory (const char* name, connection&amp; c)
5731 {
5732 auto_ptr&lt;params> p (new params);
5733 query q (query::age > query::_ref (p->age) &amp;&amp;
5734 query::first == query::_ref (p->first));
5735 prep_query pq (c.prepare_query&lt;person> (name, q));
5736 c.cache_query (pq, p);
5737 }
5738
5739 db.query_factory ("person-age-name-query", &amp;query_factory);
5740
5741 for (unsigned short age (90); age > 40; age -= 10)
5742 {
5743 transaction t (db.begin ());
5744
5745 params* p;
5746 prep_query pq (db.lookup_query&lt;person> ("person-age-name-query", p));
5747 assert (pq);
5748
5749 p->age = age;
5750 p->first = "John";
5751 result r (pq.execute ());
5752 ...
5753
5754 t.commit ();
5755 }
5756 </pre>
5757
5758 <p>In C++11 we could have instead used a lambda function as well as
5759 <code>unique_ptr</code> rather than <code>auto_ptr</code>:</p>
5760
5761 <pre>
5762 db.query_factory (
5763 "person-age-name-query",
5764 [] (const char* name, connection&amp; c)
5765 {
5766 unique_ptr&lt;params> p (new params);
5767 query q (query::age > query::_ref (p->age) &amp;&amp;
5768 query::first == query::_ref (p->first));
5769 prep_query pq (c.prepare_query&lt;person> (name, q));
5770 c.cache_query (pq, std::move (p));
5771 });
5772 </pre>
5773
5774 <!-- CHAPTER -->
5775
5776 <hr class="page-break"/>
5777 <h1><a name="5">5 Containers</a></h1>
5778
5779 <p>The ODB runtime library provides built-in persistence support for all the
5780 commonly used standard C++98/03 containers, namely,
5781 <code>std::vector</code>, <code>std::list</code>, <code>std::deque</code>,
5782 <code>std::set</code>, <code>std::multiset</code>, <code>std::map</code>, and
5783 <code>std::multimap</code> as well as C++11 <code>std::array</code>,
5784 <code>std::forward_list</code>, <code>std::unordered_set</code>,
5785 <code>std::unordered_multiset</code>, <code>std::unordered_map</code>,
5786 and <code>std::unordered_multimap</code>.
5787 Plus, ODB profile libraries, that are
5788 available for commonly used frameworks and libraries (such as Boost and
5789 Qt), provide persistence support for containers found in these frameworks
5790 and libraries (<a href="#III">Part III, "Profiles"</a>). Both the
5791 ODB runtime library and profile libraries also provide a number of
5792 change-tracking container equivalents which can be used to minimize
5793 the number of database operations necessary to synchronize the container
5794 state with the database (<a href="#5.4">Section 5.4, "Change-Tracking
5795 Containers"</a>). It is also easy to persist custom container types
5796 as discussed later in <a href="#5.5">Section 5.5, "Using Custom
5797 Containers"</a>.</p>
5798
5799 <p>We don't need to do anything special to declare a member of a
5800 container type in a persistent class. For example:</p>
5801
5802 <pre class="cxx">
5803 #pragma db object
5804 class person
5805 {
5806 ...
5807 private:
5808 std::vector&lt;std::string> nicknames_;
5809 ...
5810 };
5811 </pre>
5812
5813 <p>The complete version of the above code fragment and the other code
5814 samples presented in this chapter can be found in the <code>container</code>
5815 example in the <code>odb-examples</code> package.</p>
5816
5817 <p>A data member in a persistent class that is of a container type
5818 behaves like a value type. That is, when an object is made persistent,
5819 the elements of the container are stored in the database. Similarly,
5820 when a persistent object is loaded from the database, the contents
5821 of the container are automatically loaded as well. A data member
5822 of a container type can also use a smart pointer, as discussed
5823 in <a href="#7.3">Section 7.3, "Pointers and <code>NULL</code>
5824 Value Semantics"</a>.</p>
5825
5826 <p>While an ordinary member is mapped to one or more columns in the
5827 object's table, a member of a container type is mapped to a separate
5828 table. The exact schema of such a table depends on the kind of
5829 container. ODB defines the following container kinds: ordered,
5830 set, multiset, map, and multimap. The container kinds and the
5831 contents of the tables to which they are mapped are discussed
5832 in detail in the following sections.</p>
5833
5834 <p>Containers in ODB can contain simple value types (<a href="#7.1">Section
5835 7.1, "Simple Value Types"</a>), composite value types
5836 (<a href="#7.2">Section 7.2, "Composite Value Types"</a>), and pointers
5837 to objects (<a href="#6">Chapter 6, "Relationships"</a>). Containers of
5838 containers, either directly or indirectly via a composite value
5839 type, are not allowed. A key in a map or multimap container can
5840 be a simple or composite value type but not a pointer to an object.
5841 An index in the ordered container should be a simple integer value
5842 type.</p>
5843
5844 <p>The value type in the ordered, set, and map containers as well as
5845 the key type in the map containers should be default-constructible.
5846 The default constructor in these types can be made private in which
5847 case the <code>odb::access</code> class should be made a friend of
5848 the value or key type. For example:</p>
5849
5850 <pre class="cxx">
5851 #pragma db value
5852 class name
5853 {
5854 public:
5855 name (const std::string&amp;, const std::string&amp;);
5856 ...
5857 private:
5858 friend class odb::access;
5859 name ();
5860 ...
5861 };
5862
5863 #pragma db object
5864 class person
5865 {
5866 ...
5867 private:
5868 std::vector&lt;name> aliases_;
5869 ...
5870 };
5871 </pre>
5872
5873
5874 <h2><a name="5.1">5.1 Ordered Containers</a></h2>
5875
5876 <p>In ODB an ordered container is any container that maintains (explicitly
5877 or implicitly) an order of its elements in the form of an integer index.
5878 Standard C++ containers that are ordered include <code>std::vector</code>
5879 <code>std::list</code>, and <code>std::deque</code> as well as C++11 <code>std::array</code> and
5880 <code>std::forward_list</code>. While elements in <code>std::set</code>
5881 are also kept in a specific order, this order is not based on an
5882 integer index but rather on the relationship between elements. As
5883 a result, <code>std::set</code> is not considered an ordered
5884 container for the purpose of persistence.</p>
5885
5886 <p>The database table for an ordered container consists of at least
5887 three columns. The first column contains the object id of a
5888 persistent class instance of which the container is a member.
5889 The second column contains the element index within a container.
5890 And the last column contains the element value. If the object
5891 id or element value are composite, then, instead of a single
5892 column, they can occupy multiple columns. For an ordered
5893 container table the ODB compiler also defines two indexes:
5894 one for the object id column(s) and the other for the index
5895 column. Refer to <a href="#14.7">Section 14.7, "Index Definition
5896 Pragmas"</a> for more information on how to customize these
5897 indexes.</p>
5898
5899 <p>Consider the following persistent object as an example:</p>
5900
5901 <pre class="cxx">
5902 #pragma db object
5903 class person
5904 {
5905 ...
5906 private:
5907 #pragma db id auto
5908 unsigned long id_;
5909
5910 std::vector&lt;std::string> nicknames_;
5911 ...
5912 };
5913 </pre>
5914
5915 <p>The resulting database table (called <code>person_nicknames</code>) will
5916 contain the object id column of type <code>unsigned&nbsp;long</code>
5917 (called <code>object_id</code>), the index column of an integer type
5918 (called <code>index</code>), and the value column of type
5919 <code>std::string</code> (called <code>value</code>).</p>
5920
5921 <p>A number of ODB pragmas allow us to customize the table name, column
5922 names, and native database types of an ordered container both, on
5923 the per-container and per-member basis. For more information on
5924 these pragmas, refer to <a href="#14">Chapter 14, "ODB Pragma
5925 Language"</a>. The following example shows some of the possible
5926 customizations:</p>
5927
5928 <pre class="cxx">
5929 #pragma db object
5930 class person
5931 {
5932 ...
5933 private:
5934 #pragma db table("nicknames") \
5935 id_column("person_id") \
5936 index_type("SMALLINT UNSIGNED") \
5937 index_column("nickname_number") \
5938 value_type("VARCHAR(255)") \
5939 value_column("nickname")
5940 std::vector&lt;std::string> nicknames_;
5941 ...
5942 };
5943 </pre>
5944
5945 <p>While the C++ container used in a persistent class may be ordered,
5946 sometimes we may wish to store such a container in the database without
5947 the order information. In the example above, for instance, the order
5948 of person's nicknames is probably not important. To instruct the ODB
5949 compiler to ignore the order in ordered containers we can use the
5950 <code>db&nbsp;unordered</code> pragma (<a href="#14.3.9">Section 14.3.9,
5951 "<code>unordered</code>"</a>, <a href="#14.4.19">Section 14.4.19,
5952 "<code>unordered</code>"</a>). For example:</p>
5953
5954 <pre class="cxx">
5955 #pragma db object
5956 class person
5957 {
5958 ...
5959 private:
5960 #pragma db unordered
5961 std::vector&lt;std::string> nicknames_;
5962 ...
5963 };
5964 </pre>
5965
5966 <p>The table for an ordered container that is marked unordered won't
5967 have the index column and the order in which elements are retrieved
5968 from the database may not be the same as the order in which they
5969 were stored.</p>
5970
5971 <h2><a name="5.2">5.2 Set and Multiset Containers</a></h2>
5972
5973 <p>In ODB set and multiset containers (referred to as just set
5974 containers) are associative containers that contain elements
5975 based on some relationship between them. A set container may
5976 or may not guarantee a particular order of the elements that
5977 it stores. Standard C++ containers that are considered set
5978 containers for the purpose of persistence include
5979 <code>std::set</code> and <code>std::multiset</code> as well
5980 as C++11 <code>std::unordered_set</code> and
5981 <code>std::unordered_multiset</code>.</p>
5982
5983 <p>The database table for a set container consists of at least
5984 two columns. The first column contains the object id of a
5985 persistent class instance of which the container is a member.
5986 And the second column contains the element value. If the object
5987 id or element value are composite, then, instead of a single
5988 column, they can occupy multiple columns. ODB compiler also
5989 defines an index on a set container table for the object id
5990 column(s). Refer to <a href="#14.7">Section 14.7, "Index Definition
5991 Pragmas"</a> for more information on how to customize this
5992 index.</p>
5993
5994 <p>Consider the following persistent object as an example:</p>
5995
5996 <pre class="cxx">
5997 #pragma db object
5998 class person
5999 {
6000 ...
6001 private:
6002 #pragma db id auto
6003 unsigned long id_;
6004
6005 std::set&lt;std::string> emails_;
6006 ...
6007 };
6008 </pre>
6009
6010 <p>The resulting database table (called <code>person_emails</code>) will
6011 contain the object id column of type <code>unsigned&nbsp;long</code>
6012 (called <code>object_id</code>) and the value column of type
6013 <code>std::string</code> (called <code>value</code>).</p>
6014
6015 <p>A number of ODB pragmas allow us to customize the table name,
6016 column names, and native database types of a set container, both on
6017 the per-container and per-member basis. For more information on
6018 these pragmas, refer to <a href="#14">Chapter 14, "ODB Pragma
6019 Language"</a>. The following example shows some of the possible
6020 customizations:</p>
6021
6022 <pre class="cxx">
6023 #pragma db object
6024 class person
6025 {
6026 ...
6027 private:
6028 #pragma db table("emails") \
6029 id_column("person_id") \
6030 value_type("VARCHAR(255)") \
6031 value_column("email")
6032 std::set&lt;std::string> emails_;
6033 ...
6034 };
6035 </pre>
6036
6037 <h2><a name="5.3">5.3 Map and Multimap Containers</a></h2>
6038
6039 <p>In ODB map and multimap containers (referred to as just map
6040 containers) are associative containers that contain key-value
6041 elements based on some relationship between keys. A map container
6042 may or may not guarantee a particular order of the elements that
6043 it stores. Standard C++ containers that are considered map
6044 containers for the purpose of persistence include
6045 <code>std::map</code> and <code>std::multimap</code> as well
6046 as C++11 <code>std::unordered_map</code> and
6047 <code>std::unordered_multimap</code>.</p>
6048
6049 <p>The database table for a map container consists of at least
6050 three columns. The first column contains the object id of a
6051 persistent class instance of which the container is a member.
6052 The second column contains the element key. And the last column
6053 contains the element value. If the object id, element key, or
6054 element value are composite, then instead of a single column
6055 they can occupy multiple columns. ODB compiler also
6056 defines an index on a map container table for the object id
6057 column(s). Refer to <a href="#14.7">Section 14.7, "Index Definition
6058 Pragmas"</a> for more information on how to customize this
6059 index.</p>
6060
6061 <p>Consider the following persistent object as an example:</p>
6062
6063 <pre class="cxx">
6064 #pragma db object
6065 class person
6066 {
6067 ...
6068 private:
6069 #pragma db id auto
6070 unsigned long id_;
6071
6072 std::map&lt;unsigned short, float> age_weight_map_;
6073 ...
6074 };
6075 </pre>
6076
6077 <p>The resulting database table (called <code>person_age_weight_map</code>)
6078 will contain the object id column of type <code>unsigned&nbsp;long</code>
6079 (called <code>object_id</code>), the key column of type
6080 <code>unsigned short</code> (called <code>key</code>), and the value
6081 column of type <code>float</code> (called <code>value</code>).</p>
6082
6083 <p>A number of ODB pragmas allow us to customize the table name,
6084 column names, and native database types of a map container, both on
6085 the per-container and per-member basis. For more information on
6086 these pragmas, refer to <a href="#14">Chapter 14, "ODB Pragma
6087 Language"</a>. The following example shows some of the possible
6088 customizations:</p>
6089
6090 <pre class="cxx">
6091 #pragma db object
6092 class person
6093 {
6094 ...
6095 private:
6096 #pragma db table("weight_map") \
6097 id_column("person_id") \
6098 key_type("INT UNSIGNED") \
6099 key_column("age") \
6100 value_type("DOUBLE") \
6101 value_column("weight")
6102 std::map&lt;unsigned short, float> age_weight_map_;
6103 ...
6104 };
6105 </pre>
6106
6107 <h2><a name="5.4">5.4 Change-Tracking Containers</a></h2>
6108
6109 <p>When a persistent object containing one of the standard containers
6110 is updated in the database, ODB has no knowledge of which elements
6111 were inserted, erased, or modified. As a result, ODB has no choice
6112 but to assume the whole container has changed and update the state
6113 of every single element. This can result in a significant overhead
6114 if a container contains a large number of elements and we only
6115 changed a small subset of them.</p>
6116
6117 <p>To eliminate this overhead, ODB provides a notion of <em>change-tracking
6118 containers</em>. A change-tracking container, besides containing
6119 its elements, just like an ordinary container, also includes the
6120 change state for each element. When it is time to update such a
6121 container in the database, ODB can use this change information to
6122 perform a minimum number of database operations necessary to
6123 synchronize the container state with the database.</p>
6124
6125 <p>The current version of the ODB runtime library provides a change-tracking
6126 equivalent of <code>std::vector</code> (<a href="#5.4.1">Section 5.4.1,
6127 "Change-Tracking <code>vector</code>"</a>) with support for other
6128 standard container equivalents planned for future releases. ODB
6129 profile libraries also provide change-tracking equivalents for some
6130 containers found in the corresponding frameworks and libraries
6131 (<a href="#III">Part III, "Profiles"</a>).</p>
6132
6133 <p>A change-tracking container equivalent can normally be used as a drop-in
6134 replacement for an ordinary container except for a few minor
6135 interface differences (discussed in the corresponding sub-sections).
6136 In particular, we don't need to do anything extra to effect
6137 change tracking. ODB will automatically start, stop, and reset
6138 change tracking when necessary. The following example illustrates
6139 this point using <code>odb::vector</code> as a replacement for
6140 <code>std::vector</code>.</p>
6141
6142 <pre class="cxx">
6143 #pragma db object
6144 class person
6145 {
6146 ...
6147
6148 odb::vector&lt;std::string> names;
6149 };
6150
6151 person p; // No change tracking (not persistent).
6152 p.names.push_back ("John Doe");
6153
6154 {
6155 transaction t (db.begin ());
6156 db.persist (p); // Start change tracking (persistent).
6157 t.commit ();
6158 }
6159
6160 p.names.push_back ("Johnny Doo");
6161
6162 {
6163 transaction t (db.begin ());
6164 db.update (p); // One INSERT; reset change state.
6165 t.commit ();
6166 }
6167
6168 p.names.modify (0) = "Doe, John"; // Instead of operator[].
6169 p.names.pop_back ();
6170
6171 {
6172 transaction t (db.begin ());
6173 db.update (p); // One UPDATE, one DELETE; reset change state.
6174 t.commit ();
6175 }
6176
6177 {
6178 transaction t (db.begin ());
6179 auto_ptr&lt;person> p1 (db.load&lt;person> (...)); // Start change tracking.
6180 p1->names.insert (p1->names.begin (), "Joe Do");
6181 db.update (*p1); // One UPDATE, one INSERT; reset change state.
6182 t.commit ();
6183 }
6184
6185 {
6186 transaction t (db.begin ());
6187 db.erase (p); // One DELETE; stop change tracking (not persistent).
6188 t.commit ();
6189 }
6190 </pre>
6191
6192 <p>One interesting aspect of change tracking is what happens when a
6193 transaction that contains an update is later rolled back. In this
6194 case, while the change-tracking container has reset the change
6195 state (after update), actual changes were not committed to the
6196 database. Change-tracking containers handle this case by
6197 automatically registering a rollback callback and then, if it is
6198 called, marking the container as "completely changed". In this
6199 state, the container no longer tracks individual element changes
6200 and, when updated, falls back to the complete state update, just
6201 like an ordinary container. The following example illustrates
6202 this point:</p>
6203
6204 <pre class="cxx">
6205 person p;
6206 p.names.push_back ("John Doe");
6207
6208 {
6209 transaction t (db.begin ());
6210 db.persist (p); // Start change tracking (persistent).
6211 t.commit ();
6212 }
6213
6214 p.names.push_back ("Johnny Doo");
6215
6216 for (;;)
6217 {
6218 try
6219 {
6220 transaction t (db.begin ());
6221
6222 // First try: one INSERT.
6223 // Next try: one DELETE, two INSERTs.
6224 //
6225 db.update (p); // Reset change state.
6226
6227 t.commit (); // If throws (rollback), mark as completely changed.
6228 break;
6229 }
6230 catch (const odb::recoverable&amp;)
6231 {
6232 continue;
6233 }
6234 }
6235 </pre>
6236
6237 <p>For the interaction of change-tracking containers with change-updated
6238 object sections, refer to <a href="#9.4">Section 9.4, "Sections and
6239 Change-Tracking Containers"</a>.</p>
6240
6241 <h3><a name="5.4.1">5.4.1 Change-Tracking <code>vector</code></a></h3>
6242
6243 <p>Class template <code>odb::vector</code>, defined in
6244 <code>&lt;odb/vector.hxx></code>, is a change-tracking
6245 equivalent for <code>std::vector</code>. It
6246 is implemented in terms of <code>std::vector</code> and is
6247 implicit-convertible to and implicit-constructible from
6248 <code>const std::vector&amp;</code>. In particular, this
6249 means that we can use <code>odb::vector</code> instance
6250 anywhere <code>const std::vector&amp;</code> is
6251 expected. In addition, <code>odb::vector</code> constant
6252 iterator (<code>const_iterator</code>) is the same type as
6253 that of <code>std::vector</code>.</p>
6254
6255 <p><code>odb::vector</code> incurs 2-bit per element overhead
6256 in order to store the change state. It cannot
6257 be stored unordered in the database (<a href="#14.4.19">Section
6258 14.4.19 "<code>unordered</code>"</a>) but can be used as an inverse
6259 side of a relationship (<a href="#6.2">6.2 "Bidirectional
6260 Relationships"</a>). In this case, no change tracking is performed
6261 since no state for such a container is stored in the database.</p>
6262
6263 <p>The number of database operations required to update the state
6264 of <code>odb::vector</code> corresponds well to the complexity
6265 of <code>std::vector</code> functions. In particular, adding or
6266 removing an element from the back of the vector (for example,
6267 with <code>push_back()</code> and <code>pop_back()</code>),
6268 requires only a single database statement execution. In contrast,
6269 inserting or erasing an element somewhere in the middle of the
6270 vector will require a database statement for every element that
6271 follows it.</p>
6272
6273 <p><code>odb::vector</code> replicates most of the <code>std::vector</code>
6274 interface as defined in both C++98/03 and C++11 standards. However,
6275 functions and operators that provide direct write access to
6276 the elements had to be altered or disabled in order to support
6277 change tracking. Additional functions used to interface with
6278 <code>std::vector</code> and to control the change tracking state
6279 were also added. The following listing summarizes the differences
6280 between the <code>odb::vector</code> and <code>std::vector</code>
6281 interfaces. Any <code>std::vector</code> function or operator
6282 not mentioned in this listing has exactly the same signature
6283 and semantics in <code>odb::vector</code>. Functions and
6284 operators that were disabled are shown as commented out and
6285 are followed by functions/operators that replace them.</p>
6286
6287 <pre class="cxx">
6288 namespace odb
6289 {
6290 template &lt;class T, class A = std::allocator&lt;T> >
6291 class vector
6292 {
6293 ...
6294
6295 // Element access.
6296 //
6297
6298 //reference operator[] (size_type);
6299 reference modify (size_type);
6300
6301 //reference at (size_type);
6302 reference modify_at (size_type);
6303
6304 //reference front ();
6305 reference modify_front ();
6306
6307 //reference back ();
6308 reference modify_back ();
6309
6310 //T* data () noexcept;
6311 T* modify_data () noexcept; // C++11 only.
6312
6313 // Iterators.
6314 //
6315 typedef typename std::vector&lt;T, A>::const_iterator const_iterator;
6316
6317 class iterator
6318 {
6319 ...
6320
6321 // Element Access.
6322 //
6323
6324 //reference operator* () const;
6325 const_reference operator* () const;
6326 reference modify () const;
6327
6328 //pointer operator-> () const;
6329 const_pointer operator-> () const;
6330
6331 //reference operator[] (difference_type);
6332 const_reference operator[] (difference_type);
6333 reference modify (difference_type) const;
6334
6335 // Interfacing with std::vector::iterator.
6336 //
6337 typename std::vector&lt;T, A>::iterator base () const;
6338 };
6339
6340 // Return std::vector iterators. The begin() functions mark
6341 // all the elements as modified.
6342 //
6343 typename std::vector&lt;T, A>::iterator mbegin ();
6344 typename std::vector&lt;T, A>::iterator mend ();
6345 typename std::vector&lt;T, A>::reverse_iterator mrbegin ();
6346 typename std::vector&lt;T, A>::reverse_iterator mrend ();
6347
6348 // Interfacing with std::vector.
6349 //
6350 vector (const std::vector&lt;T, A>&amp;);
6351 vector (std::vector&lt;T, A>&amp;&amp;); // C++11 only.
6352
6353 vector&amp; operator= (const std::vector&lt;T, A>&amp;);
6354 vector&amp; operator= (std::vector&lt;T, A>&amp;&amp;); // C++11 only.
6355
6356 operator const std::vector&lt;T, A>&amp; () const;
6357 std::vector&lt;T, A>&amp; base ();
6358 const std::vector&lt;T, A>&amp; base ();
6359
6360 // Change tracking.
6361 //
6362 bool _tracking () const;
6363 void _start () const;
6364 void _stop () const;
6365 void _arm (transaction&amp;) const;
6366 };
6367 }
6368 </pre>
6369
6370 <p>The following example highlights some of the differences between
6371 the two interfaces. <code>std::vector</code> versions are commented
6372 out.</p>
6373
6374 <pre class="cxx">
6375 #include &lt;vector>
6376 #include &lt;odb/vector.hxx>
6377
6378 void f (const std::vector&lt;int>&amp;);
6379
6380 odb::vector&lt;int> v ({1, 2, 3});
6381
6382 f (v); // Ok, implicit conversion.
6383
6384 if (v[1] == 2) // Ok, const access.
6385 //v[1]++;
6386 v.modify (1)++;
6387
6388 //v.back () = 4;
6389 v.modify_back () = 4;
6390
6391 for (auto i (v.begin ()); i != v.end (); ++i)
6392 {
6393 if (*i != 0) // Ok, const access.
6394 //*i += 10;
6395 i.modify () += 10;
6396 }
6397
6398 std::sort (v.mbegin (), v.mend ());
6399 </pre>
6400
6401 <p>Note also the subtle difference between copy/move construction
6402 and copy/move assignment of <code>odb::vector</code> instances.
6403 While copy/move constructor will copy/move both the elements as
6404 well as their change state, in contrast, assignment is tracked
6405 as any other change to the vector content.</p>
6406
6407 <h2><a name="5.5">5.5 Using Custom Containers</a></h2>
6408
6409 <p>While the ODB runtime and profile libraries provide support for
6410 a wide range of containers, it is also easy to persist custom
6411 container types or make a change-tracking version out of one.</p>
6412
6413 <p>To achieve this you will need to implement the
6414 <code>container_traits</code> class template specialization for
6415 your container. First, determine the container kind (ordered, set,
6416 multiset, map, or multimap) for your container type. Then use a
6417 specialization for one of the standard C++ containers found in
6418 the common ODB runtime library (<code>libodb</code>) as a base
6419 for your own implementation.</p>
6420
6421 <p>Once the container traits specialization is ready for your container,
6422 you will need to include it into the ODB compilation process using
6423 the <code>--odb-epilogue</code> option and into the generated header
6424 files with the <code>--hxx-prologue</code> option. As an example,
6425 suppose we have a hash table container for which we have the traits
6426 specialization implemented in the <code>hashtable-traits.hxx</code>
6427 file. Then, we can create an ODB compiler options file for this
6428 container and save it to <code>hashtable.options</code>:</p>
6429
6430 <pre>
6431 # Options file for the hash table container.
6432 #
6433 --odb-epilogue '#include "hashtable-traits.hxx"'
6434 --hxx-prologue '#include "hashtable-traits.hxx"'
6435 </pre>
6436
6437 <p>Now, whenever we compile a header file that uses the hashtable
6438 container, we can specify the following command line option to
6439 make sure it is recognized by the ODB compiler as a container
6440 and the traits file is included in the generated code:</p>
6441
6442 <pre>
6443 --options-file hashtable.options
6444 </pre>
6445
6446
6447 <!-- CHAPTER -->
6448
6449
6450 <hr class="page-break"/>
6451 <h1><a name="6">6 Relationships</a></h1>
6452
6453 <p>Relationships between persistent objects are expressed with pointers or
6454 containers of pointers. The ODB runtime library provides built-in support
6455 for <code>shared_ptr</code>/<code>weak_ptr</code> (TR1 or C++11),
6456 <code>std::unique_ptr</code> (C++11),
6457 <code>std::auto_ptr</code>, and raw pointers. Plus, ODB profile
6458 libraries, that are available for commonly used frameworks and libraries
6459 (such as Boost and Qt), provide support for smart pointers found in these
6460 frameworks and libraries (<a href="#III">Part III, "Profiles"</a>). It is
6461 also easy to add support for a custom smart pointer as discussed later
6462 in <a href="#6.5"> Section 6.5, "Using Custom Smart Pointers"</a>. Any
6463 supported smart pointer can be used in a data member as long as it can be
6464 explicitly constructed from the canonical object pointer
6465 (<a href="#3.3">Section 3.3, "Object and View Pointers"</a>). For
6466 example, we can use <code>weak_ptr</code> if the object pointer
6467 is <code>shared_ptr</code>.</p>
6468
6469 <p>When an object containing a pointer to another object is loaded,
6470 the pointed-to object is loaded as well. In some situations this
6471 eager loading of the relationships is undesirable since it
6472 can lead to a large number of otherwise unused objects being
6473 instantiated from the database. To support finer control
6474 over relationships loading, the ODB runtime and profile
6475 libraries provide the so-called <em>lazy</em> versions of
6476 the supported pointers. An object pointed-to by a lazy pointer
6477 is not loaded automatically when the containing object is loaded.
6478 Instead, we have to explicitly request the instantiation of the
6479 pointed-to object. Lazy pointers are discussed in
6480 detail in <a href="#6.4">Section 6.4, "Lazy Pointers"</a>.</p>
6481
6482 <p>As a simple example, consider the following employee-employer
6483 relationship. Code examples presented in this chapter
6484 will use the <code>shared_ptr</code> and <code>weak_ptr</code>
6485 smart pointers from the TR1 (<code>std::tr1</code>) namespace.</p>
6486
6487 <pre class="cxx">
6488 #pragma db object
6489 class employer
6490 {
6491 ...
6492
6493 #pragma db id
6494 std::string name_;
6495 };
6496
6497 #pragma db object
6498 class employee
6499 {
6500 ...
6501
6502 #pragma db id
6503 unsigned long id_;
6504
6505 std::string first_name_;
6506 std::string last_name_;
6507
6508 shared_ptr&lt;employer> employer_;
6509 };
6510 </pre>
6511
6512 <p>By default, an object pointer can be <code>NULL</code>. To
6513 specify that a pointer always points to a valid object we can
6514 use the <code>not_null</code> pragma (<a href="#14.4.6">Section
6515 14.4.6, "<code>null</code>/<code>not_null</code>"</a>) for
6516 single object pointers and the <code>value_not_null</code> pragma
6517 (<a href="#14.4.28">Section
6518 14.4.28, "<code>value_null</code>/<code>value_not_null</code>"</a>)
6519 for containers of object pointers. For example:</p>
6520
6521 <pre class="cxx">
6522 #pragma db object
6523 class employee
6524 {
6525 ...
6526
6527 #pragma db not_null
6528 shared_ptr&lt;employer> current_employer_;
6529
6530 #pragma db value_not_null
6531 std::vector&lt;shared_ptr&lt;employer> > previous_employers_;
6532 };
6533 </pre>
6534
6535 <p>In this case, if we call either <code>persist()</code> or
6536 <code>update()</code> database function on the
6537 <code>employee</code> object and the <code>current_employer_</code>
6538 pointer or one of the pointers stored in the
6539 <code>previous_employers_</code> container is <code>NULL</code>,
6540 then the <code>odb::null_pointer</code> exception will be thrown.</p>
6541
6542 <p>We don't need to do anything special to establish or navigate a
6543 relationship between two persistent objects, as shown in the
6544 following code fragment:</p>
6545
6546 <pre class="cxx">
6547 // Create an employer and a few employees.
6548 //
6549 unsigned long john_id, jane_id;
6550 {
6551 shared_ptr&lt;employer> er (new employer ("Example Inc"));
6552 shared_ptr&lt;employee> john (new employee ("John", "Doe"));
6553 shared_ptr&lt;employee> jane (new employee ("Jane", "Doe"));
6554
6555 john->employer_ = er;
6556 jane->employer_ = er;
6557
6558 transaction t (db.begin ());
6559
6560 db.persist (er);
6561 john_id = db.persist (john);
6562 jane_id = db.persist (jane);
6563
6564 t.commit ();
6565 }
6566
6567 // Load a few employee objects and print their employer.
6568 //
6569 {
6570 session s;
6571 transaction t (db.begin ());
6572
6573 shared_ptr&lt;employee> john (db.load&lt;employee> (john_id));
6574 shared_ptr&lt;employee> jane (db.load&lt;employee> (jane_id));
6575
6576 cout &lt;&lt; john->employer_->name_ &lt;&lt; endl;
6577 cout &lt;&lt; jane->employer_->name_ &lt;&lt; endl;
6578
6579 t.commit ();
6580 }
6581 </pre>
6582
6583 <p>The only notable line in the above code is the creation of a
6584 session before the second transaction starts. As discussed in
6585 <a href="#11">Chapter 11, "Session"</a>, a session acts as a cache
6586 of persistent objects.
6587 By creating a session before loading the <code>employee</code>
6588 objects we make sure that their <code>employer_</code> pointers
6589 point to the same <code>employer</code> object. Without a
6590 session, each <code>employee</code> would have ended up pointing
6591 to its own, private instance of the Example Inc employer.</p>
6592
6593 <p>As a general guideline, you should use a session when loading
6594 objects that have pointers to other persistent objects. A
6595 session makes sure that for a given object id, a single instance
6596 is shared among all other objects that relate to it.</p>
6597
6598 <p>We can also use data members from pointed-to
6599 objects in database queries (<a href="#4">Chapter 4, "Querying the
6600 Database"</a>). For each pointer in a persistent class, the query
6601 class defines a smart pointer-like member that contains members
6602 corresponding to the data members in the pointed-to object. We
6603 can then use the access via a pointer syntax (<code>-></code>)
6604 to refer to data members in pointed-to objects.
6605 For example, the query class for the <code>employee</code> object
6606 contains the <code>employer</code> member (its name is derived from the
6607 <code>employer_</code> pointer) which in turn contains the
6608 <code>name</code> member (its name is derived from the
6609 <code>employer::name_</code> data member of the pointed-to object).
6610 As a result, we can use the <code>query::employer->name</code>
6611 expression while querying the database for the <code>employee</code>
6612 objects. For example, the following transaction finds all the
6613 employees of Example Inc that have the Doe last name:</p>
6614
6615 <pre class="cxx">
6616 typedef odb::query&lt;employee> query;
6617 typedef odb::result&lt;employee> result;
6618
6619 session s;
6620 transaction t (db.begin ());
6621
6622 result r (db.query&lt;employee> (
6623 query::employer->name == "Example Inc" &amp;&amp; query::last == "Doe"));
6624
6625 for (result::iterator i (r.begin ()); i != r.end (); ++i)
6626 cout &lt;&lt; i->first_ &lt;&lt; " " &lt;&lt; i->last_ &lt;&lt; endl;
6627
6628 t.commit ();
6629 </pre>
6630
6631 <p>A query class member corresponding to a non-inverse
6632 (<a href="#6.2">Section 6.2, "Bidirectional Relationships"</a>) object
6633 pointer can also be used as a normal member that has the id type
6634 of the pointed-to object. For example, the following query locates
6635 all the <code>employee</code> objects that don't have an associated
6636 <code>employer</code> object:</p>
6637
6638 <pre class="cxx">
6639 result r (db.query&lt;employee> (query::employer.is_null ()));
6640 </pre>
6641
6642 <p>An important concept to keep in mind when working with object
6643 relationships is the independence of persistent objects. In particular,
6644 when an object containing a pointer to another object is made persistent
6645 or is updated, the pointed-to object is not automatically persisted
6646 or updated. Rather, only a reference to the object (in the form of the
6647 object id) is stored for the pointed-to object in the database.
6648 The pointed-to object itself is a separate entity and should
6649 be made persistent or updated independently. By default, the
6650 same principle also applies to erasing pointed-to objects. That
6651 is, we have to make sure all the pointing objects are updated
6652 accordingly. However, in the case of erase, we can specify an
6653 alternative <code>on-delete</code> semantic as discussed in
6654 <a href="#14.4.15">Section 14.4.15, "<code>on_delete</code>"</a>.</p>
6655
6656 <p>When persisting or updating an object containing a pointer to another
6657 object, the pointed-to object must have a valid object id. This,
6658 however, may not always be easy to achieve in complex relationships that
6659 involve objects with automatically assigned identifiers. In such
6660 cases it may be necessary to first persist an object with a pointer
6661 set to <code>NULL</code> and then, once the pointed-to object is
6662 made persistent and its identifier assigned, set the pointer
6663 to the correct value and update the object in the database.</p>
6664
6665 <p>Persistent object relationships can be divided into two groups:
6666 unidirectional and bidirectional. Each group in turn contains
6667 several configurations that vary depending on the cardinality
6668 of the sides of the relationship. All possible unidirectional
6669 and bidirectional configurations are discussed in the following
6670 sections.</p>
6671
6672 <h2><a name="6.1">6.1 Unidirectional Relationships</a></h2>
6673
6674 <p>In unidirectional relationships we are only interested in navigating
6675 from object to object in one direction. Because there is no interest
6676 in navigating in the opposite direction, the cardinality of the other
6677 end of the relationship is unimportant. As a result, there are only
6678 two possible unidirectional relationships: to-one and to-many. Each
6679 of these relationships is described in the following sections. For
6680 sample code that shows how to work with these relationships, refer
6681 to the <code>relationship</code> example in the <code>odb-examples</code>
6682 package.</p>
6683
6684 <h3><a name="6.1.1">6.1.1 To-One Relationships</a></h3>
6685
6686 <p>An example of a unidirectional to-one relationship is the
6687 employee-employer relationship (an employee has one employer).
6688 The following persistent C++ classes model this relationship:</p>
6689
6690 <pre class="cxx">
6691 #pragma db object
6692 class employer
6693 {
6694 ...
6695
6696 #pragma db id
6697 std::string name_;
6698 };
6699
6700 #pragma db object
6701 class employee
6702 {
6703 ...
6704
6705 #pragma db id
6706 unsigned long id_;
6707
6708 #pragma db not_null
6709 shared_ptr&lt;employer> employer_;
6710 };
6711 </pre>
6712
6713 <p>The corresponding database tables look like this:</p>
6714
6715 <pre class="sql">
6716 CREATE TABLE employer (
6717 name VARCHAR (255) NOT NULL PRIMARY KEY);
6718
6719 CREATE TABLE employee (
6720 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
6721 employer VARCHAR (255) NOT NULL REFERENCES employer (name));
6722 </pre>
6723
6724 <h3><a name="6.1.2">6.1.2 To-Many Relationships</a></h3>
6725
6726 <p>An example of a unidirectional to-many relationship is the
6727 employee-project relationship (an employee can be involved
6728 in multiple projects). The following persistent C++ classes
6729 model this relationship:</p>
6730
6731 <pre class="cxx">
6732 #pragma db object
6733 class project
6734 {
6735 ...
6736
6737 #pragma db id
6738 std::string name_;
6739 };
6740
6741 #pragma db object
6742 class employee
6743 {
6744 ...
6745
6746 #pragma db id
6747 unsigned long id_;
6748
6749 #pragma db value_not_null unordered
6750 std::vector&lt;shared_ptr&lt;project> > projects_;
6751 };
6752 </pre>
6753
6754 <p>The corresponding database tables look like this:</p>
6755
6756 <pre class="sql">
6757 CREATE TABLE project (
6758 name VARCHAR (255) NOT NULL PRIMARY KEY);
6759
6760 CREATE TABLE employee (
6761 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
6762
6763 CREATE TABLE employee_projects (
6764 object_id BIGINT UNSIGNED NOT NULL,
6765 value VARCHAR (255) NOT NULL REFERENCES project (name));
6766 </pre>
6767
6768 <p>To obtain a more canonical database schema, the names of tables
6769 and columns above can be customized using ODB pragmas
6770 (<a href="#14">Chapter 14, "ODB Pragma Language"</a>). For example:</p>
6771
6772 <pre class="cxx">
6773 #pragma db object
6774 class employee
6775 {
6776 ...
6777
6778 #pragma db value_not_null unordered \
6779 id_column("employee_id") value_column("project_name")
6780 std::vector&lt;shared_ptr&lt;project> > projects_;
6781 };
6782 </pre>
6783
6784 <p>The resulting <code>employee_projects</code> table would then
6785 look like this:</p>
6786
6787 <pre class="sql">
6788 CREATE TABLE employee_projects (
6789 employee_id BIGINT UNSIGNED NOT NULL,
6790 project_name VARCHAR (255) NOT NULL REFERENCES project (name));
6791 </pre>
6792
6793
6794 <h2><a name="6.2">6.2 Bidirectional Relationships</a></h2>
6795
6796 <p>In bidirectional relationships we are interested in navigating
6797 from object to object in both directions. As a result, each
6798 object class in a relationship contains a pointer to the other
6799 object. If smart pointers are used, then a weak pointer should
6800 be used as one of the pointers to avoid ownership cycles. For
6801 example:</p>
6802
6803 <pre class="cxx">
6804 class employee;
6805
6806 #pragma db object
6807 class position
6808 {
6809 ...
6810
6811 #pragma db id
6812 unsigned long id_;
6813
6814 weak_ptr&lt;employee> employee_;
6815 };
6816
6817 #pragma db object
6818 class employee
6819 {
6820 ...
6821
6822 #pragma db id
6823 unsigned long id_;
6824
6825 #pragma db not_null
6826 shared_ptr&lt;position> position_;
6827 };
6828 </pre>
6829
6830 <p>Note that when we establish a bidirectional relationship, we
6831 have to set both pointers consistently. One way to make sure
6832 that a relationship is always in a consistent state is to
6833 provide a single function that updates both pointers at the
6834 same time. For example:</p>
6835
6836 <pre class="cxx">
6837 #pragma db object
6838 class position: public enable_shared_from_this&lt;position>
6839 {
6840 ...
6841
6842 void
6843 fill (shared_ptr&lt;employee> e)
6844 {
6845 employee_ = e;
6846 e->positions_ = shared_from_this ();
6847 }
6848
6849 private:
6850 weak_ptr&lt;employee> employee_;
6851 };
6852
6853 #pragma db object
6854 class employee
6855 {
6856 ...
6857
6858 private:
6859 friend class position;
6860
6861 #pragma db not_null
6862 shared_ptr&lt;position> position_;
6863 };
6864 </pre>
6865
6866 <p>At the beginning of this chapter we examined how to use a session
6867 to make sure a single object is shared among all other objects pointing
6868 to it. With bidirectional relationships involving weak pointers the
6869 use of a session becomes even more crucial. Consider the following
6870 transaction that tries to load the <code>position</code> object
6871 from the above example without using a session:</p>
6872
6873 <pre class="cxx">
6874 transaction t (db.begin ())
6875 shared_ptr&lt;position> p (db.load&lt;position> (1));
6876 ...
6877 t.commit ();
6878 </pre>
6879
6880 <p>When we load the <code>position</code> object, the <code>employee</code>
6881 object, which it points to, is also loaded. While <code>employee</code>
6882 is initially stored as <code>shared_ptr</code>, it is then assigned to
6883 the <code>employee_</code> member which is <code>weak_ptr</code>. Once
6884 the assignment is complete, the shared pointer goes out of scope
6885 and the only pointer that points to the newly loaded
6886 <code>employee</code> object is the <code>employee_</code> weak
6887 pointer. And that means the <code>employee</code> object is deleted
6888 immediately after being loaded. To help avoid such pathological
6889 situations ODB detects cases where a newly loaded object will
6890 immediately be deleted and throws the <code>odb::session_required</code>
6891 exception.</p>
6892
6893 <p>As the exception name suggests, the easiest way to resolve this
6894 problem is to use a session:</p>
6895
6896 <pre class="cxx">
6897 session s;
6898 transaction t (db.begin ())
6899 shared_ptr&lt;position> p (db.load&lt;position> (1));
6900 ...
6901 t.commit ();
6902 </pre>
6903
6904 <p>In our example, the session will maintain a shared pointer to the
6905 loaded <code>employee</code> object preventing its immediate
6906 deletion. Another way to resolve this problem is to avoid
6907 immediate loading of the pointed-to objects using lazy weak
6908 pointers. Lazy pointers are discussed in <a href="#6.4">Section 6.4,
6909 "Lazy Pointers"</a> later in this chapter.</p>
6910
6911 <p>Above, to model a bidirectional relationship in persistent classes,
6912 we used two pointers, one in each object. While this is a natural
6913 representation in C++, it does not translate to a canonical
6914 relational model. Consider the database schema generated for
6915 the above two classes:</p>
6916
6917 <pre class="sql">
6918 CREATE TABLE position (
6919 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
6920 employee BIGINT UNSIGNED REFERENCES employee (id));
6921
6922 CREATE TABLE employee (
6923 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
6924 position BIGINT UNSIGNED NOT NULL REFERENCES position (id));
6925 </pre>
6926
6927 <p>While this database schema is valid, it is unconventional. We have
6928 a reference from a row in the <code>position</code> table to a row
6929 in the <code>employee</code> table. We also have a reference
6930 from this same row in the <code>employee</code> table back to
6931 the row in the <code>position</code> table. From the relational
6932 point of view, one of these references is redundant since
6933 in SQL we can easily navigate in both directions using just one
6934 of these references.</p>
6935
6936 <p>To eliminate redundant database schema references we can use the
6937 <code>inverse</code> pragma (<a href="#14.4.14">Section 14.4.14,
6938 "<code>inverse</code>"</a>) which tells the ODB compiler that
6939 a pointer is the inverse side of a bidirectional relationship.
6940 Either side of a relationship can be made inverse. For example:</p>
6941
6942 <pre class="cxx">
6943 #pragma db object
6944 class position
6945 {
6946 ...
6947
6948 #pragma db inverse(position_)
6949 weak_ptr&lt;employee> employee_;
6950 };
6951
6952 #pragma db object
6953 class employee
6954 {
6955 ...
6956
6957 #pragma db not_null
6958 shared_ptr&lt;position> position_;
6959 };
6960 </pre>
6961
6962 <p>The resulting database schema looks like this:</p>
6963
6964 <pre class="sql">
6965 CREATE TABLE position (
6966 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
6967
6968 CREATE TABLE employee (
6969 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
6970 position BIGINT UNSIGNED NOT NULL REFERENCES position (id));
6971 </pre>
6972
6973 <p>As you can see, an inverse member does not have a corresponding
6974 column (or table, in case of an inverse container of pointers)
6975 and, from the point of view of database operations, is effectively
6976 read-only. The only way to change a bidirectional relationship
6977 with an inverse side is to set its direct (non-inverse)
6978 pointer. Also note that an ordered container (<a href="#5.1">Section
6979 5.1, "Ordered Containers"</a>) of pointers that is an inverse side
6980 of a bidirectional relationship is always treated as unordered
6981 (<a href="#14.4.19">Section 14.4.19, "<code>unordered</code>"</a>)
6982 because the contents of such a container are implicitly built from
6983 the direct side of the relationship which does not contain the
6984 element order (index).</p>
6985
6986 <p>There are three distinct bidirectional relationships that we
6987 will cover in the following sections: one-to-one, one-to-many,
6988 and many-to-many. We will only talk about bidirectional
6989 relationships with inverse sides since they result in canonical
6990 database schemas. For sample code that shows how to work with
6991 these relationships, refer to the <code>inverse</code> example
6992 in the <code>odb-examples</code> package.</p>
6993
6994 <h3><a name="6.2.1">6.2.1 One-to-One Relationships</a></h3>
6995
6996 <p>An example of a bidirectional one-to-one relationship is the
6997 presented above employee-position relationship (an employee
6998 fills one position and a position is filled by one employee).
6999 The following persistent C++ classes model this relationship:</p>
7000
7001 <pre class="cxx">
7002 class employee;
7003
7004 #pragma db object
7005 class position
7006 {
7007 ...
7008
7009 #pragma db id
7010 unsigned long id_;
7011
7012 #pragma db inverse(position_)
7013 weak_ptr&lt;employee> employee_;
7014 };
7015
7016 #pragma db object
7017 class employee
7018 {
7019 ...
7020
7021 #pragma db id
7022 unsigned long id_;
7023
7024 #pragma db not_null
7025 shared_ptr&lt;position> position_;
7026 };
7027 </pre>
7028
7029 <p>The corresponding database tables look like this:</p>
7030
7031 <pre class="sql">
7032 CREATE TABLE position (
7033 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
7034
7035 CREATE TABLE employee (
7036 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
7037 position BIGINT UNSIGNED NOT NULL REFERENCES position (id));
7038 </pre>
7039
7040 <p>If instead the other side of this relationship is made inverse,
7041 then the database tables will change as follows:</p>
7042
7043 <pre class="sql">
7044 CREATE TABLE position (
7045 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
7046 employee BIGINT UNSIGNED REFERENCES employee (id));
7047
7048 CREATE TABLE employee (
7049 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
7050 </pre>
7051
7052 <h3><a name="6.2.2">6.2.2 One-to-Many Relationships</a></h3>
7053
7054 <p>An example of a bidirectional one-to-many relationship is the
7055 employer-employee relationship (an employer has multiple
7056 employees and an employee is employed by one employer).
7057 The following persistent C++ classes model this relationship:</p>
7058
7059 <pre class="cxx">
7060 class employee;
7061
7062 #pragma db object
7063 class employer
7064 {
7065 ...
7066
7067 #pragma db id
7068 std::string name_;
7069
7070 #pragma db value_not_null inverse(employer_)
7071 std::vector&lt;weak_ptr&lt;employee> > employees_
7072 };
7073
7074 #pragma db object
7075 class employee
7076 {
7077 ...
7078
7079 #pragma db id
7080 unsigned long id_;
7081
7082 #pragma db not_null
7083 shared_ptr&lt;employer> employer_;
7084 };
7085 </pre>
7086
7087 <p>The corresponding database tables differ significantly depending
7088 on which side of the relationship is made inverse. If the <em>one</em>
7089 side (<code>employer</code>) is inverse as in the code
7090 above, then the resulting database schema looks like this:</p>
7091
7092 <pre class="sql">
7093 CREATE TABLE employer (
7094 name VARCHAR (255) NOT NULL PRIMARY KEY);
7095
7096 CREATE TABLE employee (
7097 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
7098 employer VARCHAR (255) NOT NULL REFERENCES employer (name));
7099 </pre>
7100
7101 <p>If instead the <em>many</em> side (<code>employee</code>) of this
7102 relationship is made inverse, then the database tables will change
7103 as follows:</p>
7104
7105 <pre class="sql">
7106 CREATE TABLE employer (
7107 name VARCHAR (255) NOT NULL PRIMARY KEY);
7108
7109 CREATE TABLE employer_employees (
7110 object_id VARCHAR (255) NOT NULL,
7111 value BIGINT UNSIGNED NOT NULL REFERENCES employee (id));
7112
7113 CREATE TABLE employee (
7114 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
7115 </pre>
7116
7117 <h3><a name="6.2.3">6.2.3 Many-to-Many Relationships</a></h3>
7118
7119 <p>An example of a bidirectional many-to-many relationship is the
7120 employee-project relationship (an employee can work on multiple
7121 projects and a project can have multiple participating employees).
7122 The following persistent C++ classes model this relationship:</p>
7123
7124 <pre class="cxx">
7125 class employee;
7126
7127 #pragma db object
7128 class project
7129 {
7130 ...
7131
7132 #pragma db id
7133 std::string name_;
7134
7135 #pragma db value_not_null inverse(projects_)
7136 std::vector&lt;weak_ptr&lt;employee> > employees_;
7137 };
7138
7139 #pragma db object
7140 class employee
7141 {
7142 ...
7143
7144 #pragma db id
7145 unsigned long id_;
7146
7147 #pragma db value_not_null unordered
7148 std::vector&lt;shared_ptr&lt;project> > projects_;
7149 };
7150 </pre>
7151
7152 <p>The corresponding database tables look like this:</p>
7153
7154 <pre class="sql">
7155 CREATE TABLE project (
7156 name VARCHAR (255) NOT NULL PRIMARY KEY);
7157
7158 CREATE TABLE employee (
7159 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
7160
7161 CREATE TABLE employee_projects (
7162 object_id BIGINT UNSIGNED NOT NULL,
7163 value VARCHAR (255) NOT NULL REFERENCES project (name));
7164 </pre>
7165
7166 <p>If instead the other side of this relationship is made inverse,
7167 then the database tables will change as follows:</p>
7168
7169 <pre class="sql">
7170 CREATE TABLE project (
7171 name VARCHAR (255) NOT NULL PRIMARY KEY);
7172
7173 CREATE TABLE project_employees (
7174 object_id VARCHAR (255) NOT NULL,
7175 value BIGINT UNSIGNED NOT NULL REFERENCES employee (id));
7176
7177 CREATE TABLE employee (
7178 id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
7179 </pre>
7180
7181 <h2><a name="6.3">6.3 Circular Relationships</a></h2>
7182
7183 <p>A relationship between two persistent classes is circular if each
7184 of them references the other. Bidirectional relationships are
7185 always circular. A unidirectional relationship combined with
7186 inheritance (<a href="#8">Chapter 8, "Inheritance"</a>) can also
7187 be circular. For example, the <code>employee</code> class could
7188 derive from <code>person</code> which, in turn, could contain a
7189 pointer to <code>employee</code>.</p>
7190
7191 <p>We don't need to do anything extra if persistent classes with
7192 circular dependencies are defined in the same header
7193 file. Specifically, ODB will make sure that the database tables
7194 and foreign key constraints are created in the correct order. As a
7195 result, unless you have good reasons not to, it is recommended that
7196 you keep persistent classes with circular dependencies in the same
7197 header file.</p>
7198
7199 <p>If you have to keep such classes in separate header files, then
7200 there are two extra steps that you may need to take in order to
7201 use these classes with ODB. Consider again the example from
7202 <a href="#6.2.1">Section 6.2.1, "One-to-One Relationships"</a>
7203 but this time with the classes defined in separate headers:</p>
7204
7205 <pre class="cxx">
7206 // position.hxx
7207 //
7208 class employee;
7209
7210 #pragma db object
7211 class position
7212 {
7213 ...
7214
7215 #pragma db id
7216 unsigned long id_;
7217
7218 #pragma db inverse(position_)
7219 weak_ptr&lt;employee> employee_;
7220 };
7221 </pre>
7222
7223 <pre class="cxx">
7224 // employee.hxx
7225 //
7226 #include "position.hxx"
7227
7228 #pragma db object
7229 class employee
7230 {
7231 ...
7232
7233 #pragma db id
7234 unsigned long id_;
7235
7236 #pragma db not_null
7237 shared_ptr&lt;position> position_;
7238 };
7239 </pre>
7240
7241 <p>Note that the <code>position.hxx</code> header contains only the forward
7242 declaration for <code>employee</code>. While this is sufficient to
7243 define a valid, from the C++ point of view, <code>position</code> class,
7244 the ODB compiler needs to "see" the definitions of the pointed-to
7245 persistent classes. There are several ways we can fulfil this
7246 requirement. The easiest is to simply include <code>employee.hxx</code>
7247 at the end of <code>position.hxx</code>:</p>
7248
7249 <pre class="cxx">
7250 // position.hxx
7251 //
7252 class employee;
7253
7254 #pragma db object
7255 class position
7256 {
7257 ...
7258 };
7259
7260 #include "employee.hxx"
7261 </pre>
7262
7263 <p>We can also limit this inclusion only to the time when
7264 <code>position.hxx</code> is compiled with the ODB compiler:</p>
7265
7266 <pre class="cxx">
7267 // position.hxx
7268 //
7269
7270 ...
7271
7272 #ifdef ODB_COMPILER
7273 # include "employee.hxx"
7274 #endif
7275 </pre>
7276
7277 <p>Finally, if we don't want to modify <code>position.hxx</code>,
7278 then we can add <code>employee.hxx</code> to the ODB compilation
7279 process with the <code>--odb-epilogue</code> option. For example:</p>
7280
7281 <pre class="terminal">
7282 odb ... --odb-epilogue "#include \"employee.hxx\"" position.hxx
7283 </pre>
7284
7285 <p>Note also that in this example we didn't have to do anything extra
7286 for <code>employee.hxx</code> because it already includes
7287 <code>position.hxx</code>. However, if instead it relied only
7288 on the forward declaration of the <code>position</code> class,
7289 then we would have to handle it in the same way as
7290 <code>position.hxx</code>.</p>
7291
7292 <p>The other difficulty with separately defined classes involving
7293 circular relationships has to do with the correct order of foreign
7294 key constraint creation in the generated database schema. In
7295 the above example, if we generate the database schema as
7296 standalone SQL files, then we will end up with two such files:
7297 <code>position.sql</code> and <code>employee.sql</code>.
7298 If we try to execute <code>employee.sql</code> first, then
7299 we will get an error indicating that the table corresponding to
7300 the <code>position</code> class and referenced by the foreign
7301 key constraint corresponding to the <code>position_</code>
7302 pointer does not yet exist.</p>
7303
7304 <p>Note that there is no such problem if the database schema
7305 is embedded in the generated C++ code instead of being produced
7306 as standalone SQL files. In this case, the ODB compiler is
7307 able to ensure the correct creation order even if the classes
7308 are defined in separate header files.</p>
7309
7310 <p>In certain cases, for example, a bidirectional relationship
7311 with an inverse side, this problem can be resolved by executing
7312 the database schema creation files in the correct order. In our
7313 example, this would be <code>position.sql</code> first
7314 and <code>employee.sql</code> second. However, this approach
7315 doesn't scale beyond simple object models.</p>
7316
7317 <p>A more robust solution to this problem is to generate the database
7318 schema for all the persistent classes into a single SQL file. This
7319 way, the ODB compiler can again ensure the correct creation order
7320 of tables and foreign keys. To instruct the ODB compiler to produce
7321 a combined schema file for several headers we can use the
7322 <code>--generate-schema-only</code> and <code>--at-once</code>
7323 options. For example:</p>
7324
7325 <pre class="terminal">
7326 odb ... --generate-schema-only --at-once --input-name company \
7327 position.hxx employee.hxx
7328 </pre>
7329
7330 <p>The result of the above command is a single <code>company.sql</code>
7331 file (the name is derived from the <code>--input-name</code> value)
7332 that contains the database creation code for both <code>position</code>
7333 and <code>employee</code> classes.</p>
7334
7335 <h2><a name="6.4">6.4 Lazy Pointers</a></h2>
7336
7337 <p>Consider again the bidirectional, one-to-many employer-employee
7338 relationship that was presented earlier in this chapter:</p>
7339
7340 <pre class="cxx">
7341 class employee;
7342
7343 #pragma db object
7344 class employer
7345 {
7346 ...
7347
7348 #pragma db id
7349 std::string name_;
7350
7351 #pragma db value_not_null inverse(employer_)
7352 std::vector&lt;weak_ptr&lt;employee> > employees_;
7353 };
7354
7355 #pragma db object
7356 class employee
7357 {
7358 ...
7359
7360 #pragma db id
7361 unsigned long id_;
7362
7363 #pragma db not_null
7364 shared_ptr&lt;employer> employer_;
7365 };
7366 </pre>
7367
7368 <p>Consider also the following transaction which obtains the employer
7369 name given the employee id:</p>
7370
7371 <pre class="cxx">
7372 unsigned long id = ...
7373 string name;
7374
7375 session s;
7376 transaction t (db.begin ());
7377
7378 shared_ptr&lt;employee> e (db.load&lt;employee> (id));
7379 name = e->employer_->name_;
7380
7381 t.commit ();
7382 </pre>
7383
7384 <p>While this transaction looks very simple, it actually does a lot more
7385 than what meets the eye and is necessary. Consider what happens when
7386 we load the <code>employee</code> object: the <code>employer_</code>
7387 pointer is also automatically loaded which means the <code>employer</code>
7388 object corresponding to this employee is also loaded. But the
7389 <code>employer</code> object in turn contains the list of pointers
7390 to all the employees, which are also loaded. A a result, when object
7391 relationships are involved, a simple transaction like the above can
7392 load many more objects than is necessary.</p>
7393
7394 <p>To overcome this problem ODB offers finer grained control over
7395 the relationship loading in the form of lazy pointers. A lazy
7396 pointer does not automatically load the pointed-to object
7397 when the containing object is loaded. Instead, we have to
7398 explicitly load the pointed-to object if and when we need to
7399 access it.</p>
7400
7401 <p>The ODB runtime library provides lazy counterparts for all the
7402 supported pointers, namely:
7403 <code>odb::lazy_shared_ptr</code>/<code>lazy_weak_ptr</code>
7404 for C++11 <code>std::shared_ptr</code>/<code>weak_ptr</code>,
7405 <code>odb::tr1::lazy_shared_ptr</code>/<code>lazy_weak_ptr</code>
7406 for TR1 <code>std::tr1::shared_ptr</code>/<code>weak_ptr</code>,
7407 <code>odb::lazy_unique_ptr</code> for C++11 <code>std::unique_ptr</code>,
7408 <code>odb::lazy_auto_ptr</code> for <code>std::auto_ptr</code>,
7409 and <code>odb::lazy_ptr</code> for raw pointers. The TR1 lazy
7410 pointers are defined in the <code>&lt;odb/tr1/lazy-ptr.hxx></code>
7411 header while all the others &mdash; in
7412 <code>&lt;odb/lazy-ptr.hxx></code>. The ODB profile
7413 libraries also provide lazy pointer implementations for smart pointers
7414 from popular frameworks and libraries (<a href="#III">Part III,
7415 "Profiles"</a>).</p>
7416
7417 <p>While we will discuss the interface of lazy pointers in more detail
7418 shortly, the most commonly used extra function provided by these
7419 pointers is <code>load()</code>. This function loads the
7420 pointed-to object if it hasn't already been loaded. After
7421 the call to this function, the lazy pointer can be used
7422 in the the same way as its eager counterpart. The <code>load()</code>
7423 function also returns the eager pointer, in case you need to pass
7424 it around. For a lazy weak pointer, the
7425 <code>load()</code> function also locks the pointer.</p>
7426
7427 <p>The following example shows how we can change our employer-employee
7428 relationship to use lazy pointers. Here we choose to use lazy pointers
7429 for both sides of the relationship.</p>
7430
7431 <pre class="cxx">
7432 class employee;
7433
7434 #pragma db object
7435 class employer
7436 {
7437 ...
7438
7439 #pragma db value_not_null inverse(employer_)
7440 std::vector&lt;lazy_weak_ptr&lt;employee> > employees_;
7441 };
7442
7443 #pragma db object
7444 class employee
7445 {
7446 ...
7447
7448 #pragma db not_null
7449 lazy_shared_ptr&lt;employer> employer_;
7450 };
7451 </pre>
7452
7453 <p>And the transaction is changed like this:</p>
7454
7455 <pre class="cxx">
7456 unsigned long id = ...
7457 string name;
7458
7459 session s;
7460 transaction t (db.begin ());
7461
7462 shared_ptr&lt;employee> e (db.load&lt;employee> (id));
7463 e->employer_.load ();
7464 name = e->employer_->name_;
7465
7466 t.commit ();
7467 </pre>
7468
7469
7470 <p>As a general guideline we recommend that you make at least one side
7471 of a bidirectional relationship lazy, especially for relationships
7472 with a <em>many</em> side.</p>
7473
7474 <p>A lazy pointer implementation mimics the interface of its eager
7475 counterpart which can be used once the pointer is loaded. It also
7476 adds a number of additional functions that are specific to the
7477 lazy loading functionality. Overall, the interface of a lazy
7478 pointer follows this general outline:</p>
7479
7480 <pre class="cxx">
7481 template &lt;class T>
7482 class lazy_ptr
7483 {
7484 public:
7485 //
7486 // The eager pointer interface.
7487 //
7488
7489 // Initialization/assignment from an eager pointer.
7490 //
7491 public:
7492 template &lt;class Y> lazy_ptr (const eager_ptr&lt;Y>&amp;);
7493 template &lt;class Y> lazy_ptr&amp; operator= (const eager_ptr&lt;Y>&amp;);
7494
7495 // Lazy loading interface.
7496 //
7497 public:
7498 // NULL loaded()
7499 //
7500 // true true NULL pointer to transient object
7501 // false true valid pointer to persistent object
7502 // true false unloaded pointer to persistent object
7503 // false false valid pointer to transient object
7504 //
7505 bool loaded () const;
7506
7507 eager_ptr&lt;T> load () const;
7508
7509 // Unload the pointer. For transient objects this function is
7510 // equivalent to reset().
7511 //
7512 void unload () const;
7513
7514 // Get the underlying eager pointer. If this is an unloaded pointer
7515 // to a persistent object, then the returned pointer will be NULL.
7516 //
7517 eager_ptr&lt;T> get_eager () const;
7518
7519 // Initialization with a persistent loaded object.
7520 //
7521 template &lt;class Y> lazy_ptr (database&amp;, Y*);
7522 template &lt;class Y> lazy_ptr (database&amp;, const eager_ptr&lt;Y>&amp;);
7523
7524 template &lt;class Y> void reset (database&amp;, Y*);
7525 template &lt;class Y> void reset (database&amp;, const eager_ptr&lt;Y>&amp;);
7526
7527 // Initialization with a persistent unloaded object.
7528 //
7529 template &lt;class ID> lazy_ptr (database&amp;, const ID&amp;);
7530
7531 template &lt;class ID> void reset (database&amp;, const ID&amp;);
7532
7533 // Query object id and database of a persistent object.
7534 //
7535 template &lt;class O /* = T */>
7536 // C++11: template &lt;class O = T>
7537 object_traits&lt;O>::id_type object_id () const;
7538
7539 odb::database&amp; database () const;
7540 };
7541 </pre>
7542
7543 <p>In a lazy weak pointer interface, the <code>load()</code> function
7544 returns the <em>strong</em> (shared) eager pointer. The following
7545 transaction demonstrates the use of a lazy weak pointer based on
7546 the <code>employer</code> and <code>employee</code> classes
7547 presented earlier.</p>
7548
7549 <pre class="cxx">
7550 typedef std::vector&lt;lazy_weak_ptr&lt;employee> > employees;
7551
7552 session s;
7553 transaction t (db.begin ());
7554
7555 shared_ptr&lt;employer> er (db.load&lt;employer> ("Example Inc"));
7556 employees&amp; es (er->employees ());
7557
7558 for (employees::iterator i (es.begin ()); i != es.end (); ++i)
7559 {
7560 // We are only interested in employees with object id less than
7561 // 100.
7562 //
7563 lazy_weak_ptr&lt;employee>&amp; lwp (*i);
7564
7565 if (lwp.object_id&lt;employee> () &lt; 100)
7566 // C++11: if (lwp.object_id () &lt; 100)
7567 {
7568 shared_ptr&lt;employee> e (lwp.load ()); // Load and lock.
7569 cout &lt;&lt; e->first_ &lt;&lt; " " &lt;&lt; e->last_ &lt;&lt; endl;
7570 }
7571 }
7572
7573 t.commit ();
7574 </pre>
7575
7576 <p>Notice that inside the for-loop we use a reference to the lazy
7577 weak pointer instead of making a copy. This is not merely to
7578 avoid a copy. When a lazy pointer is loaded, all other lazy
7579 pointers that point to the same object do not automatically
7580 become loaded (though an attempt to load such copies will
7581 result in them pointing to the same object, provided the
7582 same session is still in effect). By using a reference
7583 in the above transaction we make sure that we load the
7584 pointer that is contained in the <code>employer</code>
7585 object. This way, if we later need to re-examine this
7586 <code>employee</code> object, the pointer will already
7587 be loaded.</p>
7588
7589 <p>As another example, suppose we want to add an employee
7590 to Example Inc. The straightforward implementation of this
7591 transaction is presented below:</p>
7592
7593 <pre class="cxx">
7594 session s;
7595 transaction t (db.begin ());
7596
7597 shared_ptr&lt;employer> er (db.load&lt;employer> ("Example Inc"));
7598 shared_ptr&lt;employee> e (new employee ("John", "Doe"));
7599
7600 e->employer_ = er;
7601 er->employees ().push_back (e);
7602
7603 db.persist (e);
7604 t.commit ();
7605 </pre>
7606
7607 <p>Notice here that we didn't have to update the employer object
7608 in the database since the <code>employees_</code> list of
7609 pointers is an inverse side of a bidirectional relationship
7610 and is effectively read-only, from the persistence point of
7611 view.</p>
7612
7613 <p>A faster implementation of this transaction, that avoids loading
7614 the employer object, relies on the ability to initialize an
7615 <em>unloaded</em> lazy pointer with the database where the object
7616 is stored as well as its identifier:</p>
7617
7618 <pre class="cxx">
7619 lazy_shared_ptr&lt;employer> er (db, std::string ("Example Inc"));
7620 shared_ptr&lt;employee> e (new employee ("John", "Doe"));
7621
7622 e->employer_ = er;
7623
7624 session s;
7625 transaction t (db.begin ());
7626
7627 db.persist (e);
7628
7629 t.commit ();
7630 </pre>
7631
7632 <p>For the interaction of lazy pointers with lazy-loaded object
7633 sections, refer to <a href="#9.3">Section 9.3, "Sections and
7634 Lazy Pointers"</a>.</p>
7635
7636 <h2><a name="6.5">6.5 Using Custom Smart Pointers</a></h2>
7637
7638 <p>While the ODB runtime and profile libraries provide support for
7639 the majority of widely-used pointers, it is also easy to add
7640 support for a custom smart pointer.</p>
7641
7642 <p>To achieve this you will need to implement the
7643 <code>pointer_traits</code> class template specialization for
7644 your pointer. The first step is to determine the pointer kind
7645 since the interface of the <code>pointer_traits</code> specialization
7646 varies depending on the pointer kind. The supported pointer kinds
7647 are: <em>raw</em> (raw pointer or equivalent, that is, unmanaged),
7648 <em>unique</em> (smart pointer that doesn't support sharing),
7649 <em>shared</em> (smart pointer that supports sharing), and
7650 <em>weak</em> (weak counterpart of the shared pointer). Any of
7651 these pointers can be lazy, which also affects the
7652 interface of the <code>pointer_traits</code> specialization.</p>
7653
7654 <p>Once you have determined the pointer kind for your smart pointer,
7655 use a specialization for one of the standard pointers found in
7656 the common ODB runtime library (<code>libodb</code>) as a base
7657 for your own implementation.</p>
7658
7659 <p>Once the pointer traits specialization is ready, you will need to
7660 include it into the ODB compilation process using the
7661 <code>--odb-epilogue</code> option and into the generated header
7662 files with the <code>--hxx-prologue</code> option. As an example,
7663 suppose we have the <code>smart_ptr</code> smart pointer for which
7664 we have the traits specialization implemented in the
7665 <code>smart-ptr-traits.hxx</code> file. Then, we can create an ODB
7666 compiler options file for this pointer and save it to
7667 <code>smart-ptr.options</code>:</p>
7668
7669 <pre>
7670 # Options file for smart_ptr.
7671 #
7672 --odb-epilogue '#include "smart-ptr-traits.hxx"'
7673 --hxx-prologue '#include "smart-ptr-traits.hxx"'
7674 </pre>
7675
7676 <p>Now, whenever we compile a header file that uses <code>smart_ptr</code>,
7677 we can specify the following command line option to make sure it is
7678 recognized by the ODB compiler as a smart pointer and the traits file
7679 is included in the generated code:</p>
7680
7681 <pre>
7682 --options-file smart-ptr.options
7683 </pre>
7684
7685 <p>It is also possible to implement a lazy counterpart for your
7686 smart pointer. The ODB runtime library provides a class template
7687 that encapsulates the object id management and loading
7688 functionality that is needed to implement a lazy pointer. All
7689 you need to do is wrap it with an interface that mimics
7690 your smart pointer. Using one of the existing lazy pointer
7691 implementations (either from the ODB runtime library or one
7692 of the profile libraries) as a base for your implementation
7693 is the easiest way to get started.</p>
7694
7695
7696 <!-- CHAPTER -->
7697
7698 <hr class="page-break"/>
7699 <h1><a name="7">7 Value Types</a></h1>
7700
7701 <p>In <a href="#3.1">Section 3.1, "Concepts and Terminology"</a> we have
7702 already discussed the notion of values and value types as well as the
7703 distinction between simple and composite values. This chapter covers
7704 simple and composite value types in more detail.</p>
7705
7706 <h2><a name="7.1">7.1 Simple Value Types</a></h2>
7707
7708 <p>A simple value type is a fundamental C++ type or a class type that
7709 is mapped to a single database column. For each supported database
7710 system the ODB compiler provides a default mapping to suitable
7711 database types for most fundamental C++ types, such as <code>int</code>
7712 or <code>float</code> as well as some class types, such as
7713 <code>std::string</code>. For more information about the default
7714 mapping for each database system refer to <a href="#II">Part II,
7715 Database Systems</a>. We can also provide a custom mapping for
7716 these or our own value types using the <code>db&nbsp;type</code>
7717 pragma (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>).</p>
7718
7719 <h2><a name="7.2">7.2 Composite Value Types</a></h2>
7720
7721 <p>A composite value type is a <code>class</code> or <code>struct</code>
7722 type that is mapped to more than one database column. To declare
7723 a composite value type we use the <code>db&nbsp;value</code> pragma,
7724 for example:</p>
7725
7726 <pre class="cxx">
7727 #pragma db value
7728 class basic_name
7729 {
7730 ...
7731
7732 std::string first_;
7733 std::string last_;
7734 };
7735 </pre>
7736
7737 <p>The complete version of the above code fragment and the other code
7738 samples presented in this section can be found in the <code>composite</code>
7739 example in the <code>odb-examples</code> package.</p>
7740
7741 <p>A composite value type does not have to define a default constructor,
7742 unless it is used as an element of a container. In this case the
7743 default constructor can be made private provided we also make the
7744 <code>odb::access</code> class, defined in the
7745 <code>&lt;odb/core.hxx></code> header, a friend of this value type.
7746 For example:</p>
7747
7748 <pre class="cxx">
7749 #include &lt;odb/core.hxx>
7750
7751 #pragma db value
7752 class basic_name
7753 {
7754 public:
7755 basic_name (const std::string&amp; first, const std::string&amp; last);
7756
7757 ...
7758
7759 private:
7760 friend class odb::access;
7761
7762 basic_name () {} // Needed for storing basic_name in containers.
7763
7764 ...
7765 };
7766 </pre>
7767
7768 <p>The ODB compiler also needs access to the non-transient
7769 (<a href="#14.4.11">Section 14.4.11, "<code>transient</code>"</a>)
7770 data members of a composite value type. It uses the same mechanisms
7771 as for persistent classes which are discussed in
7772 <a href="#3.2">Section 3.2, "Declaring Persistent Objects and
7773 Values"</a>.</p>
7774
7775 <p>The members of a composite value can be other value types (either
7776 simple or composite), containers (<a href="#5">Chapter 5,
7777 "Containers"</a>), and pointers to objects (<a href="#6">Chapter 6,
7778 "Relationships"</a>).
7779 Similarly, a composite value type can be used in object members,
7780 as an element of a container, and as a base for another composite
7781 value type. In particular, composite value types can be used as
7782 element types in set containers (<a href="#5.2">Section 5.2, "Set
7783 and Multiset Containers"</a>) and as key types in map containers
7784 (<a href="#5.3">Section 5.3, "Map and Multimap Containers"</a>).
7785 A composite value type that is used as an element of a container
7786 cannot contain other containers since containers of containers
7787 are not allowed. The following example illustrates some of the
7788 possible use cases:</p>
7789
7790 <pre class="cxx">
7791 #pragma db value
7792 class basic_name
7793 {
7794 ...
7795
7796 std::string first_;
7797 std::string last_;
7798 };
7799
7800 typedef std::vector&lt;basic_name> basic_names;
7801
7802 #pragma db value
7803 class name_extras
7804 {
7805 ...
7806
7807 std::string nickname_;
7808 basic_names aliases_;
7809 };
7810
7811 #pragma db value
7812 class name: public basic_name
7813 {
7814 ...
7815
7816 std::string title_;
7817 name_extras extras_;
7818 };
7819
7820 #pragma db object
7821 class person
7822 {
7823 ...
7824
7825 name name_;
7826 };
7827 </pre>
7828
7829 <p>A composite value type can be defined inside a persistent class,
7830 view, or another composite value and even made private, provided
7831 we make <code>odb::access</code> a friend of the containing class,
7832 for example:</p>
7833
7834 <pre class="cxx">
7835 #pragma db object
7836 class person
7837 {
7838 ...
7839
7840 #pragma db value
7841 class name
7842 {
7843 ...
7844
7845 std::string first_;
7846 std::string last_;
7847 };
7848
7849 name name_;
7850 };
7851 </pre>
7852
7853 <p>A composite value type can also be defined as an instantiation
7854 of a C++ class template, for example:</p>
7855
7856 <pre class="cxx">
7857 template &lt;typename T>
7858 struct point
7859 {
7860 T x;
7861 T y;
7862 T z;
7863 };
7864
7865 typedef point&lt;int> int_point;
7866 #pragma db value(int_point)
7867
7868 #pragma db object
7869 class object
7870 {
7871 ...
7872
7873 int_point center_;
7874 };
7875 </pre>
7876
7877 <p>Note that the database support code for such a composite value type
7878 is generated when compiling the header containing the
7879 <code>db&nbsp;value</code> pragma and not the header containing
7880 the template definition or the <code>typedef</code> name. This
7881 allows us to use templates defined in other files, such as
7882 <code>std::pair</code> defined in the <code>utility</code>
7883 standard header file:</p>
7884
7885 <pre class="cxx">
7886 #include &lt;utility> // std::pair
7887
7888 typedef std::pair&lt;std::string, std::string> phone_numbers;
7889 #pragma db value(phone_numbers)
7890
7891 #pragma db object
7892 class person
7893 {
7894 ...
7895
7896 phone_numbers phone_;
7897 };
7898 </pre>
7899
7900 <p>We can also use data members from composite value types
7901 in database queries (<a href="#4">Chapter 4, "Querying the
7902 Database"</a>). For each composite value in a persistent class, the
7903 query class defines a nested member that contains members corresponding
7904 to the data members in the value type. We can then use the member access
7905 syntax (.) to refer to data members in value types. For example, the
7906 query class for the <code>person</code> object presented above
7907 contains the <code>name</code> member (its name is derived from
7908 the <code>name_</code> data member) which in turn contains the
7909 <code>extras</code> member (its name is derived from the
7910 <code>name::extras_</code> data member of the composite value type).
7911 This process continues recursively for nested composite value types
7912 and, as a result, we can use the <code>query::name.extras.nickname</code>
7913 expression while querying the database for the <code>person</code>
7914 objects. For example:</p>
7915
7916 <pre class="cxx">
7917 typedef odb::query&lt;person> query;
7918 typedef odb::result&lt;person> result;
7919
7920 transaction t (db.begin ());
7921
7922 result r (db.query&lt;person> (
7923 query::name.extras.nickname == "Squeaky"));
7924
7925 ...
7926
7927 t.commit ();
7928 </pre>
7929
7930 <h3><a name="7.2.1">7.2.1 Composite Object Ids</a></h3>
7931
7932 <p>An object id can be of a composite value type, for example:</p>
7933
7934 <pre class="cxx">
7935 #pragma db value
7936 class name
7937 {
7938 ...
7939
7940 std::string first_;
7941 std::string last_;
7942 };
7943
7944 #pragma db object
7945 class person
7946 {
7947 ...
7948
7949 #pragma db id
7950 name name_;
7951 };
7952 </pre>
7953
7954 <p>However, a value type that can be used as an object id has a number
7955 of restrictions. Such a value type cannot have container, object
7956 pointer, or read-only data members. It also must be
7957 default-constructible, copy-constructible, and copy-assignable.
7958 Furthermore, if the persistent class in which
7959 this composite value type is used as object id has session support
7960 enabled (<a href="#11">Chapter 11, "Session"</a>), then it must also
7961 implement the less-than comparison operator (<code>operator&lt;</code>).</p>
7962
7963 <h3><a name="7.2.2">7.2.2 Composite Value Column and Table Names</a></h3>
7964
7965 <p>Customizing a column name for a data member of a simple value
7966 type is straightforward: we simply specify the desired name with
7967 the <code>db&nbsp;column</code> pragma (<a href="#14.4.9">Section
7968 14.4.9, "<code>column</code>"</a>). For composite value
7969 types things are slightly more complex since they are mapped to
7970 multiple columns. Consider the following example:</p>
7971
7972 <pre class="cxx">
7973 #pragma db value
7974 class name
7975 {
7976 ...
7977
7978 std::string first_;
7979 std::string last_;
7980 };
7981
7982 #pragma db object
7983 class person
7984 {
7985 ...
7986
7987 #pragma db id auto
7988 unsigned long id_;
7989
7990 name name_;
7991 };
7992 </pre>
7993
7994 <p>The column names for the <code>first_</code> and <code>last_</code>
7995 members are constructed by using the sanitized name of the
7996 <code>person::name_</code> member as a prefix and the names of the
7997 members in the value type (<code>first_</code> and <code>last_</code>)
7998 as suffixes. As a result, the database schema for the above classes
7999 will look like this:</p>
8000
8001 <pre class="sql">
8002 CREATE TABLE person (
8003 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8004 name_first TEXT NOT NULL,
8005 name_last TEXT NOT NULL);
8006 </pre>
8007
8008 <p>We can customize both the prefix and the suffix using the
8009 <code>db&nbsp;column</code> pragma as shown in the following
8010 example:</p>
8011
8012 <pre class="cxx">
8013 #pragma db value
8014 class name
8015 {
8016 ...
8017
8018 #pragma db column("first_name")
8019 std::string first_;
8020
8021 #pragma db column("last_name")
8022 std::string last_;
8023 };
8024
8025 #pragma db object
8026 class person
8027 {
8028 ...
8029
8030 #pragma db column("person_")
8031 name name_;
8032 };
8033 </pre>
8034
8035 <p>The database schema changes as follows:</p>
8036
8037 <pre class="sql">
8038 CREATE TABLE person (
8039 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8040 person_first_name TEXT NOT NULL,
8041 person_last_name TEXT NOT NULL);
8042 </pre>
8043
8044 <p>We can also make the column prefix empty, for example:</p>
8045
8046 <pre class="cxx">
8047 #pragma db object
8048 class person
8049 {
8050 ...
8051
8052 #pragma db column("")
8053 name name_;
8054 };
8055 </pre>
8056
8057 <p>This will result in the following schema:</p>
8058
8059 <pre class="sql">
8060 CREATE TABLE person (
8061 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8062 first_name TEXT NOT NULL,
8063 last_name TEXT NOT NULL);
8064 </pre>
8065
8066 <p>The same principle applies when a composite value type is used
8067 as an element of a container, except that instead of
8068 <code>db&nbsp;column</code>, either the <code>db&nbsp;value_column</code>
8069 (<a href="#14.4.36">Section 14.4.36, "<code>value_column</code>"</a>) or
8070 <code>db&nbsp;key_column</code>
8071 (<a href="#14.4.35">Section 14.4.35, "<code>key_column</code>"</a>)
8072 pragmas are used to specify the column prefix.</p>
8073
8074 <p>When a composite value type contains a container, an extra table
8075 is used to store its elements (<a href="#5">Chapter 5, "Containers"</a>).
8076 The names of such tables are constructed in a way similar to the
8077 column names, except that by default both the object name and the
8078 member name are used as a prefix. For example:</p>
8079
8080 <pre class="cxx">
8081 #pragma db value
8082 class name
8083 {
8084 ...
8085
8086 std::string first_;
8087 std::string last_;
8088 std::vector&lt;std::string> nicknames_;
8089 };
8090
8091 #pragma db object
8092 class person
8093 {
8094 ...
8095
8096 name name_;
8097 };
8098 </pre>
8099
8100 <p>The corresponding database schema will look like this:</p>
8101
8102 <pre class="sql">
8103 CREATE TABLE person_name_nicknames (
8104 object_id BIGINT UNSIGNED NOT NULL,
8105 index BIGINT UNSIGNED NOT NULL,
8106 value TEXT NOT NULL)
8107
8108 CREATE TABLE person (
8109 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8110 name_first TEXT NOT NULL,
8111 name_last TEXT NOT NULL);
8112 </pre>
8113
8114 <p>To customize the container table name we can use the
8115 <code>db&nbsp;table</code> pragma (<a href="#14.4.20">Section
8116 14.4.20, "<code>table</code>"</a>), for example:</p>
8117
8118 <pre class="cxx">
8119 #pragma db value
8120 class name
8121 {
8122 ...
8123
8124 #pragma db table("nickname")
8125 std::vector&lt;std::string> nicknames_;
8126 };
8127
8128 #pragma db object
8129 class person
8130 {
8131 ...
8132
8133 #pragma db table("person_")
8134 name name_;
8135 };
8136 </pre>
8137
8138 <p>This will result in the following schema changes:</p>
8139
8140 <pre class="sql">
8141 CREATE TABLE person_nickname (
8142 object_id BIGINT UNSIGNED NOT NULL,
8143 index BIGINT UNSIGNED NOT NULL,
8144 value TEXT NOT NULL)
8145 </pre>
8146
8147 <p>Similar to columns, we can make the table prefix empty.</p>
8148
8149
8150 <h2><a name="7.3">7.3 Pointers and <code>NULL</code> Value Semantics</a></h2>
8151
8152 <p>Relational database systems have a notion of the special
8153 <code>NULL</code> value that is used to indicate the absence
8154 of a valid value in a column. While by default ODB maps
8155 values to columns that do not allow <code>NULL</code> values,
8156 it is possible to change that with the <code>db&nbsp;null</code>
8157 pragma (<a href="#14.4.6">Section 14.4.6,
8158 "<code>null</code>/<code>not_null</code>"</a>).</p>
8159
8160 <p>To properly support the <code>NULL</code> semantics, the
8161 C++ value type must have a notion of a <code>NULL</code>
8162 value or a similar special state concept. Most basic
8163 C++ types, such as <code>int</code> or <code>std::string</code>,
8164 do not have this notion and therefore cannot be used directly
8165 for <code>NULL</code>-enabled data members (in the case of a
8166 <code>NULL</code> value being loaded from the database,
8167 such data members will be default-initialized).</p>
8168
8169 <p>To allow the easy conversion of value types that do not support
8170 the <code>NULL</code> semantics into the ones that do, ODB
8171 provides the <code>odb::nullable</code> class template. It
8172 allows us to wrap an existing C++ type into a container-like
8173 class that can either be <code>NULL</code> or contain a
8174 value of the wrapped type. ODB also automatically enables
8175 the <code>NULL</code> values for data members of the
8176 <code>odb::nullable</code> type. For example:</p>
8177
8178 <pre class="cxx">
8179 #include &lt;odb/nullable.hxx>
8180
8181 #pragma db object
8182 class person
8183 {
8184 ...
8185
8186 std::string first_; // TEXT NOT NULL
8187 odb::nullable&lt;std::string> middle_; // TEXT NULL
8188 std::string last_; // TEXT NOT NULL
8189 };
8190 </pre>
8191
8192 <p>The <code>odb::nullable</code> class template is defined
8193 in the <code>&lt;odb/nullable.hxx></code> header file and
8194 has the following interface:</p>
8195
8196 <pre class="cxx">
8197 namespace odb
8198 {
8199 template &lt;typename T>
8200 class nullable
8201 {
8202 public:
8203 typedef T value_type;
8204
8205 nullable ();
8206 nullable (const T&amp;);
8207 nullable (const nullable&amp;);
8208 template &lt;typename Y> explicit nullable (const nullable&lt;Y>&amp;);
8209
8210 nullable&amp; operator= (const T&amp;);
8211 nullable&amp; operator= (const nullable&amp;);
8212 template &lt;typename Y> nullable&amp; operator= (const nullable&lt;Y>&amp;);
8213
8214 void swap (nullable&amp;);
8215
8216 // Accessor interface.
8217 //
8218 bool null () const;
8219
8220 T&amp; get ();
8221 const T&amp; get () const;
8222
8223 // Pointer interface.
8224 //
8225 operator bool_convertible () const;
8226
8227 T* operator-> ();
8228 const T* operator-> () const;
8229
8230 T&amp; operator* ();
8231 const T&amp; operator* () const;
8232
8233 // Reset to the NULL state.
8234 //
8235 void reset ();
8236 };
8237 }
8238 </pre>
8239
8240 <p>The following example shows how we can use this interface:</p>
8241
8242 <pre class="cxx">
8243 nullable&lt;string> ns;
8244
8245 // Using the accessor interface.
8246 //
8247 if (ns.null ())
8248 {
8249 s = "abc";
8250 }
8251 else
8252 {
8253 string s (ns.get ());
8254 ns.reset ();
8255 }
8256
8257 // The same using the pointer interface.
8258 //
8259 if (ns)
8260 {
8261 s = "abc";
8262 }
8263 else
8264 {
8265 string s (*ns);
8266 ns.reset ();
8267 }
8268 </pre>
8269
8270
8271 <p>The <code>odb::nullable</code> class template requires the wrapped
8272 type to have public default and copy constructors as well as the
8273 copy assignment operator. Note also that the <code>odb::nullable</code>
8274 implementation is not the most efficient in that it always contains
8275 a fully constructed value of the wrapped type. This is normally
8276 not a concern for simple types such as the C++ fundamental
8277 types or <code>std::string</code>. However, it may become
8278 an issue for more complex types. In such cases you may want to
8279 consider using a more efficient implementation of the
8280 <em>optional value</em> concept such as the
8281 <code>optional</code> class template from Boost
8282 (<a href="#23.4">Section 23.4, "Optional Library"</a>).</p>
8283
8284 <p>Another common C++ representation of a value that can be
8285 <code>NULL</code> is a pointer. ODB will automatically
8286 handle data members that are pointers to values, however,
8287 it will not automatically enable <code>NULL</code> values
8288 for such data members, as is the case for <code>odb::nullable</code>.
8289 Instead, if the <code>NULL</code> value is desired, we will
8290 need to enable it explicitly using the <code>db&nbsp;null</code>
8291 pragma. For example:</p>
8292
8293 <pre class="cxx">
8294 #pragma db object
8295 class person
8296 {
8297 ...
8298
8299 std::string first_;
8300
8301 #pragma db null
8302 std::auto_ptr&lt;std::string> middle_;
8303
8304 std::string last_;
8305 };
8306 </pre>
8307
8308 <p>The ODB compiler includes built-in support for using
8309 <code>std::auto_ptr</code>, <code>std::unique_ptr</code> (C++11),
8310 and <code>shared_ptr</code> (TR1 or C++11) as pointers to values.
8311 Plus, ODB profile libraries, that are
8312 available for commonly used frameworks and libraries (such as Boost and
8313 Qt), provide support for smart pointers found in these frameworks
8314 and libraries (<a href="#III">Part III, "Profiles"</a>).</p>
8315
8316 <p>ODB also supports the <code>NULL</code> semantics for composite
8317 values. In the relational database the <code>NULL</code> composite
8318 value is translated to <code>NULL</code> values for all the simple
8319 data members of this composite value. For example:</p>
8320
8321 <pre class="cxx">
8322 #pragma db value
8323 struct name
8324 {
8325 std::string first_;
8326 odb::nullable&lt;std::string> middle_;
8327 std::string last_;
8328 };
8329
8330 #pragma db object
8331 class person
8332 {
8333 ...
8334 odb::nullable&lt;name> name_;
8335 };
8336 </pre>
8337
8338 <p>ODB does not support the <code>NULL</code> semantics for containers.
8339 This also means that a composite value that contains a container
8340 cannot be <code>NULL</code>. With this limitation in mind, we can
8341 still use smart pointers in data members of container types. The
8342 only restriction is that these pointers must not be <code>NULL</code>.
8343 For example:</p>
8344
8345 <pre class="cxx">
8346 #pragma db object
8347 class person
8348 {
8349 ...
8350
8351 std::auto_ptr&lt;std::vector&lt;std::string> > aliases_;
8352 };
8353 </pre>
8354
8355
8356 <!-- CHAPTER -->
8357
8358
8359 <hr class="page-break"/>
8360 <h1><a name="8">8 Inheritance</a></h1>
8361
8362 <p>In C++ inheritance can be used to achieve two different goals.
8363 We can employ inheritance to reuse common data and functionality
8364 in multiple classes. For example:</p>
8365
8366 <pre class="cxx">
8367 class person
8368 {
8369 public:
8370 const std::string&amp; first () const;
8371 const std::string&amp; last () const;
8372
8373 private:
8374 std::string first_;
8375 std::string last_;
8376 };
8377
8378 class employee: public person
8379 {
8380 ...
8381 };
8382
8383 class contractor: public person
8384 {
8385 ...
8386 };
8387 </pre>
8388
8389 <p>In the above example both the <code>employee</code> and
8390 <code>contractor</code> classes inherit the <code>first_</code>
8391 and <code>last_</code> data members as well as the <code>first()</code>
8392 and <code>last()</code> accessors from the <code>person</code> base
8393 class.</p>
8394
8395 <p>A common trait of this inheritance style, referred to as <em>reuse
8396 inheritance</em> from now on, is the lack of virtual functions and
8397 a virtual destructor in the base class. Also with this style the
8398 application code is normally written in terms of the derived classes
8399 instead of the base.</p>
8400
8401 <p>The second way to utilize inheritance in C++ is to provide polymorphic
8402 behavior through a common interface. In this case the base class
8403 defines a number of virtual functions and, normally, a virtual
8404 destructor while the derived classes provide specific
8405 implementations of these virtual functions. For example:</p>
8406
8407 <pre class="cxx">
8408 class person
8409 {
8410 public:
8411 enum employment_status
8412 {
8413 unemployed,
8414 temporary,
8415 permanent,
8416 self_employed
8417 };
8418
8419 virtual employment_status
8420 employment () const = 0;
8421
8422 virtual
8423 ~person ();
8424 };
8425
8426 class employee: public person
8427 {
8428 public:
8429 virtual employment_status
8430 employment () const
8431 {
8432 return temporary_ ? temporary : permanent;
8433 }
8434
8435 private:
8436 bool temporary_;
8437 };
8438
8439 class contractor: public person
8440 {
8441 public:
8442 virtual employment_status
8443 employment () const
8444 {
8445 return self_employed;
8446 }
8447 };
8448 </pre>
8449
8450 <p>With this inheritance style, which we will call <em>polymorphism
8451 inheritance</em>, the application code normally works with derived
8452 classes via the base class interface. Note also that it is very common
8453 to mix both styles in the same hierarchy. For example, the above two
8454 code fragments can be combined so that the <code>person</code> base
8455 class provides the common data members and functions as well as
8456 defines the polymorphic interface.</p>
8457
8458 <p>The following sections describe the available strategies for
8459 mapping reuse and polymorphism inheritance styles to a relational
8460 data model. Note also that the distinction between the two styles is
8461 conceptual rather than formal. For example, it is possible to treat
8462 a class hierarchy that defines virtual functions as a case of reuse
8463 inheritance if this results in the desired database mapping and
8464 semantics.</p>
8465
8466 <p>Generally, classes that employ reuse inheritance are mapped to
8467 completely independent entities in the database. They use different
8468 object id spaces and should always be passed to and returned from
8469 the database operations as pointers or references to derived types.
8470 In other words, from the persistence point of view, such classes
8471 behave as if the data members from the base classes were copied
8472 verbatim into the derived ones.</p>
8473
8474 <p>In contrast, classes that employ polymorphism inheritance share
8475 the object id space and can be passed to and returned from the
8476 database operations <em>polymorphically</em> as pointers or
8477 references to the base class.</p>
8478
8479 <p>For both inheritance styles it is sometimes desirable to prevent
8480 instances of a base class from being stored in the database.
8481 To achieve this a persistent
8482 class can be declared abstract using the <code>db&nbsp;abstract</code>
8483 pragma (<a href="#14.1.3">Section 14.1.3, "<code>abstract</code>"</a>).
8484 Note that a <em>C++-abstract</em> class, or a class that
8485 has one or more pure virtual functions and therefore cannot be
8486 instantiated, is also <em>database-abstract</em>. However, a
8487 database-abstract class is not necessarily C++-abstract. The
8488 ODB compiler automatically treats C++-abstract classes as
8489 database-abstract.</p>
8490
8491 <h2><a name="8.1">8.1 Reuse Inheritance</a></h2>
8492
8493 <p>Each non-abstract class from the reuse inheritance hierarchy is
8494 mapped to a separate database table that contains all its data
8495 members, including those inherited from base classes. An abstract
8496 persistent class does not have to define an object id, nor a default
8497 constructor, and it does not have a corresponding database table.
8498 An abstract class cannot be a pointed-to object in a relationship.
8499 Multiple inheritance is supported as long as each base
8500 class is only inherited once. The following example shows a
8501 persistent class hierarchy employing reuse inheritance:</p>
8502
8503 <pre class="cxx">
8504 // Abstract person class. Note that it does not declare the
8505 // object id.
8506 //
8507 #pragma db object abstract
8508 class person
8509 {
8510 ...
8511
8512 std::string first_;
8513 std::string last_;
8514 };
8515
8516 // Abstract employee class. It derives from the person class and
8517 // declares the object id for all the concrete employee types.
8518 //
8519 #pragma db object abstract
8520 class employee: public person
8521 {
8522 ...
8523
8524 #pragma db id auto
8525 unsigned long id_;
8526 };
8527
8528 // Concrete permanent_employee class. Note that it doesn't define
8529 // any data members of its own.
8530 //
8531 #pragma db object
8532 class permanent_employee: public employee
8533 {
8534 ...
8535 };
8536
8537 // Concrete temporary_employee class. It adds the employment
8538 // duration in months.
8539 //
8540 #pragma db object
8541 class temporary_employee: public employee
8542 {
8543 ...
8544
8545 unsigned long duration_;
8546 };
8547
8548 // Concrete contractor class. It derives from the person class
8549 // (and not employee; an independent contractor is not considered
8550 // an employee). We use the contractor's external email address
8551 // as the object id.
8552 //
8553 #pragma db object
8554 class contractor: public person
8555 {
8556 ...
8557
8558 #pragma db id
8559 std::string email_;
8560 };
8561 </pre>
8562
8563 <p>The sample database schema for this hierarchy is shown below.</p>
8564
8565 <pre class="sql">
8566 CREATE TABLE permanent_employee (
8567 first TEXT NOT NULL,
8568 last TEXT NOT NULL,
8569 id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT);
8570
8571 CREATE TABLE temporary_employee (
8572 first TEXT NOT NULL,
8573 last TEXT NOT NULL,
8574 id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
8575 duration BIGINT UNSIGNED NOT NULL);
8576
8577 CREATE TABLE contractor (
8578 first TEXT NOT NULL,
8579 last TEXT NOT NULL,
8580 email VARCHAR (255) NOT NULL PRIMARY KEY);
8581 </pre>
8582
8583 <p>The complete version of the code presented in this section is
8584 available in the <code>inheritance/reuse</code> example in the
8585 <code>odb-examples</code> package.</p>
8586
8587 <h2><a name="8.2">8.2 Polymorphism Inheritance</a></h2>
8588
8589 <p>There are three general approaches to mapping a polymorphic
8590 class hierarchy to a relational database. These are
8591 <em>table-per-hierarchy</em>, <em>table-per-difference</em>,
8592 and <em>table-per-class</em>. With the table-per-hierarchy
8593 mapping, all the classes in a hierarchy are stored in a single,
8594 "wide" table. <code>NULL</code> values are stored in columns
8595 corresponding to data members of derived classes that are
8596 not present in any particular instance.</p>
8597
8598 <p>In the table-per-difference mapping, each class is mapped
8599 to a separate table. For a derived class, this table contains
8600 only columns corresponding to the data members added by this
8601 derived class.</p>
8602
8603 <p>Finally, in the table-per-class mapping, each class is mapped
8604 to a separate table. For a derived class, this table contains
8605 columns corresponding to all the data members, from this derived
8606 class all the way down to the root of the hierarchy.</p>
8607
8608 <p>The table-per-difference mapping is generally considered as
8609 having the best balance of flexibility, performance, and space
8610 efficiency. It also results in a more canonical relational
8611 database model compared to the other two approaches. As a
8612 result, this is the mapping currently implemented in ODB.
8613 Other mappings may be supported in the future.</p>
8614
8615 <p>A pointer or reference to an ordinary, non-polymorphic object
8616 has just one type &mdash; the class type of that object. When we
8617 start working with polymorphic objects, there are two types
8618 to consider: the <em>static type</em>, or the declaration type
8619 of a reference or pointer, and the object's actual or <em>dynamic
8620 type</em>. An example will help illustrate the difference:</p>
8621
8622 <pre class="cxx">
8623 class person {...};
8624 class employee: public person {...};
8625
8626 person p;
8627 employee e;
8628
8629 person&amp; r1 (p);
8630 person&amp; r2 (e);
8631
8632 auto_ptr&lt;person> p1 (new employee);
8633 </pre>
8634
8635 <p>In the above example, the <code>r1</code> reference's both static
8636 and dynamic types are <code>person</code>.
8637 In contrast, the <code>r2</code> reference's static type is
8638 <code>person</code> while its dynamic type (the actual object
8639 that it refers to) is <code>employee</code>. Similarly,
8640 <code>p1</code> points to the object of the <code>person</code>
8641 static type but <code>employee</code> dynamic type.</p>
8642
8643 <p>In C++, the primary mechanisms for working with polymorphic objects
8644 are virtual functions. We call a virtual function only knowing the
8645 object's static type, but the version corresponding to the object's
8646 dynamic type is automatically executed. This is the essence of
8647 runtime polymorphism support in C++: we can operate in terms of a base
8648 class interface but get the derived class' behavior. Similarly, the
8649 essence of the runtime polymorphism support in ODB is to allow us to
8650 persist, load, update, and query in terms of the base class interface
8651 but have the derived class actually stored in the database.</p>
8652
8653 <p>To declare a persistent class as polymorphic we use the
8654 <code>db&nbsp;polymorphic</code> pragma. We only need to
8655 declare the root class of a hierarchy as polymorphic; ODB will
8656 treat all the derived classes as polymorphic automatically. For
8657 example:</p>
8658
8659 <pre class="cxx">
8660 #pragma db object polymorphic
8661 class person
8662 {
8663 ...
8664
8665 virtual
8666 ~person () = 0; // Automatically abstract.
8667
8668 #pragma db id auto
8669 unsigned long id_;
8670
8671 std::string first_;
8672 std::string last_;
8673 };
8674
8675 #pragma db object
8676 class employee: public person
8677 {
8678 ...
8679
8680 bool temporary_;
8681 };
8682
8683 #pragma db object
8684 class contractor: public person
8685 {
8686
8687 std::string email_;
8688 };
8689 </pre>
8690
8691 <p>A persistent class hierarchy declared polymorphic must also be
8692 polymorphic in the C++ sense, that is, the root class must
8693 declare or inherit at least one virtual function. It is
8694 recommended that the root class also declares a virtual destructor.
8695 The root class of the polymorphic hierarchy must contain
8696 the data member designated as object id (a persistent class
8697 without an object id cannot be polymorphic). Note also that,
8698 unlike reuse inheritance, abstract polymorphic classes have
8699 a table in the database, just like non-abstract classes.</p>
8700
8701 <p>Persistent classes in the same polymorphic hierarchy must use the
8702 same kind of object pointer (<a href="#3.3">Section 3.3,
8703 "Object and View Pointers"</a>). If the object pointer
8704 for the root class is specified as a template or using the
8705 special raw pointer syntax (<code>*</code>), then the ODB
8706 compiler will automatically use the same object pointer
8707 for all the derived classes. For example:</p>
8708
8709 <pre class="cxx">
8710 #pragma db object polymorphic pointer(std::shared_ptr)
8711 class person
8712 {
8713 ...
8714 };
8715
8716 #pragma db object // Object pointer is std::shared_ptr&lt;employee>.
8717 class employee: public person
8718 {
8719 ...
8720 };
8721
8722 #pragma db object // Object pointer is std::shared_ptr&lt;contractor>.
8723 class contractor: public person
8724 {
8725 ...
8726 };
8727 </pre>
8728
8729 <p>Similarly, if we enable or disable session support
8730 (<a href="#11">Chapter 11, "Session"</a>) for the root class, then
8731 the ODB compiler will automatically enable or disable it for all
8732 the derived classes.</p>
8733
8734 <p>For polymorphic persistent classes, all the database operations can
8735 be performed on objects with different static and dynamic types.
8736 Similarly, operations that load persistent objects from the
8737 database (<code>load()</code>, <code>query()</code>, etc.), can
8738 return objects with different static and dynamic types. For
8739 example:</p>
8740
8741 <pre class="cxx">
8742 unsigned long id1, id2;
8743
8744 // Persist.
8745 //
8746 {
8747 shared_ptr&lt;person> p1 (new employee (...));
8748 shared_ptr&lt;person> p2 (new contractor (...));
8749
8750 transaction t (db.begin ());
8751 id1 = db.persist (p1); // Stores employee.
8752 id2 = db.persist (p2); // Stores contractor.
8753 t.commit ();
8754 }
8755
8756 // Load.
8757 //
8758 {
8759 shared_ptr&lt;person> p;
8760
8761 transaction t (db.begin ());
8762 p = db.load&lt;person> (id1); // Loads employee.
8763 p = db.load&lt;person> (id2); // Loads contractor.
8764 t.commit ();
8765 }
8766
8767 // Query.
8768 //
8769 {
8770 typedef odb::query&lt;person> query;
8771 typedef odb::result&lt;person> result;
8772
8773 transaction t (db.begin ());
8774
8775 result r (db.query&lt;person> (query::last == "Doe"));
8776
8777 for (result::iterator i (r.begin ()); i != r.end (); ++i)
8778 {
8779 person&amp; p (*i); // Can be employee or contractor.
8780 }
8781
8782 t.commit ();
8783 }
8784
8785 // Update.
8786 //
8787 {
8788 shared_ptr&lt;person> p;
8789 shared_ptr&lt;employee> e;
8790
8791 transaction t (db.begin ());
8792
8793 e = db.load&lt;employee> (id1);
8794 e->temporary (false);
8795 p = e;
8796 db.update (p); // Updates employee.
8797
8798 t.commit ();
8799 }
8800
8801 // Erase.
8802 //
8803 {
8804 shared_ptr&lt;person> p;
8805
8806 transaction t (db.begin ());
8807 p = db.load&lt;person> (id1); // Loads employee.
8808 db.erase (p); // Erases employee.
8809 db.erase&lt;person> (id2); // Erases contractor.
8810 t.commit ();
8811 }
8812 </pre>
8813
8814
8815 <p>The table-per-difference mapping, as supported by ODB, requires
8816 two extra columns, in addition to those corresponding to the
8817 data members. The first, called <em>discriminator</em>, is added
8818 to the table corresponding to the root class of the hierarchy.
8819 This column is used to determine the dynamic type of each
8820 object. The second column is added to tables corresponding
8821 to the derived classes and contains the object id. This
8822 column is used to form a foreign key constraint referencing
8823 the root class table.</p>
8824
8825 <p>When querying the database for polymorphic objects, it is
8826 possible to obtain the discriminator value without
8827 instantiating the object. For example:</p>
8828
8829 <pre class="cxx">
8830 typedef odb::query&lt;person> query;
8831 typedef odb::result&lt;person> result;
8832
8833 transaction t (db.begin ());
8834
8835 result r (db.query&lt;person> (query::last == "Doe"));
8836
8837 for (result::iterator i (r.begin ()); i != r.end (); ++i)
8838 {
8839 std::string d (i.discriminator ());
8840 ...
8841 }
8842
8843 t.commit ();
8844 </pre>
8845
8846 <p>In the current implementation, ODB has limited support for
8847 customizing names, types, and values of the extra columns.
8848 Currently, the discriminator column is always called
8849 <code>typeid</code> and contains a namespace-qualified class
8850 name (for example, <code>"employee"</code> or
8851 <code>"hr::employee"</code>). The id column in the derived
8852 class table has the same name as the object id column in
8853 the root class table. Future versions of ODB will add support
8854 for customizing these extra columns.</p>
8855
8856 <p>The sample database schema for the above polymorphic hierarchy
8857 is shown below.</p>
8858
8859 <pre class="sql">
8860 CREATE TABLE person (
8861 id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
8862 typeid VARCHAR(255) NOT NULL,
8863 first TEXT NOT NULL,
8864 last TEXT NOT NULL);
8865
8866 CREATE TABLE employee (
8867 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8868 temporary TINYINT(1) NOT NULL,
8869
8870 CONSTRAINT employee_id_fk
8871 FOREIGN KEY (id)
8872 REFERENCES person (id)
8873 ON DELETE CASCADE);
8874
8875 CREATE TABLE contractor (
8876 id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
8877 email TEXT NOT NULL,
8878
8879 CONSTRAINT contractor_id_fk
8880 FOREIGN KEY (id)
8881 REFERENCES person (id)
8882 ON DELETE CASCADE);
8883 </pre>
8884
8885 <p>The complete version of the code presented in this section is
8886 available in the <code>inheritance/polymorphism</code> example
8887 in the <code>odb-examples</code> package.</p>
8888
8889 <h3><a name="8.2.1">8.2.1 Performance and Limitations</a></h3>
8890
8891 <p>A database operation on a non-polymorphic object normally translates
8892 to a single database statement execution (objects with containers
8893 and eager object pointers can be the exception). Because polymorphic
8894 objects have their data members
8895 stored in multiple tables, some database operations on such objects
8896 may result in multiple database statements being executed while others
8897 may require more complex statements. There is also some functionality
8898 that is not available to polymorphic objects.</p>
8899
8900 <p>The first part of this section discusses the performance implications
8901 to keep in mind when designing and working with polymorphic hierarchies.
8902 The second part talks about limitations of polymorphic objects.</p>
8903
8904 <p>The most important aspect of a polymorphic hierarchy that
8905 affects database performance is its depth. The distance between
8906 the root of the hierarchy and the derived class translates
8907 directly to the number of database statements that will have to
8908 be executed in order to persist, update, or erase this derived class.
8909 It also translates directly to the number of SQL <code>JOIN</code>
8910 clauses that will be needed to load or query the database for this
8911 derived class. As a result, to achieve best performance, we should
8912 try to keep our polymorphic hierarchies as flat as possible.</p>
8913
8914 <p>When loading an object or querying the database for objects,
8915 ODB will need to execute two statements if this object's static
8916 and dynamic types are different but only one statement if
8917 they are the same. This example will help illustrate the
8918 difference:</p>
8919
8920 <pre class="cxx">
8921 unsigned long id;
8922
8923 {
8924 employee e (...);
8925
8926 transaction t (db.begin ());
8927 id = db.persist (e);
8928 t.commit ();
8929 }
8930
8931 {
8932 shared_ptr&lt;person> p;
8933
8934 transaction t (db.begin ());
8935 p = db.load&lt;person> (id); // Requires two statement.
8936 p = db.load&lt;employee> (id); // Requires only one statement.
8937 t.commit ();
8938 }
8939 </pre>
8940
8941 <p>As a result, we should try to load and query using the most
8942 derived class possible.</p>
8943
8944 <p>Finally, for polymorphic objects, erasing via the object instance
8945 is faster than erasing via its object id. In the former case the
8946 object's dynamic type can be determined locally in the application
8947 while in the latter case an extra statement has to be executed to
8948 achieve the same result. For example:</p>
8949
8950 <pre class="cxx">
8951 shared_ptr&lt;person> p = ...;
8952
8953 transaction t (db.begin ());
8954 db.erase&lt;person> (p.id ()); // Slower (executes extra statement).
8955 db.erase (p); // Faster.
8956 t.commit ();
8957 </pre>
8958
8959 <p>Polymorphic objects can use all the mechanisms that are available
8960 to ordinary objects. These include containers (<a href="#5">Chapter 5,
8961 "Containers"</a>), object relationships, including to polymorphic
8962 objects (<a href="#6">Chapter 6, "Relationships"</a>), views
8963 (<a href="#10">Chapter 10, "Views"</a>), session (<a href="#11">Chapter
8964 11, "Session"</a>), and optimistic concurrency (<a href="#12">Chapter
8965 12, "Optimistic Concurrency"</a>). There are, however, a few
8966 limitations, mainly due to the underlying use of SQL to access the
8967 data.</p>
8968
8969 <p>When a polymorphic object is "joined" in a view, and the join
8970 condition (either in the form of an object pointer or a custom
8971 condition) comes from the object itself (as opposed to one of
8972 the objects joined previously), then this condition must only
8973 use data members from the derived class. For example, consider
8974 the following polymorphic object hierarchy and a view:</p>
8975
8976
8977 <pre class="cxx">
8978 #pragma db object polymorphic
8979 class employee
8980 {
8981 ...
8982 };
8983
8984 #pragma db object
8985 class permanent_employee: public employee
8986 {
8987 ...
8988 };
8989
8990 #pragma db object
8991 class temporary_employee: public employee
8992 {
8993 ...
8994
8995 shared_ptr&lt;permanent_employee> manager_;
8996 };
8997
8998 #pragma db object
8999 class contractor: public temporary_employee
9000 {
9001 shared_ptr&lt;permanent_employee> manager_;
9002 };
9003
9004 #pragma db view object(permanent_employee) \
9005 object(contractor: contractor::manager_)
9006 struct contractor_manager
9007 {
9008 ...
9009 };
9010 </pre>
9011
9012 <p>This view will not function correctly because the join condition
9013 (<code>manager_</code>) comes from the base class
9014 (<code>temporary_employee</code>) instead of the derived
9015 (<code>contractor</code>). The reason for this limitation is the
9016 <code>JOIN</code> clause order in the underlying SQL <code>SELECT</code>
9017 statement. In the view presented above, the table corresponding
9018 to the base class (<code>temporary_employee</code>) will have to
9019 be joined first which will result in this view matching both
9020 the <code>temporary_employee</code> and <code>contractor</code>
9021 objects instead of just <code>contractor</code>. It is usually
9022 possible to resolve this issue by reordering the objects in the
9023 view. Our example, for instance, can be fixed by swapping the
9024 two objects:</p>
9025
9026 <pre class="cxx">
9027 #pragma db view object(contractor) \
9028 object(permanent_employee: contractor::manager_)
9029 struct contractor_manager
9030 {
9031 ...
9032 };
9033 </pre>
9034
9035 <p>The <code>erase_query()</code> database function (<a href="#3.11">Section
9036 3.11, "Deleting Persistent Objects"</a>) also has limited functionality
9037 when used on polymorphic objects. Because many database implementations
9038 do not support <code>JOIN</code> clauses in the SQL <code>DELETE</code>
9039 statement, only data members from the derived class being erased can
9040 be used in the query condition. For example:</p>
9041
9042 <pre class="cxx">
9043 typedef odb::query&lt;employee> query;
9044
9045 transaction t (db.begin ());
9046 db.erase_query&lt;employee> (query::permanent); // Ok.
9047 db.erase_query&lt;employee> (query::last == "Doe"); // Error.
9048 t.commit ();
9049 </pre>
9050
9051 <h2><a name="8.3">8.3 Mixed Inheritance</a></h2>
9052
9053 <p>It is possible to mix the reuse and polymorphism inheritance
9054 styles in the same hierarchy. In this case, the reuse inheritance
9055 must be used for the "bottom" (base) part of the hierarchy while
9056 the polymorphism inheritance &mdash; for the "top" (derived) part.
9057 For example:</p>
9058
9059 <pre class="cxx">
9060 #pragma db object
9061 class person
9062 {
9063 ...
9064 };
9065
9066 #pragma db object polymorphic
9067 class employee: public person // Reuse inheritance.
9068 {
9069 ...
9070 };
9071
9072 #pragma db object
9073 class temporary_employee: public employee // Polymorphism inheritance.
9074 {
9075 ...
9076 };
9077
9078 #pragma db object
9079 class permanent_employee: public employee // Polymorphism inheritance.
9080 {
9081 ...
9082 };
9083 </pre>
9084
9085
9086 <!-- CHAPTER -->
9087
9088
9089 <hr class="page-break"/>
9090 <h1><a name="9">9 Sections</a></h1>
9091
9092 <p>ODB sections are an optimization mechanism that allows us to
9093 partition data members of a persistent class into groups that
9094 can be separately loaded and/or updated. This can be useful,
9095 for example, if an object contains expensive to load or update
9096 data members (such as <code>BLOB</code>s or containers) and
9097 that are accessed or modified infrequently. For example:</p>
9098
9099 <pre class="cxx">
9100 #include &lt;odb/section.hxx>
9101
9102 #pragma db object
9103 class person
9104 {
9105 ...
9106
9107 #pragma db load(lazy) update(manual)
9108 odb::section keys_;
9109
9110 #pragma db section(keys_) type("BLOB")
9111 char public_key_[1024];
9112
9113 #pragma db section(keys_) type("BLOB")
9114 char private_key_[1024];
9115 };
9116
9117 transaction t (db.begin ());
9118
9119 auto_ptr&lt;person> p (db.load&lt;person> (...)); // Keys are not loaded.
9120
9121 if (need_keys)
9122 {
9123 db.load (*p, p->keys_); // Load keys.
9124 ...
9125 }
9126
9127 db.update (*p); // Keys are not updated.
9128
9129 if (update_keys)
9130 {
9131 ...
9132 db.update (*p, p->keys_); // Update keys.
9133 }
9134
9135 t.commit ();
9136 </pre>
9137
9138 <p>A complete example that shows how to use sections is available in
9139 the <code>section</code> directory in the <code>odb-examples</code>
9140 package.</p>
9141
9142 <p>Why do we need to group data members into sections? Why can't
9143 each data member be loaded and updated independently if and
9144 when necessary? The reason for this requirement is that loading
9145 or updating a group of data members with a single database
9146 statement is significantly more efficient than loading or updating
9147 each data member with a separate statement. Because ODB
9148 prepares and caches statements used to load and update
9149 persistent objects, generating a custom statement for
9150 a specific set of data members that need to be loaded or
9151 updated together is not a viable approach either. To resolve
9152 this, ODB allows us to group data members that are
9153 often updated and/or loaded together into sections. To
9154 achieve the best performance, we should aim to find a balance
9155 between having too many sections with too few data
9156 members and too few sections with too many data
9157 members. We can use the access and modification patterns
9158 of our application as a base for this decision.</p>
9159
9160 <p>To add a new section to a persistent class we declare a new
9161 data member of the <code>odb::section</code> type. At this
9162 point we also need to specify the loading and updating behavior
9163 of this section with the <code>db&nbsp;load</code> and
9164 <code>db&nbsp;update</code> pragmas, respectively.</p>
9165
9166 <p>The loading behavior of a section can be either <code>eager</code>
9167 or <code>lazy</code>. An eager-loaded section is always loaded as
9168 part of the object load. A lazy-loaded section is not loaded
9169 as part of the object load and has to be explicitly loaded with
9170 the <code>database::load()</code> function (discussed below) if
9171 and when necessary.</p>
9172
9173 <p>The updating behavior of a section can be <code>always</code>,
9174 <code>change</code>, or <code>manual</code>. An always-updated
9175 section is always updated as part of the object update,
9176 provided it has been loaded. A change-updated section
9177 is only updated as part of the object update if it has been loaded
9178 and marked as changed. A manually-updated section is never updated
9179 as part of the object update and has to be explicitly updated with
9180 the <code>database::update()</code> function (discussed below) if
9181 and when necessary.</p>
9182
9183 <p>If no loading behavior is specified explicitly, then an eager-loaded
9184 section is assumed. Similarly, if no updating behavior is specified,
9185 then an always-updated section is assumed. An eager-loaded, always-updated
9186 section is pointless and therefore illegal. Only persistent classes
9187 with an object id can have sections.</p>
9188
9189 <p>To specify that a data member belongs to a section we use the
9190 <code>db&nbsp;section</code> pragma with the section's member
9191 name as its single argument. Except for special data members
9192 such as the object id and optimistic concurrency version, any
9193 direct, non-transient member of a persistent class can belong
9194 to a section, including composite values, containers, and
9195 pointers to objects. For example:</p>
9196
9197 <pre class="cxx">
9198 #pragma db value
9199 class text
9200 {
9201 std::string data;
9202 std::string lang;
9203 };
9204
9205 #pragma db object
9206 class person
9207 {
9208 ...
9209
9210 #pragma db load(lazy)
9211 odb::section extras_;
9212
9213 #pragma db section(extras_)
9214 text bio_;
9215
9216 #pragma db section(extras_)
9217 std::vector&lt;std::string> nicknames_;
9218
9219 #pragma db section(extras_)
9220 std::shared_ptr&lt;person> emergency_contact_;
9221 };
9222 </pre>
9223
9224 <p>An empty section is pointless and therefore illegal, except
9225 in abstract or polymorphic classes where data members can be
9226 added to a section by derived classes (see <a href="#9.1">Section
9227 9.1, "Sections and Inheritance"</a>).</p>
9228
9229 <p>The <code>odb::section</code> class is defined in the
9230 <code>&lt;odb/section.hxx></code> header file and has the
9231 following interface:</p>
9232
9233 <pre class="cxx">
9234 namespace odb
9235 {
9236 class section
9237 {
9238 public:
9239 // Load state.
9240 //
9241 bool
9242 loaded () const;
9243
9244 void
9245 unload ();
9246
9247 // Change state.
9248 //
9249 bool
9250 changed () const;
9251
9252 void
9253 change ();
9254
9255 // User data.
9256 //
9257 unsigned char
9258 user_data () const;
9259
9260 void
9261 user_data (unsigned char);
9262 };
9263 }
9264 </pre>
9265
9266 <p>The <code>loaded()</code> accessor can be used to determine
9267 whether a section is already loaded. The <code>unload()</code>
9268 modifier marks a loaded section as not loaded. This, for example,
9269 can be useful if you don't want the section to be reloaded during
9270 the object reload.</p>
9271
9272 <p>The <code>changed()</code> accessor can be used to query the
9273 section's change state. The <code>change()</code> modifier
9274 marks the section as changed. It is valid to call this modifier
9275 for an unloaded (or transient) section, however, the state will
9276 be reset back to unchanged once the section (or object) is loaded.
9277 The change state is only relevant to sections with change-updated
9278 behavior and is ignored for all other sections.</p>
9279
9280 <p>The size of the section class is one byte with four bits available
9281 to store a custom state via the <code>user_data()</code> accessor
9282 and modifier.</p>
9283
9284 <p>The <code>odb::database</code> class provides special
9285 versions of the <code>load()</code> and <code>update()</code>
9286 functions that allow us to load and update sections of a
9287 persistent class. Their signatures are as follows:</p>
9288
9289 <pre class="cxx">
9290 template &lt;typename T>
9291 void
9292 load (T&amp; object, section&amp;);
9293
9294 template &lt;typename T>
9295 void
9296 update (const T&amp; object, const section&amp;);
9297 </pre>
9298
9299 <p>Before calling the section <code>load()</code> function, the
9300 object itself must already be loaded. If the section is already
9301 loaded, then the call to <code>load()</code> will reload its
9302 data members. It is illegal to explicitly load an eager-loaded
9303 section.</p>
9304
9305 <p>Before calling the section <code>update()</code> function, the
9306 section (and therefore the object) must be in the loaded state.
9307 If the section is not loaded, the <code>odb::section_not_loaded</code>
9308 exception is thrown. The section <code>update()</code> function
9309 does not check but does clear the section's change state. In
9310 other words, section <code>update()</code> will always update
9311 section data members in the database and clear the change flag.
9312 Note also that any section, that is, always-, change-, or
9313 manually-updated, can be explicitly updated with this function.</p>
9314
9315 <p>Both section <code>load()</code> and <code>update()</code>, just
9316 like the rest of the database operations, must be performed within
9317 a transaction. Notice also that both <code>load()</code> and
9318 <code>update()</code> expect a reference to the section as
9319 their second argument. This reference must refer to the data
9320 member in the object passed as the first argument. If instead
9321 it refers to some other instance of the <code>section</code>
9322 class, for example, a local copy or a temporary, then the
9323 <code>odb::section_not_in_object</code> exception is thrown.
9324 For example:</p>
9325
9326 <pre class="cxx">
9327 #pragma db object
9328 class person
9329 {
9330 public:
9331 ...
9332
9333 odb::section
9334 keys () const {return keys_;}
9335
9336 private:
9337 odb::section keys_;
9338
9339 ...
9340 };
9341
9342 auto_ptr&lt;person> p (db.load&lt;person> (...));
9343
9344 section s (p->keys ());
9345 db.load (*p, s); // Throw section_not_in_object, copy.
9346
9347 db.update (*p, p->keys ()); // Throw section_not_in_object, copy.
9348 </pre>
9349
9350 <p>At first glance it may seem more appropriate to make the
9351 <code>section</code> class non-copyable in order to prevent
9352 such errors from happening. However, it is perfectly reasonable
9353 to expect to be able to copy (or assign) sections as part of
9354 the object copying (or assignment). As a result, sections are
9355 left copyable and copy-assignable, however, this functionality
9356 should not be used in accessors or modifiers. Instead, section
9357 accessors and modifiers should always be by-reference. Here is
9358 how we can fix our previous example:</p>
9359
9360 <pre class="cxx">
9361 #pragma db object
9362 class person
9363 {
9364 public:
9365 ...
9366
9367 const odb::section&amp;
9368 keys () const {return keys_;}
9369
9370 odb::section&amp;
9371 keys () {return keys_;}
9372
9373 private:
9374 odb::section keys_;
9375
9376 ...
9377 };
9378
9379 auto_ptr&lt;person> p (db.load&lt;person> (...));
9380
9381 section&amp; s (p->keys ());
9382 db.load (*p, s); // Ok, reference.
9383
9384 db.update (*p, p->keys ()); // Ok, reference.
9385 </pre>
9386
9387 <p>Several other database operations affect sections. The state of
9388 a section in a transient object is undefined. That is, before
9389 the call to object <code>persist()</code> or <code>load()</code>
9390 functions, or after the call to object <code>erase()</code>
9391 function, the values returned by the <code>section::loaded()</code> and
9392 <code>section::changed()</code> accessors are undefined.</p>
9393
9394 <p>After the call to <code>persist()</code>, all sections, including
9395 eager-loaded ones, are marked as loaded and unchanged. If instead we
9396 are loading an object with the <code>load()</code> call or as
9397 a result of a query, then eager-loaded sections are loaded
9398 and marked as loaded and unchanged while lazy-loaded ones are marked
9399 as unloaded. If a lazy-loaded section is later loaded with the
9400 section <code>load()</code> call, then it is marked as loaded and
9401 unchanged.</p>
9402
9403 <p>When we update an object with the <code>update()</code> call,
9404 manually-updated sections are ignored while always-updated
9405 sections are updated if they are loaded. Change-updated
9406 sections are only updated if they are both loaded and marked
9407 as changed. After the update, such sections are reset to the
9408 unchanged state. When we reload an object with the
9409 <code>reload()</code> call, sections that were loaded are
9410 automatically reloaded and reset to the unchanged state.</p>
9411
9412 <p>To further illustrate the state transitions of a section,
9413 consider this example:</p>
9414
9415 <pre class="cxx">
9416 #pragma db object
9417 class person
9418 {
9419 ...
9420
9421 #pragma db load(lazy) update(change)
9422 odb::section keys_;
9423
9424 ...
9425 };
9426
9427 transaction t (db.begin ());
9428
9429 person p ("John", "Doe"); // Section state is undefined (transient).
9430
9431 db.persist (p); // Section state: loaded, unchanged.
9432
9433 auto_ptr&lt;person> l (
9434 db.load&lt;person> (...)); // Section state: unloaded, unchanged.
9435
9436 db.update (*l); // Section not updated since not loaded.
9437 db.update (p); // Section not updated since not changed.
9438
9439 p.keys_.change (); // Section state: loaded, changed.
9440 db.update (p); // Section updated, state: loaded, unchanged.
9441
9442 db.update (*l, l->keys_); // Throw section_not_loaded.
9443 db.update (p, p.keys_); // Section updated even though not changed.
9444
9445 db.reload (*l); // Section not reloaded since not loaded.
9446 db.reload (p); // Section reloaded, state: loaded, unchanged.
9447
9448 db.load (*l, l->keys_); // Section loaded, state: loaded, unchanged.
9449 db.load (p, p.keys_); // Section reloaded, state: loaded, unchanged.
9450
9451 db.erase (p); // Section state is undefined (transient).
9452
9453 t.commit ();
9454 </pre>
9455
9456 <p>When using change-updated behavior, it is our responsibility to
9457 mark the section as changed when any of the data members belonging
9458 to this section is modified. A natural place to mark the section
9459 as changed is the modifiers for section data members, for example:</p>
9460
9461 <pre class="cxx">
9462 #pragma db object
9463 class person
9464 {
9465 ...
9466
9467 typedef std::array&lt;char, 1024> key_type;
9468
9469 const key_type&amp;
9470 public_key () const {return public_key_;}
9471
9472 void
9473 public_key (const key_type&amp; k)
9474 {
9475 public_key_ = k;
9476 keys_.change ();
9477 }
9478
9479 const key_type&amp;
9480 private_key () const {return private_key_;}
9481
9482 void
9483 private_key (const key_type&amp; k)
9484 {
9485 private_key_ = k;
9486 keys_.change ();
9487 }
9488
9489 private:
9490 #pragma db load(lazy) update(change)
9491 odb::section keys_;
9492
9493 #pragma db section(keys_) type("BLOB")
9494 key_type public_key_;
9495
9496 #pragma db section(keys_) type("BLOB")
9497 key_type private_key_;
9498
9499 ...
9500 };
9501 </pre>
9502
9503 <p>One interesting aspect of change-updated sections is what happens
9504 when a transaction that performed an object or section update is
9505 later rolled back. In this case, while the change state of a
9506 section has been reset (after update), actual changes were not
9507 committed to the database. Change-updated sections handle this
9508 case by automatically registering a rollback callback and then,
9509 if it is called, restoring the original change state. The
9510 following code illustrates this semantics (continuing with
9511 the previous example):</p>
9512
9513 <pre class="cxx">
9514 auto_ptr&lt;person> p;
9515
9516 try
9517 {
9518 transaction t (db.begin ());
9519 p = db.load&lt;person> (...);
9520 db.load (*p, p->keys_);
9521
9522 p->private_key (new_key); // The section is marked changed.
9523 db.update (*p); // The section is reset to unchanged.
9524
9525 throw failed (); // Triggers rollback.
9526 t.commit ();
9527 }
9528 catch (const failed&amp;)
9529 {
9530 // The section is restored back to changed.
9531 }
9532 </pre>
9533
9534
9535 <h2><a name="9.1">9.1 Sections and Inheritance</a></h2>
9536
9537 <p>With both reuse and polymorphism inheritance (<a href="#8">Chapter 8,
9538 "Inheritance"</a>) it is possible to add new sections to derived
9539 classes. It is also possible to add data members from derived
9540 classes to sections declared in the base. For example:</p>
9541
9542 <pre class="cxx">
9543 #pragma db object polymorphic
9544 class person
9545 {
9546 ...
9547
9548 virtual void
9549 print ();
9550
9551 #pragma db load(lazy)
9552 odb::section print_;
9553
9554 #pragma db section(print_)
9555 std::string bio_;
9556 };
9557
9558 #pragma db object
9559 class employee: public person
9560 {
9561 ...
9562
9563 virtual void
9564 print ();
9565
9566 #pragma db section(print_)
9567 std::vector&lt;std::string> employment_history_;
9568 };
9569
9570 transaction t (db.begin ());
9571
9572 auto_ptr&lt;person> p (db.load&lt;person> (...)); // Person or employee.
9573 db.load (*p, p->print_); // Load data members needed for print.
9574 p->print ();
9575
9576 t.commit ();
9577 </pre>
9578
9579 <p>When data members of a section are spread over several classes in a
9580 reuse inheritance hierarchy, both section load and update are
9581 performed with a single database statement. In contrast, with
9582 polymorphism inheritance, section load is performed with a
9583 single statement while update requires a separate statement
9584 for each class that adds to the section.</p>
9585
9586 <p>Note also that in polymorphism inheritance the section-to-object
9587 association is static. Or, in other words, you can load a section
9588 via an object only if its static type actually contains this
9589 section. The following example will help illustrate this
9590 point further:</p>
9591
9592 <pre class="cxx">
9593 #pragma db object polymorphic
9594 class person
9595 {
9596 ...
9597 };
9598
9599 #pragma db object
9600 class employee: public person
9601 {
9602 ...
9603
9604 #pragma db load(lazy)
9605 odb::section extras_;
9606
9607 ...
9608 };
9609
9610 #pragma db object
9611 class manager: public employee
9612 {
9613 ...
9614 };
9615
9616 auto_ptr&lt;manager> m (db.load&lt;manager> (...));
9617
9618 person&amp; p (*m);
9619 employee&amp; e (*m);
9620 section&amp; s (m->extras_);
9621
9622 db.load (p, s); // Error: extras_ is not in person.
9623 db.load (e, s); // Ok: extras_ is in employee.
9624 </pre>
9625
9626 <h2><a name="9.2">9.2 Sections and Optimistic Concurrency</a></h2>
9627
9628 <p>When sections are used in a class with the optimistic concurrency
9629 model (<a href="#12">Chapter 12, "Optimistic Concurrency"</a>),
9630 both section update and load operations compare the object version
9631 to that in the database and throw the <code>odb::object_changed</code>
9632 exception if they do not match. In addition, the section update
9633 operation increments the version to indicate that the object state
9634 has changed. For example:</p>
9635
9636 <pre class="cxx">
9637 #pragma db object optimistic
9638 class person
9639 {
9640 ...
9641
9642 #pragma db version
9643 unsigned long long version_;
9644
9645 #pragma db load(lazy)
9646 odb::section extras_;
9647
9648 #pragma db section(extras_)
9649 std::string bio_;
9650 };
9651
9652 auto_ptr&lt;person> p;
9653
9654 {
9655 transaction t (db.begin ());
9656 p = db.load&lt;person> (...);
9657 t.commit ();
9658 }
9659
9660 {
9661 transaction t (db.begin ());
9662
9663 try
9664 {
9665 db.load (*p, p->extras_); // Throws if object state has changed.
9666 }
9667 catch (const object_changed&amp;)
9668 {
9669 db.reload (*p);
9670 db.load (*p, p->extras_); // Cannot fail.
9671 }
9672
9673 t.commit ();
9674 }
9675 </pre>
9676
9677 <p>Note also that if an object update triggers one or more
9678 section updates, then each such update will increment the
9679 object version. As a result, an update of an object that
9680 contains sections may result in a version increment by
9681 more than one.</p>
9682
9683 <p>When sections are used together with optimistic concurrency and
9684 inheritance, an extra step may be required to enable this
9685 functionality. If you plan to add new sections to derived
9686 classes, then the root class of the hierarchy
9687 (the one that declares the version data member) must be
9688 declared as sectionable with the <code>db&nbsp;sectionable</code>
9689 pragma. For example:</p>
9690
9691 <pre class="cxx">
9692 #pragma db object polymorphic sectionable
9693 class person
9694 {
9695 ...
9696
9697 #pragma db version
9698 unsigned long long version_;
9699 };
9700
9701 #pragma db object
9702 class employee: public person
9703 {
9704 ...
9705
9706 #pragma db load(lazy)
9707 odb::section extras_;
9708
9709 #pragma db section(extras_)
9710 std::vector&lt;std::string> employment_history_;
9711 };
9712 </pre>
9713
9714 <p>This requirement has to do with the need to generate extra
9715 version increment code in the root class that will be used
9716 by sections added in the derived classes. If you forget to
9717 declare the root class as sectionable and later add a
9718 section to one of the derived classes, the ODB compiler
9719 will issue diagnostics.</p>
9720
9721 <h2><a name="9.3">9.3 Sections and Lazy Pointers</a></h2>
9722
9723 <p>If a lazy pointer (<a href="#6.4">Section 6.4, "Lazy Pointers"</a>)
9724 belongs to a lazy-loaded section, then we end up with two levels of
9725 lazy loading. Specifically, when the section is loaded, the lazy
9726 pointer is initialized with the object id but the object itself
9727 is not loaded. For example:</p>
9728
9729 <pre class="cxx">
9730 #pragma db object
9731 class employee
9732 {
9733 ...
9734
9735 #pragma db load(lazy)
9736 odb::section extras_;
9737
9738 #pragma db section(extras_)
9739 odb::lazy_shared_ptr&lt;employer> employer_;
9740 };
9741
9742 transaction t (db.begin ());
9743
9744 auto_ptr&lt;employee> e (db.load&lt;employee> (...)); // employer_ is NULL.
9745
9746 db.load (*e, e->extras_); // employer_ contains valid employer id.
9747
9748 e->employer_.load (); // employer_ points to employer object.
9749
9750 t.commit ();
9751 </pre>
9752
9753 <h2><a name="9.4">9.4 Sections and Change-Tracking Containers</a></h2>
9754
9755 <p>If a change-tracking container (<a href="#5.4">Section 5.4,
9756 "Change-Tracking Containers"</a>) belongs to a change-updated
9757 section, then prior to an object update ODB will check if the
9758 container has been changed and if so, automatically mark the
9759 section as changed. For example:</p>
9760
9761 <pre class="cxx">
9762 #pragma db object
9763 class person
9764 {
9765 ...
9766
9767 #pragma db load(lazy) update(change)
9768 odb::section extras_;
9769
9770 #pragma db section(extras_)
9771 odb::vector&lt;std::string> nicknames_;
9772 };
9773
9774 transaction t (db.begin ());
9775
9776 auto_ptr&lt;person> p (db.load&lt;person> (...));
9777 db.load (*p, p->extras_);
9778
9779 p->nicknames_.push_back ("JD");
9780
9781 db.update (*p); // Section is automatically updated even
9782 // though it was not marked as changed.
9783 t.commit ();
9784 </pre>
9785
9786
9787 <!-- CHAPTER -->
9788
9789
9790 <hr class="page-break"/>
9791 <h1><a name="10">10 Views</a></h1>
9792
9793 <p>An ODB view is a C++ <code>class</code> or <code>struct</code> type
9794 that embodies a light-weight, read-only projection of one or more
9795 persistent objects or database tables or the result of a native SQL
9796 query execution.</p>
9797
9798 <p>Some of the common applications of views include loading a subset
9799 of data members from objects or columns from database tables, executing
9800 and handling results of arbitrary SQL queries, including aggregate
9801 queries and stored procedure calls, as well as joining multiple
9802 objects and/or database tables using object relationships or custom
9803 join conditions.</p>
9804
9805 <p>Many relational databases also define the concept of views. Note,
9806 however, that ODB views are not mapped to database views. Rather,
9807 by default, an ODB view is mapped to an SQL <code>SELECT</code>
9808 query. However, if desired, it is easy to create an ODB view
9809 that is based on a database view.</p>
9810
9811 <p>Usually, views are defined in terms of other persistent entities,
9812 such as persistent objects, database tables, sequences, etc.
9813 Therefore, before we can examine our first view, we need to
9814 define a few persistent objects and a database table. We will
9815 use this model in examples throughout this chapter. Here we
9816 assume that you are familiar with ODB object relationship
9817 support (<a href="#6">Chapter 6, "Relationships"</a>).</p>
9818
9819 <pre class="cxx">
9820 #pragma db object
9821 class country
9822 {
9823 ...
9824
9825 #pragma db id
9826 std::string code_; // ISO 2-letter country code.
9827
9828 std::string name_;
9829 };
9830
9831 #pragma db object
9832 class employer
9833 {
9834 ...
9835
9836 #pragma db id
9837 unsigned long id_;
9838
9839 std::string name_;
9840 };
9841
9842 #pragma db object
9843 class employee
9844 {
9845 ...
9846
9847 #pragma db id
9848 unsigned long id_;
9849
9850 std::string first_;
9851 std::string last_;
9852
9853 unsigned short age_;
9854
9855 shared_ptr&lt;country> residence_;
9856 shared_ptr&lt;country> nationality_;
9857
9858 shared_ptr&lt;employer> employed_by_;
9859 };
9860 </pre>
9861
9862 <p>Besides these objects, we also have the legacy
9863 <code>employee_extra</code> table that is not mapped to any persistent
9864 class. It has the following definition:</p>
9865
9866 <pre class="sql">
9867 CREATE TABLE employee_extra(
9868 employee_id INTEGER NOT NULL,
9869 vacation_days INTEGER NOT NULL,
9870 previous_employer_id INTEGER)
9871 </pre>
9872
9873 <p>The above persistent objects and database table as well as many of
9874 the views shown in this chapter are based on the
9875 <code>view</code> example which can be found in the
9876 <code>odb-examples</code> package of the ODB distribution.</p>
9877
9878 <p>To declare a view we use the <code>db&nbsp;view</code> pragma,
9879 for example:</p>
9880
9881 <pre class="cxx">
9882 #pragma db view object(employee)
9883 struct employee_name
9884 {
9885 std::string first;
9886 std::string last;
9887 };
9888 </pre>
9889
9890 <p>The above example shows one of the simplest views that we can create.
9891 It has a single associated object (<code>employee</code>) and its
9892 purpose is to extract the employee's first and last names without
9893 loading any other data, such as the referenced <code>country</code>
9894 and <code>employer</code> objects.</p>
9895
9896 <p>Views use the same query facility (<a href="#4">Chapter 4, "Querying
9897 the Database"</a>) as persistent objects. Because support for queries
9898 is optional and views cannot be used without this support, you need
9899 to compile any header that defines a view with the
9900 <code>--generate-query</code> ODB compiler option.</p>
9901
9902 <p>To query the database for a view we use the
9903 <code>database::query()</code>, <code>database::query_one()</code>, or
9904 <code>database::query_value()</code> functions in exactly the same way
9905 as we would use them to query the database for an object. For example,
9906 the following code fragment shows how we can find the names of all the
9907 employees that are younger than 31:</p>
9908
9909 <pre class="cxx">
9910 typedef odb::query&lt;employee_name> query;
9911 typedef odb::result&lt;employee_name> result;
9912
9913 transaction t (db.begin ());
9914
9915 result r (db.query&lt;employee_name> (query::age &lt; 31));
9916
9917 for (result::iterator i (r.begin ()); i != r.end (); ++i)
9918 {
9919 const employee_name&amp; en (*i);
9920 cout &lt;&lt; en.first &lt;&lt; " " &lt;&lt; en.last &lt;&lt; endl;
9921 }
9922
9923 t.commit ();
9924 </pre>
9925
9926 <p>A view can be defined as a projection of one or more objects, one
9927 or more tables, a combination of objects and tables, or it can be
9928 the result of a custom SQL query. The following sections discuss each
9929 of these kinds of view in more detail.</p>
9930
9931 <h2><a name="10.1">10.1 Object Views</a></h2>
9932
9933 <p>To associate one or more objects with a view we use the
9934 <code>db&nbsp;object</code> pragma (<a href="#14.2.1">Section
9935 14.2.1, "<code>object</code>"</a>). We have already seen
9936 a simple, single-object view in the introduction to this chapter.
9937 To associate the second and subsequent objects we repeat the
9938 <code>db&nbsp;object</code> pragma for each additional object,
9939 for example:</p>
9940
9941 <pre class="cxx">
9942 #pragma db view object(employee) object(employer)
9943 struct employee_employer
9944 {
9945 std::string first;
9946 std::string last;
9947 std::string name;
9948 };
9949 </pre>
9950
9951 <p>The complete syntax of the <code>db&nbsp;object</code> pragma is
9952 shown below:</p>
9953
9954 <p><code><b>object(</b><i>name</i>
9955 [<b>=</b> <i>alias</i>]
9956 [<i>join-type</i>]
9957 [<b>:</b> <i>join-condition</i>]<b>)</b></code></p>
9958
9959 <p>The <i>name</i> part is a potentially qualified persistent class
9960 name that has been defined previously. The optional <i>alias</i>
9961 part gives this object an alias. If provided, the alias is used
9962 in several contexts instead of the object's unqualified name. We
9963 will discuss aliases further as we cover each of these contexts
9964 below. The optional <i>join-type</i> part specifies the way this
9965 object is associated. It can be <code>left</code>, <code>right</code>,
9966 <code>full</code>, <code>inner</code>, and <code>cross</code>
9967 with <code>left</code> being the default.
9968 Finally, the optional <i>join-condition</i> part provides the
9969 criteria which should be used to associate this object with any
9970 of the previously associated objects or, as we will see in
9971 <a href="#10.4">Section 10.4, "Mixed Views"</a>, tables. Note that
9972 while the first associated object can have an alias, it cannot
9973 have a join type or condition.</p>
9974
9975 <p>For each subsequent associated object the ODB compiler needs
9976 a join condition and there are several ways to specify
9977 it. The easiest way is to omit it altogether and let the ODB
9978 compiler try to come up with a join condition automatically.
9979 To do this the ODB compiler will examine each previously
9980 associated object for object relationships
9981 (<a href="#6">Chapter 6, "Relationships"</a>) that
9982 may exist between these objects and the object being associated.
9983 If such a relationship exists and is unambiguous, that is
9984 there is only one such relationship, then the ODB compiler
9985 will automatically use it to come up with the join condition for
9986 this object. This is exactly what happens in the previous
9987 example: there is a single relationship
9988 (<code>employee::employed_by</code>) between the
9989 <code>employee</code> and <code>employer</code> objects.</p>
9990
9991 <p>On the other hand, consider this view:</p>
9992
9993 <pre class="cxx">
9994 #pragma db view object(employee) object(country)
9995 struct employee_residence
9996 {
9997 std::string first;
9998 std::string last;
9999 std::string name;
10000 };
10001 </pre>
10002
10003 <p>While there is a relationship between <code>country</code> and
10004 <code>employee</code>, it is ambiguous. It can be
10005 <code>employee::residence_</code> (which is what we want) or
10006 it can be <code>employee::nationality_</code> (which we don't
10007 want). As result, when compiling the above view, the ODB
10008 compiler will issue an error indicating an ambiguous object
10009 relationship. To resolve this ambiguity, we can explicitly
10010 specify the object relationship that should be used to create
10011 the join condition as the name of the corresponding data member.
10012 Here is how we can fix the <code>employee_residence</code>
10013 view:</p>
10014
10015 <pre class="cxx">
10016 #pragma db view object(employee) object(country: employee::residence_)
10017 struct employee_residence
10018 {
10019 std::string first;
10020 std::string last;
10021 std::string name;
10022 };
10023 </pre>
10024
10025 <p>It is possible to associate the same object with a single view
10026 more than once using different join conditions. However, in
10027 this case, we have to use aliases to assign different names
10028 for each association. For example:</p>
10029
10030 <pre class="cxx">
10031 #pragma db view object(employee) \
10032 object(country = res_country: employee::residence_) \
10033 object(country = nat_country: employee::nationality_)
10034 struct employee_country
10035 {
10036 ...
10037 };
10038 </pre>
10039
10040 <p>Note that correctly defining data members in this view requires
10041 the use of a mechanism that we haven't yet covered. We will
10042 see how to do this shortly.</p>
10043
10044 <p>If we assign an alias to an object and refer to a data member of
10045 this object in one of the join conditions, we have to use the
10046 unqualified alias name instead of the potentially qualified
10047 object name. For example:</p>
10048
10049 <pre class="cxx">
10050 #pragma db view object(employee = ee) object(country: ee::residence_)
10051 struct employee_residence
10052 {
10053 ...
10054 };
10055 </pre>
10056
10057 <p>The last way to specify a join condition is to provide a custom
10058 query expression. This method is primarily useful if you would
10059 like to associate an object using a condition that does not
10060 involve an object relationship. Consider, for example, a
10061 modified <code>employee</code> object from the beginning of
10062 the chapter with an added country of birth member. For one
10063 reason or another we have decided not to use a relationship to
10064 the <code>country</code> object, as we have done with
10065 residence and nationality.</p>
10066
10067 <pre class="cxx">
10068 #pragma db object
10069 class employee
10070 {
10071 ...
10072
10073 std::string birth_place_; // Country name.
10074 };
10075 </pre>
10076
10077 <p>If we now want to create a view that returns the birth country code
10078 for an employee, then we have to use a custom join condition when
10079 associating the <code>country</code> object. For example:</p>
10080
10081 <pre class="cxx">
10082 #pragma db view object(employee) \
10083 object(country: employee::birth_place_ == country::name_)
10084 struct employee_birth_code
10085 {
10086 std::string first;
10087 std::string last;
10088 std::string code;
10089 };
10090 </pre>
10091
10092 <p>The syntax of the query expression in custom join conditions
10093 is the same as in the query facility used to query the database
10094 for objects (<a href="#4">Chapter 4, "Querying the Database"</a>)
10095 except that for query members, instead of using
10096 <code>odb::query&lt;object>::member</code> names, we refer directly
10097 to object members.</p>
10098
10099 <p>Looking at the views we have defined so far, you may be wondering
10100 how the ODB compiler knows which view data members correspond to which
10101 object data members. While the names are similar, they are not exactly
10102 the same, for example <code>employee_name::first</code> and
10103 <code>employee::first_</code>.</p>
10104
10105 <p>As with join conditions, when it comes to associating data members,
10106 the ODB compiler tries to do this automatically. It first searches
10107 all the associated objects for an exact name match. If no match is
10108 found, then the ODB compiler compares the so-called public names.
10109 A public name of a member is obtained by removing the common member
10110 name decorations, such as leading and trailing underscores, the
10111 <code>m_</code> prefix, etc. In both of these searches the ODB
10112 compiler also makes sure that the types of the two members are the
10113 same or compatible.</p>
10114
10115 <p>If one of the above searches returned a match and it is unambiguous, that
10116 is there is only one match, then the ODB compiler will automatically
10117 associate the two members. On the other hand, if no match is found
10118 or the match is ambiguous, the ODB compiler will issue an error.
10119 To associate two differently-named members or to resolve an ambiguity,
10120 we can explicitly specify the member association using the
10121 <code>db&nbsp;column</code> pragma (<a href="#14.4.9">Section 14.4.9,
10122 "<code>column</code>"</a>). For example:</p>
10123
10124 <pre class="cxx">
10125 #pragma db view object(employee) object(employer)
10126 struct employee_employer
10127 {
10128 std::string first;
10129 std::string last;
10130
10131 #pragma db column(employer::name_)
10132 std::string employer_name;
10133 };
10134 </pre>
10135
10136 <p>If an object data member specifies the SQL type with
10137 the <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section
10138 14.4.3, "<code>type</code>"</a>), then this type is also used for
10139 the associated view data members.</p>
10140
10141 <p>Note also that similar to join conditions, if we assign an alias to
10142 an object and refer to a data member of this object in one of the
10143 <code>db&nbsp;column</code> pragmas, then we have to use the
10144 unqualified alias name instead of the potentially qualified
10145 object name. For example:</p>
10146
10147 <pre class="cxx">
10148 #pragma db view object(employee) \
10149 object(country = res_country: employee::residence_) \
10150 object(country = nat_country: employee::nationality_)
10151 struct employee_country
10152 {
10153 std::string first;
10154 std::string last;
10155
10156 #pragma db column(res_country::name_)
10157 std::string res_country_name;
10158
10159 #pragma db column(nat_country::name_)
10160 std::string nat_country_name;
10161 };
10162 </pre>
10163
10164 <p>Besides specifying just the object member, we can also specify a
10165 <em>+-expression</em> in the <code>db&nbsp;column</code> pragma. A
10166 +-expression consists of string literals and object
10167 member references connected using the <code>+</code> operator.
10168 It is primarily useful for defining aggregate views based on
10169 SQL aggregate functions, for example:</p>
10170
10171 <pre class="cxx">
10172 #pragma db view object(employee)
10173 struct employee_count
10174 {
10175 #pragma db column("count(" + employee::id_ + ")")
10176 std::size_t count;
10177 };
10178 </pre>
10179
10180 <p>When querying the database for a view, we may want to provide
10181 additional query criteria based on the objects associated with
10182 this view. To support this a view defines query members for all
10183 the associated objects which allows us to refer to such objects'
10184 members using the <code>odb::query&lt;view>::member</code> expressions.
10185 This is similar to how we can refer to object members using the
10186 <code>odb::query&lt;object>::member</code> expressions when
10187 querying the database for an object. For example:</p>
10188
10189 <pre class="cxx">
10190 typedef odb::query&lt;employee_count> query;
10191
10192 transaction t (db.begin ());
10193
10194 // Find the number of employees with the Doe last name. Result of this
10195 // aggregate query contains only one element so use the query_value()
10196 // shortcut function.
10197 //
10198 employee_count ec (
10199 db.query_value&lt;employee_count> (query::last == "Doe"));
10200
10201 cout &lt;&lt; ec.count &lt;&lt; endl;
10202
10203 t.commit ();
10204 </pre>
10205
10206 <p>In the above query we used the last name data member from the associated
10207 <code>employee</code> object to only count employees with the specific
10208 name.</p>
10209
10210 <p>When a view has only one associated object, the query members
10211 corresponding to this object are defined directly in the
10212 <code>odb::query&lt;view></code> scope. For instance,
10213 in the above example, we referred to the last name member as
10214 <code>odb::query&lt;employee_count>::last</code>. However, if
10215 a view has multiple associated objects, then query members
10216 corresponding to each such object are defined in a nested
10217 scope named after the object. As an example, consider
10218 the <code>employee_employer</code> view again:</p>
10219
10220 <pre class="cxx">
10221 #pragma db view object(employee) object(employer)
10222 struct employee_employer
10223 {
10224 std::string first;
10225 std::string last;
10226
10227 #pragma db column(employer::name_)
10228 std::string employer_name;
10229 };
10230 </pre>
10231
10232 <p>Now, to refer to the last name data member from the <code>employee</code>
10233 object we use the
10234 <code>odb::query&lt;...>::employee::last</code> expression.
10235 Similarly, to refer to the employer name, we use the
10236 <code>odb::query&lt;...>::employer::name</code> expression.
10237 For example:</p>
10238
10239 <pre class="cxx">
10240 typedef odb::result&lt;employee_employer> result;
10241 typedef odb::query&lt;employee_employer> query;
10242
10243 transaction t (db.begin ());
10244
10245 result r (db.query&lt;employee_employer> (
10246 query::employee::last == "Doe" &amp;&amp;
10247 query::employer::name == "Simple Tech Ltd"));
10248
10249 for (result::iterator i (r.begin ()); i != r.end (); ++i)
10250 cout &lt;&lt; i->first &lt;&lt; " " &lt;&lt; i->last &lt;&lt; " " &lt;&lt; i->employer_name &lt;&lt; endl;
10251
10252 t.commit ();
10253 </pre>
10254
10255 <p>If we assign an alias to an object, then this alias is used to
10256 name the query members scope instead of the object name. As an
10257 example, consider the <code>employee_country</code> view again:</p>
10258
10259 <pre class="cxx">
10260 #pragma db view object(employee) \
10261 object(country = res_country: employee::residence_) \
10262 object(country = nat_country: employee::nationality_)
10263 struct employee_country
10264 {
10265 ...
10266 };
10267 </pre>
10268
10269 <p>And a query which returns all the employees that have the same
10270 country of residence and nationality:</p>
10271
10272 <pre class="cxx">
10273 typedef odb::query&lt;employee_country> query;
10274 typedef odb::result&lt;employee_country> result;
10275
10276 transaction t (db.begin ());
10277
10278 result r (db.query&lt;employee_country> (
10279 query::res_country::name == query::nat_country::name));
10280
10281 for (result::iterator i (r.begin ()); i != r.end (); ++i)
10282 cout &lt;&lt; i->first &lt;&lt; " " &lt;&lt; i->last &lt;&lt; " " &lt;&lt; i->res_country_name &lt;&lt; endl;
10283
10284 t.commit ();
10285 </pre>
10286
10287 <p>Note also that unlike object query members, view query members do
10288 no support referencing members in related objects. For example,
10289 the following query is invalid:</p>
10290
10291 <pre class="cxx">
10292 typedef odb::query&lt;employee_name> query;
10293 typedef odb::result&lt;employee_name> result;
10294
10295 transaction t (db.begin ());
10296
10297 result r (db.query&lt;employee_name> (
10298 query::employed_by->name == "Simple Tech Ltd"));
10299
10300 t.commit ();
10301 </pre>
10302
10303 <p>To get this behavior, we would instead need to associate the
10304 <code>employer</code> object with this view and then use the
10305 <code>query::employer::name</code> expression instead of
10306 <code>query::employed_by->name</code>.</p>
10307
10308 <p>As we have discussed above, if specified, an object alias is
10309 used instead of the object name in the join condition, data
10310 member references in the <code>db&nbsp;column</code> pragma,
10311 as well as to name the query members scope. The object alias
10312 is also used as a table name alias in the underlying
10313 <code>SELECT</code> statement generated by the ODB compiler.
10314 Normally, you would not use the table alias directly with
10315 object views. However, if for some reason you need to refer
10316 to a table column directly, for example, as part of a native
10317 query expression, and you need to qualify the column with
10318 the table, then you will need to use the table alias instead.</p>
10319
10320 <h2><a name="10.2">10.2 Object Loading Views</a></h2>
10321
10322 <p>A special variant of object views is object loading views. Object
10323 loading views allow us to load one or more complete objects
10324 instead of, or in addition to, a subset of data member. While we
10325 can often achieve the same end result by calling
10326 <code>database::load()</code>, using a view has several advantages.</p>
10327
10328 <p>If we need to load multiple objects, then using a view allows us
10329 to do this with a single <code>SELECT</code> statement execution
10330 instead of one for each object that would be necessary in case of
10331 <code>load()</code>. A view can also be useful for loading only
10332 a single object if the query criterion that we would like to use
10333 involves other, potentially unrelated, objects. We will examine
10334 concrete examples of these and other scenarios in the rest of this
10335 section.</p>
10336
10337 <p>To load a complete object as part of a view we use a data member of
10338 the pointer to object type, just like for object relationships
10339 (<a href="#6">Chapter 6, "Relationships"</a>). As an example, here
10340 is how we can load both the <code>employee</code> and
10341 <code>employer</code> objects from the previous section with a single
10342 statement:</p>
10343
10344 <pre class="cxx">
10345 #pragma db view object(employee) object(employer)
10346 struct employee_employer
10347 {
10348 shared_ptr&lt;employee> ee;
10349 shared_ptr&lt;employer> er;
10350 };
10351 </pre>
10352
10353 <p>We use an object loading view just like any other view. In the
10354 result of a query, as we would expect, the pointer data members
10355 point to the loaded objects. For example:</p>
10356
10357 <pre class="cxx">
10358 typedef odb::query&lt;employee_employer> query;
10359
10360 transaction t (db.begin ());
10361
10362 for (const employee_employer&amp; r:
10363 db.query&lt;employee_employer> (query::employee::age &lt; 31))
10364 {
10365 cout &lt;&lt; r.ee->age () &lt;&lt; " " &lt;&lt; r.er->name () &lt;&lt; endl;
10366 }
10367
10368 t.commit ();
10369 </pre>
10370
10371 <p>As another example, consider a query that loads the <code>employer</code>
10372 objects using some condition based on its employees. For instance, we
10373 want to find all the employers that employ people over 65 years old.
10374 We can use this object loading view to implement such a query (notice
10375 the <code>distinct</code> result modifier discussed later in
10376 <a href="#10.5">Section 10.5, "View Query Conditions"</a>):</p>
10377
10378 <pre class="cxx">
10379 #pragma db view object(employer) object(employee) query(distinct)
10380 struct employer_view
10381 {
10382 shared_ptr&lt;employer> er;
10383 };
10384 </pre>
10385
10386 <p>And this is how we can use this view to find all the employers that
10387 employ seniors:</p>
10388
10389 <pre class="cxx">
10390 typedef odb::query&lt;employee_employer> query;
10391
10392 db.query&lt;employer_view> (query::employee::age > 65)
10393 </pre>
10394
10395 <p>We can even use object loading views to load completely unrelated
10396 (from the ODB object relationships point of view) objects. For example,
10397 the following view will load all the employers that are named the
10398 same as a country (notice the <code>inner</code> join type):</p>
10399
10400 <pre class="cxx">
10401 #pragma db view object(employer) \
10402 object(country inner: employer::name == country::name)
10403 struct employer_named_country
10404 {
10405 shared_ptr&lt;employer> e;
10406 shared_ptr&lt;country> c;
10407 };
10408 </pre>
10409
10410 <p>An object loading view can contain ordinary data members
10411 in addition to object pointers. For example, if we are only
10412 interested in the country code in the above view, then we
10413 can reimplement it like this:</p>
10414
10415 <pre class="cxx">
10416 #pragma db view object(employer) \
10417 object(country inner: employer::name == country::name)
10418 struct employer_named_country
10419 {
10420 shared_ptr&lt;employer> e;
10421 std::string code;
10422 };
10423 </pre>
10424
10425 <p>Object loading views also have a few rules and restrictions.
10426 Firstly, the pointed-to object in the data member must be associated
10427 with the view. Furthermore, if the associated object has an alias,
10428 then the data member name must be the same as the alias (more
10429 precisely, the public name derived from the data member must
10430 match the alias; which means we can use normal data member
10431 decorations such as trailing underscores, etc., see the previous
10432 section for more information on public names). The following view
10433 illustrates the use of aliases as data member names:</p>
10434
10435 <pre class="cxx">
10436 #pragma db view object(employee) \
10437 object(country = res: employee::residence_) \
10438 object(country = nat: employee::nationality_)
10439 struct employee_country
10440 {
10441 shared_ptr&lt;country> res;
10442 shared_ptr&lt;country> nat_;
10443 };
10444 </pre>
10445
10446 <p>Finally, the object pointers must be direct data members of
10447 the view. Using, for example, a composite value that contains
10448 pointers as a view data member is not supported. Note also
10449 that depending on the join type you are using, some of the
10450 resulting pointers might be <code>NULL</code>.</p>
10451
10452 <p>Up until now we have consistently used <code>shared_ptr</code>
10453 as an object pointer in our views. Can we use other pointers,
10454 such as <code>unique_ptr</code> or raw pointers? To answer
10455 this question we first need to discuss what happens with
10456 object pointers that may be inside objects that a view
10457 loads. As a concrete example, let us revisit the
10458 <code>employee_employer</code> view from the beginning of
10459 this section:</p>
10460
10461 <pre class="cxx">
10462 #pragma db view object(employee) object(employer)
10463 struct employee_employer
10464 {
10465 shared_ptr&lt;employee> ee;
10466 shared_ptr&lt;employer> er;
10467 };
10468 </pre>
10469
10470 <p>This view loads two objects: <code>employee</code> and
10471 <code>employer</code>. The <code>employee</code> object,
10472 however, also contains a pointer to <code>employer</code>
10473 (see the <code>employed_by_</code> data member). In fact,
10474 this is the same object that the view loads since <code>employer</code>
10475 is associated with the view using this same relationship (ODB
10476 automatically uses it since it is the only one). The correct
10477 result of loading such a view is then clear: both <code>er</code> and
10478 <code>er->employed_by_</code> must point to (or share) the
10479 same instance.</p>
10480
10481 <p>Just like object loading via the <code>database</code> class
10482 functions, views achieve this correct behavior of only loading
10483 a single instance of the same object with the help of session's
10484 object cache (<a href="#11">Chapter 11, "Session"</a>). In fact,
10485 object loading views enforce this by throwing the
10486 <code>session_required</code> exception if there is no current
10487 session and the view loads an object that is also indirectly
10488 loaded by one of the other objects. The ODB compiler will also
10489 issue diagnostics if such an object has session support
10490 disabled (<a href="#14.1.10">Section 14.1.10,
10491 "<code>session</code>"</a>).</p>
10492
10493 <p>With this understanding we can now provide the correct implementation
10494 of our transaction that uses the <code>employee_employer</code> view:</p>
10495
10496 <pre class="cxx">
10497 typedef odb::query&lt;employee_employer> query;
10498
10499 transaction t (db.begin ());
10500 odb::session s;
10501
10502 for (const employee_employer&amp; r:
10503 db.query&lt;employee_employer> (query::employee::age &lt; 31))
10504 {
10505 assert (r.ee->employed_by_ == r.er);
10506 cout &lt;&lt; r.ee->age () &lt;&lt; " " &lt;&lt; r.er->name () &lt;&lt; endl;
10507 }
10508
10509 t.commit ();
10510 </pre>
10511
10512 <p>It might seem logical, then, to always load all the objects from
10513 all the eager relationships with the view. After all, this will
10514 lead to them all being loaded with a single statement. While
10515 this is theoretically true, the reality is slightly more nuanced.
10516 If there is a high probability of the object already have been
10517 loaded and sitting in the cache, then not loading the object
10518 as part of the view (and therefore not fetching all its data
10519 from the database) might result in better performance.</p>
10520
10521 <p>Now we can also answer the question about which pointers we can
10522 use in object loading views. From the above discussion it should
10523 be clear that if an object that we are loading is also part of a
10524 relationship inside another object that we are loading, then we
10525 should use some form of a shared ownership pointer. If, however,
10526 there are no relationships involved, as is the case, for example,
10527 in our <code>employer_named_country</code> and
10528 <code>employee_country</code> views above, then we can use a
10529 unique ownership pointer such as <code>unique_ptr</code>.</p>
10530
10531 <p>Note also that your choice of a pointer type can be limited by the
10532 "official" object pointer type assigned to the object
10533 (<a href="#3.3">Section 3.3, "Object and View Pointers"</a>).
10534 For example, if the object pointer type is <code>shared_ptr</code>,
10535 you will not be able to use <code>unique_ptr</code> to load
10536 such an object into a view since initializing <code>unique_ptr</code>
10537 from <code>shared_ptr</code> would be a mistake.</p>
10538
10539 <p>Unless you want to perform your own object cleanup, raw object
10540 pointers in views are not particularly useful. They do have one
10541 special semantics, however: If a raw pointer is used as a view
10542 member, then, before creating a new instance, the implementation
10543 will check if the member is <code>NULL</code>. If it is not, then
10544 it is assumed to point to an existing instance and the implementation
10545 will load the data into it instead of creating a new one. The
10546 primary use of this special functionality is to implement by-value
10547 loading with the ability to detect <code>NULL</code> values.</p>
10548
10549 <p>To illustrate this functionality, consider the following view that
10550 load the employee's residence country by value:</p>
10551
10552 <pre class="cxx">
10553 #pragma db view object(employee) \
10554 object(country = res: employee::residence_) transient
10555 struct employee_res_country
10556 {
10557 typedef country* country_ptr;
10558
10559 #pragma db member(res_) virtual(country_ptr) get(&amp;this.res) \
10560 set(this.res_null = ((?) == nullptr))
10561
10562 country res;
10563 bool res_null;
10564 };
10565 </pre>
10566
10567 <p>Here we are using a virtual data member
10568 (<a href="#14.4.13">Section 14.4.13, "<code>virtual</code>"</a>) to
10569 add an object pointer member to the view. Its accessor expression
10570 returns the pointer to the <code>res</code> member so that
10571 the implementation can load the data into it. The modifier
10572 expression checks the passed pointer to initialize the
10573 <code>NULL</code> value indicator. Here, the two possible
10574 values that can be passed to the modifier expression are
10575 the address of the <code>res</code> member that we returned
10576 earlier from the accessor and <code>NULL</code> (strictly
10577 speaking, there is a third possibility: the address of an
10578 object that was found in the session cache).</p>
10579
10580 <p>If we are not interested in the <code>NULL</code> indicator,
10581 then the above view can simplified to this:</p>
10582
10583 <pre class="cxx">
10584 #pragma db view object(employee) \
10585 object(country = res: employee::residence_) transient
10586 struct employee_res_country
10587 {
10588 typedef country* country_ptr;
10589
10590 #pragma db member(res_) virtual(country_ptr) get(&amp;this.res) set()
10591
10592 country res;
10593 };
10594 </pre>
10595
10596 <p>That is, we specify an empty modifier expression which leads to
10597 the value being ignored.</p>
10598
10599 <p>As another example of by-value loading, consider a view that allows
10600 us to load objects into existing instances that have been allocated
10601 outside the view:</p>
10602
10603 <pre class="cxx">
10604 #pragma db view object(employee) \
10605 object(country = res: employee::residence_) \
10606 object(country = nat: employee::nationality_)
10607 struct employee_country
10608 {
10609 employee_country (country&amp; r, country&amp; n): res (&amp;r), nat (&amp;n) {}
10610
10611 country* res;
10612 country* nat;
10613 };
10614 </pre>
10615
10616 <p>And here is how we can use this view:</p>
10617
10618 <pre class="cxx">
10619 typedef odb::result&lt;employee_country> result;
10620
10621 transaction t (db.begin ());
10622
10623 result r (db.query&lt;employee_country> (...);
10624
10625 for (result::iterator i (r.begin ()); i != r.end (); ++i)
10626 {
10627 country res, nat;
10628 employee_country v (res, nat);
10629 i.load (v);
10630
10631 if (v.res != nullptr)
10632 ... // Result is in res.
10633
10634 if (v.nat != nullptr)
10635 ... // Result is in nat.
10636 }
10637
10638 t.commit ();
10639 </pre>
10640
10641 <p>As a final example of the by-value loading, consider the following
10642 view which implements a slightly more advanced logic: if the object
10643 is already in the session cache, then it sets the pointer data member
10644 in the view (<code>er_p</code>) to that. Otherwise, it loads the data
10645 into the by-value instance (<code>er</code>). We can also check
10646 whether the pointer data member points to the instance to distinguish
10647 between the two outcomes. And we can check it for <code>nullptr</code>
10648 to detect <code>NULL</code> values.</p>
10649
10650 <pre class="cxx">
10651 #pragma db view object(employer)
10652 struct employer_view
10653 {
10654 // Since we may be getting the pointer as both smart and raw, we
10655 // need to create a bit of support code to use in the modifier
10656 // expression.
10657 //
10658 void set_er (employer* p) {er_p = p;} // &amp;er or NULL.
10659 void set_er (shared_ptr&lt;employer> p) {er_p = p.get ();} // From cache.
10660
10661 #pragma db get(&amp;this.er) set(set_er(?))
10662 employer* er_p;
10663
10664 #pragma db transient
10665 employer er;
10666
10667 // Return-by-value support (e.g., query_value()).
10668 //
10669 employer_view (): er_p (0) {}
10670 employer_view (const employer_view&amp; x)
10671 : er_p (x.er_p == &amp;x.er ? &amp;er : x.er_p), er (x.er) {}
10672 };
10673 </pre>
10674
10675 <p>We can use object loading views with polymorphic objects
10676 (<a href="#8.2">Section 8.2, "Polymorphism Inheritance"</a>). Note,
10677 however, that when loading a derived object via the base pointer
10678 in a view, a separate statement will be executed to load the
10679 dynamic part of the object. There is no support for by-value
10680 loading for polymorphic objects.</p>
10681
10682 <p>We can also use object loading views with objects without id
10683 (<a href="#14.1.6">Section 14.1.6, "<code>no_id</code>"</a>).
10684 Note, however, that for such objects, <code>NULL</code> values
10685 are not automatically detected (since there is no primary key,
10686 which is otherwise guaranteed to be not <code>NULL</code>, there
10687 might not be a column on which to base this detection). The
10688 workaround for this limitation is to load an otherwise not
10689 <code>NULL</code> column next to the object which will serve
10690 as an indicator. For example:</p>
10691
10692 <pre class="cxx">
10693 #pragma db object no_id
10694 class object
10695 {
10696 ...
10697
10698 int n; // NOT NULL
10699 std::string s;
10700 };
10701
10702 #include &lt;odb/nullable.hxx>
10703
10704 #pragma db view object(object)
10705 struct view
10706 {
10707
10708 odb::nullable&lt;int> n; // If 'n' is NULL, then, logically, so is 'o'.
10709 unique_ptr&lt;object> o;
10710 };
10711 </pre>
10712
10713 <h2><a name="10.3">10.3 Table Views</a></h2>
10714
10715 <p>A table view is similar to an object view except that it is
10716 based on one or more database tables instead of persistent
10717 objects. Table views are primarily useful when dealing with
10718 ad-hoc tables that are not mapped to persistent classes.</p>
10719
10720 <p>To associate one or more tables with a view we use the
10721 <code>db&nbsp;table</code> pragma (<a href="#14.2.2">Section 14.2.2,
10722 "<code>table</code>"</a>). To associate the second and subsequent
10723 tables we repeat the <code>db&nbsp;table</code> pragma for each
10724 additional table. For example, the following view is based on the
10725 <code>employee_extra</code> legacy table we have defined at the
10726 beginning of the chapter.</p>
10727
10728 <pre class="cxx">
10729 #pragma db view table("employee_extra")
10730 struct employee_vacation
10731 {
10732 #pragma db column("employee_id") type("INTEGER")
10733 unsigned long employee_id;
10734
10735 #pragma db column("vacation_days") type("INTEGER")
10736 unsigned short vacation_days;
10737 };
10738 </pre>
10739
10740 <p>Besides the table name in the <code>db&nbsp;table</code> pragma
10741 we also have to specify the column name for each view data
10742 member. Note that unlike for object views, the ODB compiler
10743 does not try to automatically come up with column names for
10744 table views. Furthermore, we cannot use references to object
10745 members either, since there are no associated objects in table
10746 views. Instead, the actual column name or column expression
10747 must be specified as a string literal. The column name can
10748 also be qualified with a table name either in the
10749 <code>"table.column"</code> form or, if either a table
10750 or a column name contains a period, in the
10751 <code>"table"."column"</code> form. The following example
10752 illustrates the use of a column expression:</p>
10753
10754 <pre class="cxx">
10755 #pragma db view table("employee_extra")
10756 struct employee_max_vacation
10757 {
10758 #pragma db column("max(vacation_days)") type("INTEGER")
10759 unsigned short max_vacation_days;
10760 };
10761 </pre>
10762
10763 <p>Both the asociated table names and the column names can be qualified
10764 with a database schema, for example:</p>
10765
10766 <pre class="cxx">
10767 #pragma db view table("hr.employee_extra")
10768 struct employee_max_vacation
10769 {
10770 #pragma db column("hr.employee_extra.vacation_days") type("INTEGER")
10771 unsigned short vacation_days;
10772 };
10773 </pre>
10774
10775 <p>For more information on database schemas and the format of the
10776 qualified names, refer to <a href="#14.1.8">Section 14.1.8,
10777 "<code>schema</code>"</a>.</p>
10778
10779 <p>Note also that in the above examples we specified the SQL type
10780 for each of the columns to make sure that the ODB compiler
10781 has knowledge of the actual types as specified in the database
10782 schema. This is required to obtain correct and optimal
10783 generated code.</p>
10784
10785
10786 <p>The complete syntax of the <code>db&nbsp;table</code> pragma
10787 is similar to the <code>db&nbsp;object</code> pragma and is shown
10788 below:</p>
10789
10790 <p><code><b>table("</b><i>name</i><b>"</b>
10791 [<b>=</b> <b>"</b><i>alias</i><b>"</b>]
10792 [<i>join-type</i>]
10793 [<b>:</b> <i>join-condition</i>]<b>)</b></code></p>
10794
10795 <p>The <i>name</i> part is a database table name. The optional
10796 <i>alias</i> part gives this table an alias. If provided, the
10797 alias must be used instead of the table whenever a reference
10798 to a table is used. Contexts where such a reference may
10799 be needed include the join condition (discussed below),
10800 column names, and query expressions. The optional <i>join-type</i>
10801 part specifies the way this table is associated. It can
10802 be <code>left</code>, <code>right</code>, <code>full</code>,
10803 <code>inner</code>, and <code>cross</code> with <code>left</code>
10804 being the default. Finally, the optional <i>join-condition</i>
10805 part provides the criteria which should be used to associate this
10806 table with any of the previously associated tables or, as we will see in
10807 <a href="#10.4">Section 10.4, "Mixed Views"</a>, objects. Note that
10808 while the first associated table can have an alias, it cannot have
10809 a join type or condition.</p>
10810
10811 <p>Similar to object views, for each subsequent associated table the
10812 ODB compiler needs a join condition. However, unlike for object views,
10813 for table views the ODB compiler does not try to come up with one
10814 automatically. Furthermore, we cannot use references to object
10815 members corresponding to object relationships either, since there
10816 are no associated objects in table views. Instead, for each
10817 subsequent associated table, a join condition must be
10818 specified as a custom query expression. While the syntax of the
10819 query expression is the same as in the query facility used to query
10820 the database for objects (<a href="#4">Chapter 4, "Querying the
10821 Database"</a>), a join condition for a table is normally specified
10822 as a single string literal containing a native SQL query expression.</p>
10823
10824 <p>As an example of a multi-table view, consider the
10825 <code>employee_health</code> table that we define in addition
10826 to <code>employee_extra</code>:</p>
10827
10828 <pre class="sql">
10829 CREATE TABLE employee_health(
10830 employee_id INTEGER NOT NULL,
10831 sick_leave_days INTEGER NOT NULL)
10832 </pre>
10833
10834 <p>Given these two tables we can now define a view that returns both
10835 the vacation and sick leave information for each employee:</p>
10836
10837 <pre class="cxx">
10838 #pragma db view table("employee_extra" = "extra") \
10839 table("employee_health" = "health": \
10840 "extra.employee_id = health.employee_id")
10841 struct employee_leave
10842 {
10843 #pragma db column("extra.employee_id") type("INTEGER")
10844 unsigned long employee_id;
10845
10846 #pragma db column("vacation_days") type("INTEGER")
10847 unsigned short vacation_days;
10848
10849 #pragma db column("sick_leave_days") type("INTEGER")
10850 unsigned short sick_leave_days;
10851 };
10852 </pre>
10853
10854 <p>Querying the database for a table view is the same as for an
10855 object view except that we can only use native query expressions.
10856 For example:</p>
10857
10858 <pre class="cxx">
10859 typedef odb::query&lt;employee_leave> query;
10860 typedef odb::result&lt;employee_leave> result;
10861
10862 transaction t (db.begin ());
10863
10864 unsigned short v_min = ...
10865 unsigned short l_min = ...
10866
10867 result r (db.query&lt;employee_leave> (
10868 "vacation_days > " + query::_val(v_min) + "AND"
10869 "sick_leave_days > " + query::_val(l_min)));
10870
10871 t.commit ();
10872 </pre>
10873
10874
10875 <h2><a name="10.4">10.4 Mixed Views</a></h2>
10876
10877 <p>A mixed view has both associated objects and tables. As a first
10878 example of a mixed view, let us improve <code>employee_vacation</code>
10879 from the previous section to return the employee's first
10880 and last names instead of the employee id. To achieve this we
10881 have to associate both the <code>employee</code> object and
10882 the <code>employee_extra</code> table with the view:</p>
10883
10884 <pre class="cxx">
10885 #pragma db view object(employee) \
10886 table("employee_extra" = "extra": "extra.employee_id = " + employee::id_)
10887 struct employee_vacation
10888 {
10889 std::string first;
10890 std::string last;
10891
10892 #pragma db column("extra.vacation_days") type("INTEGER")
10893 unsigned short vacation_days;
10894 };
10895 </pre>
10896
10897 <p>When querying the database for a mixed view, we can use query members
10898 for the parts of the query expression that involves object members
10899 but have to fall back to using the native syntax for the parts that
10900 involve table columns. For example:</p>
10901
10902 <pre class="cxx">
10903 typedef odb::query&lt;employee_vacation> query;
10904 typedef odb::result&lt;employee_vacation> result;
10905
10906 transaction t (db.begin ());
10907
10908 result r (db.query&lt;employee_vacation> (
10909 (query::last == "Doe") + "AND extra.vacation_days &lt;> 0"));
10910
10911 for (result::iterator i (r.begin ()); i != r.end (); ++i)
10912 cout &lt;&lt; i->first &lt;&lt; " " &lt;&lt; i->last &lt;&lt; " " &lt;&lt; i->vacation_days &lt;&lt; endl;
10913
10914 t.commit ();
10915 </pre>
10916
10917 <p>As another example, consider a more advanced view that associates
10918 two objects via a legacy table. This view allows us to find the
10919 previous employer name for each employee:</p>
10920
10921 <pre class="cxx">
10922 #pragma db view object(employee) \
10923 table("employee_extra" = "extra": "extra.employee_id = " + employee::id_) \
10924 object(employer: "extra.previous_employer_id = " + employer::id_)
10925 struct employee_prev_employer
10926 {
10927 std::string first;
10928 std::string last;
10929
10930 // If previous_employer_id is NULL, then the name will be NULL as well.
10931 // We use the odb::nullable wrapper to handle this.
10932 //
10933 #pragma db column(employer::name_)
10934 odb::nullable&lt;std::string> prev_employer_name;
10935 };
10936 </pre>
10937
10938 <h2><a name="10.5">10.5 View Query Conditions</a></h2>
10939
10940 <p>Object, table, and mixed views can also specify an optional query
10941 condition that should be used whenever the database is queried for
10942 this view. To specify a query condition we use the
10943 <code>db&nbsp;query</code> pragma (<a href="#14.2.3">Section 14.2.3,
10944 "<code>query</code>"</a>).</p>
10945
10946 <p>As an example, consider a view that returns some information about
10947 all the employees that are over a predefined retirement age.
10948 One way to implement this would be to define a standard object
10949 view as we have done in the previous sections and then use a
10950 query like this:</p>
10951
10952 <pre class="cxx">
10953 result r (db.query&lt;employee_retirement> (query::age > 50));
10954 </pre>
10955
10956 <p>The problem with the above approach is that we have to keep
10957 repeating the <code>query::age > 50</code> expression every
10958 time we execute the query, even though this expression always
10959 stays the same. View query conditions allow us to solve this
10960 problem. For example:</p>
10961
10962 <pre class="cxx">
10963 #pragma db view object(employee) query(employee::age > 50)
10964 struct employee_retirement
10965 {
10966 std::string first;
10967 std::string last;
10968 unsigned short age;
10969 };
10970 </pre>
10971
10972 <p>With this improvement we can rewrite our query like this:</p>
10973
10974 <pre class="cxx">
10975 result r (db.query&lt;employee_retirement> ());
10976 </pre>
10977
10978 <p>But what if we may also need to restrict the result set based on
10979 some varying criteria, such as the employee's last name? Or, in other
10980 words, we may need to combine a constant query expression specified
10981 in the <code>db&nbsp;query</code> pragma with the varying expression
10982 specified at the query execution time. To allow this, the
10983 <code>db&nbsp;query</code> pragma syntax supports the use of the special
10984 <code>(?)</code> placeholder that indicates the position in the
10985 constant query expression where the runtime expression should be
10986 inserted. For example:</p>
10987
10988 <pre class="cxx">
10989 #pragma db view object(employee) query(employee::age > 50 &amp;&amp; (?))
10990 struct employee_retirement
10991 {
10992 std::string first;
10993 std::string last;
10994 unsigned short name;
10995 };
10996 </pre>
10997
10998 <p>With this change we can now use additional query criteria in our
10999 view:</p>
11000
11001 <pre class="cxx">
11002 result r (db.query&lt;employee_retirement> (query::last == "Doe"));
11003 </pre>
11004
11005 <p>The syntax of the expression in a query condition is the same as in
11006 the query facility used to query the database for objects
11007 (<a href="#4">Chapter 4, "Querying the Database"</a>) except for
11008 two differences. Firstly, for query members, instead of
11009 using <code>odb::query&lt;object>::member</code> names, we refer
11010 directly to object members, using the object alias instead of the
11011 object name if an alias was assigned. Secondly, query conditions
11012 support the special <code>(?)</code> placeholder which can be used
11013 both in the C++-integrated query expressions as was shown above
11014 and in native SQL expressions specified as string literals. The
11015 following view is an example of the latter case:</p>
11016
11017 <pre class="cxx">
11018 #pragma db view table("employee_extra") \
11019 query("vacation_days &lt;> 0 AND (?)")
11020 struct employee_vacation
11021 {
11022 ...
11023 };
11024 </pre>
11025
11026 <p>Another common use case for query conditions are views with the
11027 <code>ORDER BY</code> or <code>GROUP BY</code> clause. Such
11028 clauses are normally present in the same form in every query
11029 involving such views. As an example, consider an aggregate
11030 view which calculate the minimum and maximum ages of employees
11031 for each employer:</p>
11032
11033 <pre class="cxx">
11034 #pragma db view object(employee) object(employer) \
11035 query((?) + "GROUP BY" + employer::name_)
11036 struct employer_age
11037 {
11038 #pragma db column(employer::name_)
11039 std::string employer_name;
11040
11041 #pragma db column("min(" + employee::age_ + ")")
11042 unsigned short min_age;
11043
11044 #pragma db column("max(" + employee::age_ + ")")
11045 unsigned short max_age;
11046 };
11047 </pre>
11048
11049 <p>The query condition can be optionally followed (or replaced,
11050 if no constant query expression is needed) by one or more
11051 <em>result modifiers</em>. Currently supported result modifiers
11052 are <code>distinct</code> (which is translated to <code>SELECT
11053 DISTINCT</code>) and <code>for_update</code> (which is translated
11054 to <code>FOR UPDATE</code> or equivalent for database systems
11055 that support it). As an example, consider a view that
11056 allows us to get some information about employers ordered
11057 by the object id and without any duplicates:</p>
11058
11059 <pre class="cxx">
11060 #pragma db view object(employer) object(employee) \
11061 query((?) + "ORDER BY" + employer::name_, distinct)
11062 struct employer_info
11063 {
11064 ...
11065 };
11066 </pre>
11067
11068 <p>If we don't require ordering, then this view can be re-implemented
11069 like this:</p>
11070
11071 <pre class="cxx">
11072 #pragma db view object(employer) object(employee) query(distinct)
11073 struct employer_info
11074 {
11075 ...
11076 };
11077 </pre>
11078
11079 <h2><a name="10.6">10.6 Native Views</a></h2>
11080
11081 <p>The last kind of view supported by ODB is a native view. Native
11082 views are a low-level mechanism for capturing results of native
11083 SQL queries, stored procedure calls, etc. Native views don't have
11084 associated tables or objects. Instead, we use the
11085 <code>db&nbsp;query</code> pragma to specify the native SQL query,
11086 which should normally include the select-list and, if applicable,
11087 the from-list. For example, here is how we can re-implement the
11088 <code>employee_vacation</code> table view from Section 10.3 above
11089 as a native view:</p>
11090
11091 <pre class="cxx">
11092 #pragma db view query("SELECT employee_id, vacation_days " \
11093 "FROM employee_extra")
11094 struct employee_vacation
11095 {
11096 #pragma db type("INTEGER")
11097 unsigned long employee_id;
11098
11099 #pragma db type("INTEGER")
11100 unsigned short vacation_days;
11101 };
11102 </pre>
11103
11104 <p>In native views the columns in the query select-list are
11105 associated with the view data members in the order specified.
11106 That is, the first column is stored in the first member, the
11107 second column &mdash; in the second member, and so on. The ODB compiler
11108 does not perform any error checking in this association. As a result
11109 you must make sure that the number and order of columns in the
11110 query select-list match the number and order of data members
11111 in the view. This is also the reason why we are not
11112 required to provide the column name for each data member in native
11113 views, as is the case for object and table views.</p>
11114
11115 <p>Note also that while it is always possible to implement a table
11116 view as a native view, the table views must be preferred since
11117 they are safer. In a native view, if you add, remove, or
11118 rearrange data members without updating the column list in the
11119 query, or vice versa, at best, this will result in a runtime
11120 error. In contrast, in a table view such changes will result
11121 in the query being automatically updated.</p>
11122
11123 <p>Similar to object and table views, the query specified for
11124 a native view can contain the special <code>(?)</code>
11125 placeholder which is replaced with the query expression
11126 specified at the query execution time.
11127 If the native query does not contain a placeholder, as in
11128 the example above, then any query expression specified at
11129 the query execution time is appended to the query text
11130 along with the <code>WHERE</code> keyword, if required.
11131 The following example shows the usage of the placeholder:</p>
11132
11133 <pre class="cxx">
11134 #pragma db view query("SELECT employee_id, vacation_days " \
11135 "FROM employee_extra " \
11136 "WHERE vacation_days &lt;> 0 AND (?)")
11137 struct employee_vacation
11138 {
11139 ...
11140 };
11141 </pre>
11142
11143 <p>As another example, consider a view that returns the next
11144 value of a database sequence:</p>
11145
11146 <pre class="cxx">
11147 #pragma db view query("SELECT nextval('my_seq')")
11148 struct sequence_value
11149 {
11150 unsigned long long value;
11151 };
11152 </pre>
11153
11154 <p>While this implementation can be acceptable in some cases, it has
11155 a number of drawbacks. Firstly, the name of the sequence is
11156 fixed in the view, which means if we have a second sequence, we
11157 will have to define another, almost identical view. Similarly,
11158 the operation that we perform on the sequence is also fixed.
11159 In some situations, instead of returning the next value, we may
11160 need the last value.</p>
11161
11162 <p>Note that we cannot use the placeholder mechanism to resolve
11163 these problems since placeholders can only be used in the
11164 <code>WHERE</code>, <code>GROUP BY</code>, and similar
11165 clauses. In other words, the following won't work:</p>
11166
11167 <pre class="cxx">
11168 #pragma db view query("SELECT nextval('(?)')")
11169 struct sequence_value
11170 {
11171 unsigned long long value;
11172 };
11173
11174 result r (db.query&lt;sequence_value> ("my_seq"));
11175 </pre>
11176
11177 <p>To support these kinds of use cases, ODB allows us to specify the
11178 complete query for a native view at runtime rather than at the view
11179 definition. To indicate that a native view has a runtime query,
11180 we can either specify the empty <code>db&nbsp;query</code>
11181 pragma or omit the pragma altogether. For example:</p>
11182
11183 <pre class="cxx">
11184 #pragma db view
11185 struct sequence_value
11186 {
11187 unsigned long long value;
11188 };
11189 </pre>
11190
11191 <p>Given this view, we can perform the following queries:</p>
11192
11193 <pre class="cxx">
11194 typedef odb::query&lt;sequence_value> query;
11195 typedef odb::result&lt;sequence_value> result;
11196
11197 string seq_name = ...
11198
11199 result l (db.query&lt;sequence_value> (
11200 "SELECT lastval('" + seq_name + "')"));
11201
11202 result n (db.query&lt;sequence_value> (
11203 "SELECT nextval('" + seq_name + "')"));
11204 </pre>
11205
11206 <p>Native views can also be used to call and handle results of
11207 stored procedures. The semantics and limitations of stored
11208 procedures vary greatly between database systems while some
11209 do not support this functionality at all. As a result, support
11210 for calling stored procedures using native views is described
11211 for each database system in <a href="#II">Part II, "Database
11212 Systems"</a>.</p>
11213
11214 <h2><a name="10.7">10.7 Other View Features and Limitations</a></h2>
11215
11216 <p>Views cannot be derived from other views. However, you can derive
11217 a view from a transient C++ class. View data members cannot be
11218 object pointers. If you need to access data from a pointed-to
11219 object, then you will need to associate such an object with
11220 the view. Similarly, view data members cannot be containers.
11221 These two limitations also apply to composite value types that
11222 contain object pointers or containers. Such composite values
11223 cannot be used as view data members.</p>
11224
11225 <p>On the other hand, composite values that do not contain object
11226 pointers or containers can be used in views. As an example,
11227 consider a modified version of the <code>employee</code> persistent
11228 class that stores a person's name as a composite value:</p>
11229
11230 <pre class="cxx">
11231 #pragma db value
11232 class person_name
11233 {
11234 std::string first_;
11235 std::string last_;
11236 };
11237
11238 #pragma db object
11239 class employee
11240 {
11241 ...
11242
11243 person_name name_;
11244
11245 ...
11246 };
11247 </pre>
11248
11249 <p>Given this change, we can re-implement the <code>employee_name</code>
11250 view like this:</p>
11251
11252 <pre class="cxx">
11253 #pragma db view object(employee)
11254 struct employee_name
11255 {
11256 person_name name;
11257 };
11258 </pre>
11259
11260 <p>It is also possible to extract some or all of the nested members
11261 of a composite value into individual view data members. Here is
11262 how we could have defined the <code>employee_name</code> view
11263 if we wanted to keep its original structure:</p>
11264
11265 <pre class="cxx">
11266 #pragma db view object(employee)
11267 struct employee_name
11268 {
11269 #pragma db column(employee::name.first_)
11270 std::string first;
11271
11272 #pragma db column(employee::name.last_)
11273 std::string last;
11274 };
11275 </pre>
11276
11277
11278 <!-- CHAPTER -->
11279
11280
11281 <hr class="page-break"/>
11282 <h1><a name="11">11 Session</a></h1>
11283
11284 <p>A session is an application's unit of work that may encompass several
11285 database transactions. In this version of ODB a session is just an
11286 object cache. In future versions it may provide additional
11287 functionality, such as delayed database operations and automatic
11288 object state change tracking. As discussed later in
11289 <a href="#11.2">Section 11.2, "Custom Sessions"</a>, it is also
11290 possible to provide a custom session implementation that provides
11291 these or other features.</p>
11292
11293 <p>Session support is optional and can be enabled or disabled on the
11294 per object basis using the <code>db&nbsp;session</code> pragma, for
11295 example:</p>
11296
11297 <pre class="cxx">
11298 #pragma db object session
11299 class person
11300 {
11301 ...
11302 };
11303 </pre>
11304
11305 <p>We can also enable or disable session support for a group of
11306 objects at the namespace level:</p>
11307
11308 <pre class="cxx">
11309 #pragma db namespace session
11310 namespace accounting
11311 {
11312 #pragma db object // Session support is enabled.
11313 class employee
11314 {
11315 ...
11316 };
11317
11318 #pragma db object session(false) // Session support is disabled.
11319 class employer
11320 {
11321 ...
11322 };
11323 }
11324 </pre>
11325
11326 <p>Finally, we can pass the <code>--generate-session</code> ODB compiler
11327 option to enable session support by default. With this option session
11328 support will be enabled for all the persistent classes except those
11329 for which it was explicitly disabled using the
11330 <code>db&nbsp;session</code>. An alternative to this method with the
11331 same effect is to enable session support for the global namespace:</p>
11332
11333 <pre class="cxx">
11334 #pragma db namespace() session
11335 </pre>
11336
11337 <p>Each thread of execution in an application can have only one active
11338 session at a time. A session is started by creating an instance of
11339 the <code>odb::session</code> class and is automatically terminated
11340 when this instance is destroyed. You will need to include the
11341 <code>&lt;odb/session.hxx></code> header file to make this class
11342 available in your application. For example:</p>
11343
11344 <pre class="cxx">
11345 #include &lt;odb/database.hxx>
11346 #include &lt;odb/session.hxx>
11347 #include &lt;odb/transaction.hxx>
11348
11349 using namespace odb::core;
11350
11351 {
11352 session s;
11353
11354 // First transaction.
11355 //
11356 {
11357 transaction t (db.begin ());
11358 ...
11359 t.commit ();
11360 }
11361
11362 // Second transaction.
11363 //
11364 {
11365 transaction t (db.begin ());
11366 ...
11367 t.commit ();
11368 }
11369
11370 // Session 's' is terminated here.
11371 }
11372 </pre>
11373
11374 <p>The <code>session</code> class has the following interface:</p>
11375
11376 <pre class="cxx">
11377 namespace odb
11378 {
11379 class session
11380 {
11381 public:
11382 session (bool make_current = true);
11383 ~session ();
11384
11385 // Copying or assignment of sessions is not supported.
11386 //
11387 private:
11388 session (const session&amp;);
11389 session&amp; operator= (const session&amp;);
11390
11391 // Current session interface.
11392 //
11393 public:
11394 static session&amp;
11395 current ();
11396
11397 static bool
11398 has_current ();
11399
11400 static void
11401 current (session&amp;);
11402
11403 static void
11404 reset_current ();
11405
11406 static session*
11407 current_pointer ();
11408
11409 static void
11410 current_pointer (session*);
11411
11412 // Object cache interface.
11413 //
11414 public:
11415 template &lt;typename T>
11416 struct cache_position {...};
11417
11418 template &lt;typename T>
11419 cache_position&lt;T>
11420 cache_insert (database&amp;,
11421 const object_traits&lt;T>::id_type&amp;,
11422 const object_traits&lt;T>::pointer_type&amp;);
11423
11424 template &lt;typename T>
11425 object_traits&lt;T>::pointer_type
11426 cache_find (database&amp;, const object_traits&lt;T>::id_type&amp;) const;
11427
11428 template &lt;typename T>
11429 void
11430 cache_erase (const cache_position&lt;T>&amp;);
11431
11432 template &lt;typename T>
11433 void
11434 cache_erase (database&amp;, const object_traits&lt;T>::id_type&amp;);
11435 };
11436 }
11437 </pre>
11438
11439 <p>The session constructor creates a new session and, if the
11440 <code>make_current</code> argument is <code>true</code>, sets it as a
11441 current session for this thread. If we try to make a session current
11442 while there is already another session in effect for this thread,
11443 then the constructor throws the <code>odb::already_in_session</code>
11444 exception. The destructor clears the current session for this
11445 thread if this session is the current one.</p>
11446
11447 <p>The static <code>current()</code> accessor returns the currently active
11448 session for this thread. If there is no active session, this function
11449 throws the <code>odb::not_in_session</code> exception. We can check
11450 whether there is a session in effect in this thread using the
11451 <code>has_current()</code> static function.</p>
11452
11453 <p>The static <code>current()</code> modifier allows us to set the
11454 current session for this thread. The <code>reset_current()</code>
11455 static function clears the current session. These two functions
11456 allow for more advanced use cases, such as multiplexing
11457 two or more sessions on the same thread.</p>
11458
11459 <p>The static <code>current_pointer()</code> overloaded functions
11460 provided the same functionality but using pointers. Specifically,
11461 the <code>current_pointer()</code> accessor can be used to
11462 test whether there is a current session and get a pointer to it
11463 all with a single call.</p>
11464
11465 <p>We normally don't use the object cache interface directly. However,
11466 it could be useful in some cases, for example, to find out whether
11467 an object has already been loaded. Note that when calling
11468 <code>cache_insert()</code>, <code>cache_find()</code>, or
11469 the second version of <code>cache_erase()</code>, you need to
11470 specify the template argument (object type) explicitly. It is
11471 also possible to access the underlying cache data structures
11472 directly. This can be useful if, for example, you want to
11473 iterate over the objects store in the cache. Refer to the ODB
11474 runtime header files for more details on this direct access.</p>
11475
11476 <h2><a name="11.1">11.1 Object Cache</a></h2>
11477
11478 <p>A session is an object cache. Every time a session-enabled object is
11479 made persistent by calling the <code>database::persist()</code> function
11480 (<a href="#3.8">Section 3.8, "Making Objects Persistent"</a>), loaded
11481 by calling the <code>database::load()</code> or <code>database::find()</code>
11482 function (<a href="#3.9">Section 3.9, "Loading Persistent Objects"</a>),
11483 or loaded by iterating over a query result (<a href="#4.4">Section 4.4,
11484 "Query Result"</a>), the pointer to the persistent object, in the form
11485 of the canonical object pointer (<a href="#3.3">Section 3.3, "Object
11486 and View Pointers"</a>), is stored in the session. For as long as the
11487 session is in effect, any subsequent calls to load the same object will
11488 return the cached instance. When an object's state is deleted from the
11489 database with the <code>database::erase()</code> function
11490 (<a href="#3.11">Section 3.11, "Deleting Persistent Objects"</a>), the
11491 cached object pointer is removed from the session. For example:</p>
11492
11493 <pre class="cxx">
11494 shared_ptr&lt;person> p (new person ("John", "Doe"));
11495
11496 session s;
11497 transaction t (db.begin ());
11498
11499 unsigned long id (db.persist (p)); // p is cached in s.
11500 shared_ptr&lt;person> p1 (db.load&lt;person> (id)); // p1 same as p.
11501
11502 t.commit ();
11503 </pre>
11504
11505
11506 <p>The per-object caching policies depend on the object pointer kind
11507 (<a href="#6.5">Section 6.5, "Using Custom Smart Pointers"</a>).
11508 Objects with a unique pointer, such as <code>std::auto_ptr</code>
11509 or <code>std::unique_ptr</code>, as an object pointer are never
11510 cached since it is not possible to have two such pointers pointing
11511 to the same object. When an object is persisted via a pointer or
11512 loaded as a dynamically allocated instance, objects with both raw
11513 and shared pointers as object pointers are cached. If an object is
11514 persisted as a reference or loaded into a pre-allocated instance,
11515 the object is only cached if its object pointer is a raw pointer.</p>
11516
11517 <p>Also note that when we persist an object as a constant reference
11518 or constant pointer, the session caches such an object as
11519 unrestricted (non-<code>const</code>). This can lead to undefined
11520 behavior if the object being persisted was actually created as
11521 <code>const</code> and is later found in the session cache and
11522 used as non-<code>const</code>. As a result, when using sessions,
11523 it is recommended that all persistent objects be created as
11524 non-<code>const</code> instances. The following code fragment
11525 illustrates this point:</p>
11526
11527 <pre class="cxx">
11528 void save (database&amp; db, shared_ptr&lt;const person> p)
11529 {
11530 transaction t (db.begin ());
11531 db.persist (p); // Persisted as const pointer.
11532 t.commit ();
11533 }
11534
11535 session s;
11536
11537 shared_ptr&lt;const person> p1 (new const person ("John", "Doe"));
11538 unsigned long id1 (save (db, p1)); // p1 is cached in s as non-const.
11539
11540 {
11541 transaction t (db.begin ());
11542 shared_ptr&lt;person> p (db.load&lt;person> (id1)); // p == p1
11543 p->age (30); // Undefined behavior since p1 was created const.
11544 t.commit ();
11545 }
11546
11547 shared_ptr&lt;const person> p2 (new person ("Jane", "Doe"));
11548 unsigned long id2 (save (db, p2)); // p2 is cached in s as non-const.
11549
11550 {
11551 transaction t (db.begin ());
11552 shared_ptr&lt;person> p (db.load&lt;person> (id2)); // p == p2
11553 p->age (30); // Ok, since p2 was not created const.
11554 t.commit ();
11555 }
11556 </pre>
11557
11558 <h2><a name="11.2">11.2 Custom Sessions</a></h2>
11559
11560 <p>ODB can use a custom session implementation instead of the
11561 default <code>odb::session</code>. There could be multiple
11562 reasons for an application to provide its own session. For
11563 example, the application may already include a notion of an
11564 object cache or registry which ODB can re-use. A custom
11565 session can also provide additional functionality, such as
11566 automatic change tracking, delayed database operations, or
11567 object eviction. Finally, the session-per-thread approach used
11568 by <code>odb::session</code> may not be suitable for all
11569 applications. For instance, some may need a thread-safe
11570 session that can be shared among multiple threads. For
11571 an example of a custom session that implements automatic
11572 change tracking by keeping original copies of the objects,
11573 refer to the <code>common/session/custom</code> test
11574 in the <code>odb-tests</code> package.</p>
11575
11576 <p>To use a custom session we need to specify its type with
11577 the <code>--session-type</code> ODB compiler command line
11578 option. We also need to include its definition into the
11579 generated header file. This can be achieved with the
11580 <code>--hxx-prologue</code> option. For example, if our
11581 custom session is called <code>app::session</code> and
11582 is defined in the <code>app/session.hxx</code> header
11583 file, then the corresponding ODB compiler options would
11584 look like this:</p>
11585
11586 <pre class="terminal">
11587 odb --hxx-prologue "#include \"app/session.hxx\"" \
11588 --session-type ::app::session ...
11589 </pre>
11590
11591 <p>A custom session should provide the following interface:</p>
11592
11593 <pre class="cxx">
11594 class custom_session
11595 {
11596 public:
11597 template &lt;typename T>
11598 struct cache_position
11599 {
11600 ...
11601 };
11602
11603 // Cache management functions.
11604 //
11605 template &lt;typename T>
11606 static cache_position&lt;T>
11607 _cache_insert (odb::database&amp;,
11608 const typename odb::object_traits&lt;T>::id_type&amp;,
11609 const typename odb::object_traits&lt;T>::pointer_type&amp;);
11610
11611 template &lt;typename T>
11612 static typename odb::object_traits&lt;T>::pointer_type
11613 _cache_find (odb::database&amp;,
11614 const typename odb::object_traits&lt;T>::id_type&amp;);
11615
11616 template &lt;typename T>
11617 static void
11618 _cache_erase (const cache_position&lt;T>&amp;);
11619
11620 // Notification functions.
11621 //
11622 template &lt;typename T>
11623 static void
11624 _cache_persist (const cache_position&lt;T>&amp;);
11625
11626 template &lt;typename T>
11627 static void
11628 _cache_load (const cache_position&lt;T>&amp;);
11629
11630 template &lt;typename T>
11631 static void
11632 _cache_update (odb::database&amp;, const T&amp; obj);
11633
11634 template &lt;typename T>
11635 static void
11636 _cache_erase (odb::database&amp;,
11637 const typename odb::object_traits&lt;T>::id_type&amp;);
11638 };
11639 </pre>
11640
11641 <p>The <code>cache_position</code> class template represents a position
11642 in the cache of the inserted object. It should be default and
11643 copy-constructible as well as copy-assignable. The default
11644 constructor shall create a special empty/<code>NULL</code>
11645 position. A call of any of the cache management or notification
11646 functions with such an empty/<code>NULL</code> position shall be
11647 ignored.</p>
11648
11649 <p>The <code>_cache_insert()</code> function shall add the object into
11650 the object cache and return its position. The <code>_cache_find()</code>
11651 function looks an object up in the object cache given its id.
11652 It returns a <code>NULL</code> pointer if the object is not
11653 found. The <code>_cache_erase()</code> cache management function
11654 shall remove the object from the cache. It is called
11655 if the database operation that caused the object to be inserted
11656 (for example, load) failed. Note also that after insertion the object
11657 state is undefined. You can only access the object state
11658 (for example, make a copy or clear a flag) from one of the
11659 notification functions discussed below.</p>
11660
11661 <p>The notification functions are called after an object has
11662 been persisted, loaded, updated, or erased, respectively. If
11663 your session implementation does not need some of the
11664 notifications, you still have to provide their functions,
11665 however, you can leave their implementations empty.</p>
11666
11667 <p>Notice also that all the cache management and notification
11668 functions are static. This is done in order to allow for a
11669 custom notion of a current session. Normally, the first
11670 step a non-empty implementation will perform is lookup the
11671 current session.</p>
11672
11673
11674 <!-- CHAPTER -->
11675
11676
11677 <hr class="page-break"/>
11678 <h1><a name="12">12 Optimistic Concurrency</a></h1>
11679
11680 <p>The ODB transaction model (<a href="#3.5">Section 3.5,
11681 "Transactions"</a>) guarantees consistency as long as we perform all the
11682 database operations corresponding to a specific application transaction
11683 in a single database transaction. That is, if we load an object within a
11684 database transaction and update it in the same transaction, then we are
11685 guaranteed that the object state that we are updating in the database is
11686 exactly the same as the state we have loaded. In other words, it is
11687 impossible for another process or thread to modify the object state
11688 in the database between these load and update operations.</p>
11689
11690 <p>In this chapter we use the term <em>application transaction</em>
11691 to refer to a set of operations on persistent objects that an
11692 application needs to perform in order to implement some
11693 application-specific functionality. The term <em>database
11694 transaction</em> refers to the set of database operations
11695 performed between the ODB <code>begin()</code> and <code>commit()</code>
11696 calls. Up until now we have treated application transactions and
11697 database transactions as essentially the same thing.</p>
11698
11699 <p>While this model is easy to understand and straightforward to use,
11700 it may not be suitable for applications that have long application
11701 transactions. The canonical example of such a situation is an
11702 application transaction that requires user input between loading
11703 an object and updating it. Such an operation may take an arbitrary
11704 long time to complete and performing it within a single database
11705 transaction will consume database resources as well as prevent
11706 other processes/threads from updating the object for too long.</p>
11707
11708 <p>The solution to this problem is to break up the long-lived
11709 application transaction into several short-lived database
11710 transactions. In our example that would mean loading the object
11711 in one database transaction, waiting for user input, and then
11712 updating the object in another database transaction. For example:</p>
11713
11714 <pre class="cxx">
11715 unsigned long id = ...;
11716 person p;
11717
11718 {
11719 transaction t (db.begin ());
11720 db.load (id, p);
11721 t.commit ();
11722 }
11723
11724 cerr &lt;&lt; "enter age for " &lt;&lt; p.first () &lt;&lt; " " &lt;&lt; p.last () &lt;&lt; endl;
11725 unsigned short age;
11726 cin >> age;
11727 p.age (age);
11728
11729 {
11730 transaction t (db.begin ());
11731 db.update (p);
11732 t.commit ();
11733 }
11734 </pre>
11735
11736 <p>This approach works well if we only have one process/thread that can ever
11737 update the object. However, if we have multiple processes/threads
11738 modifying the same object, then this approach does not guarantee
11739 consistency anymore. Consider what happens in the above example if
11740 another process updates the person's last name while we are waiting for
11741 the user input. Since we loaded the object before this change occured,
11742 our version of the person's data will still have the old name. Once we
11743 receive the input from the user, we go ahead and update the object,
11744 overwriting both the old age with the new one (correct) and the new name
11745 with the old one (incorrect).</p>
11746
11747 <p>While there is no way to restore the consistency guarantee in
11748 an application transaction that consists of multiple database
11749 transactions, ODB provides a mechanism, called optimistic
11750 concurrency, that allows applications to detect and potentially
11751 recover from such inconsistencies.</p>
11752
11753 <p>In essence, the optimistic concurrency model detects mismatches
11754 between the current object state in the database and the state
11755 when it was loaded into the application memory. Such a mismatch
11756 would mean that the object was changed by another process or
11757 thread. There are several ways to implement such state mismatch
11758 detection. Currently, ODB uses object versioning while other
11759 methods, such as timestamps, may be supported in the future.</p>
11760
11761 <p>To declare a persistent class with the optimistic concurrency model we
11762 use the <code>optimistic</code> pragma (<a href="#14.1.5">Section 14.1.5,
11763 "<code>optimistic</code>"</a>). We also use the <code>version</code>
11764 pragma (<a href="#14.4.16">Section 14.4.16, "<code>version</code>"</a>)
11765 to specify which data member will store the object version. For
11766 example:</p>
11767
11768 <pre class="cxx">
11769 #pragma db object optimistic
11770 class person
11771 {
11772 ...
11773
11774 #pragma db version
11775 unsigned long version_;
11776 };
11777 </pre>
11778
11779 <p>The version data member is managed by ODB. It is initialized to
11780 <code>1</code> when the object is made persistent and incremented
11781 by <code>1</code> with each update. The <code>0</code> version value
11782 is not used by ODB and the application can use it as a special value,
11783 for example, to indicate that the object is transient. Note that
11784 for optimistic concurrency to function properly, the application
11785 should not modify the version member after making the object persistent
11786 or loading it from the database and until deleting the state of this
11787 object from the database. To avoid any accidental modifications
11788 to the version member, we can declare it <code>const</code>, for
11789 example:</p>
11790
11791 <pre class="cxx">
11792 #pragma db object optimistic
11793 class person
11794 {
11795 ...
11796
11797 #pragma db version
11798 const unsigned long version_;
11799 };
11800 </pre>
11801
11802 <p>When we call the <code>database::update()</code> function
11803 (<a href="#3.10">Section 3.10, "Updating Persistent Objects"</a>) and pass
11804 an object that has an outdated state, the <code>odb::object_changed</code>
11805 exception is thrown. At this point the application has two
11806 recovery options: it can abort and potentially restart the
11807 application transaction or it can reload the new object
11808 state from the database, re-apply or merge the changes, and call
11809 <code>update()</code> again. Note that aborting an application
11810 transaction that performs updates in multiple database transactions
11811 may require reverting changes that have already been committed to
11812 the database. As a result, this strategy works best if all the
11813 updates are performed in the last database transaction of the
11814 application transaction. This way the changes can be reverted
11815 by simply rolling back this last database transaction.</p>
11816
11817 <p>The following example shows how we can reimplement the above
11818 transaction using the second recovery option:</p>
11819
11820 <pre class="cxx">
11821 unsigned long id = ...;
11822 person p;
11823
11824 {
11825 transaction t (db.begin ());
11826 db.load (id, p);
11827 t.commit ();
11828 }
11829
11830 cerr &lt;&lt; "enter age for " &lt;&lt; p.first () &lt;&lt; " " &lt;&lt; p.last () &lt;&lt; endl;
11831 unsigned short age;
11832 cin >> age;
11833 p.age (age);
11834
11835 {
11836 transaction t (db.begin ());
11837
11838 try
11839 {
11840 db.update (p);
11841 }
11842 catch (const object_changed&amp;)
11843 {
11844 db.reload (p);
11845 p.age (age);
11846 db.update (p);
11847 }
11848
11849 t.commit ();
11850 }
11851 </pre>
11852
11853 <p>An important point to note in the above code fragment is that the second
11854 <code>update()</code> call cannot throw the <code>object_changed</code>
11855 exception because we are reloading the state of the object
11856 and updating it within the same database transaction.</p>
11857
11858 <p>Depending on the recovery strategy employed by the application,
11859 an application transaction with a failed update can be significantly
11860 more expensive than a successful one. As a result, optimistic
11861 concurrency works best for situations with low to medium contention
11862 levels where the majority of the application transactions complete
11863 without update conflicts. This is also the reason why this concurrency
11864 model is called optimistic.</p>
11865
11866 <p>In addition to updates, ODB also performs state mismatch detection
11867 when we are deleting an object from the database
11868 (<a href="#3.11">Section 3.11, "Deleting Persistent Objects"</a>).
11869 To understand why this can be important, consider the following
11870 application transaction:</p>
11871
11872 <pre class="cxx">
11873 unsigned long id = ...;
11874 person p;
11875
11876 {
11877 transaction t (db.begin ());
11878 db.load (id, p);
11879 t.commit ();
11880 }
11881
11882 string answer;
11883 cerr &lt;&lt; "age is " &lt;&lt; p.age () &lt;&lt; ", delete?" &lt;&lt; endl;
11884 getline (cin, answer);
11885
11886 if (answer == "yes")
11887 {
11888 transaction t (db.begin ());
11889 db.erase (p);
11890 t.commit ();
11891 }
11892 </pre>
11893
11894 <p>Consider again what happens if another process or thread updates
11895 the object by changing the person's age while we are waiting for
11896 the user input. In this case, the user makes the decision based on
11897 a certain age while we may delete (or not delete) an object that has
11898 a completely different age. Here is how we can fix this problem
11899 using optimistic concurrency:</p>
11900
11901 <pre class="cxx">
11902 unsigned long id = ...;
11903 person p;
11904
11905 {
11906 transaction t (db.begin ());
11907 db.load (id, p);
11908 t.commit ();
11909 }
11910
11911 string answer;
11912 for (bool done (false); !done; )
11913 {
11914 if (answer.empty ())
11915 cerr &lt;&lt; "age is " &lt;&lt; p.age () &lt;&lt; ", delete?" &lt;&lt; endl;
11916 else
11917 cerr &lt;&lt; "age changed to " &lt;&lt; p.age () &lt;&lt; ", still delete?" &lt;&lt; endl;
11918
11919 getline (cin, answer);
11920
11921 if (answer == "yes")
11922 {
11923 transaction t (db.begin ());
11924
11925 try
11926 {
11927 db.erase (p);
11928 done = true;
11929 }
11930 catch (const object_changed&amp;)
11931 {
11932 db.reload (p);
11933 }
11934
11935 t.commit ();
11936 }
11937 else
11938 done = true;
11939 }
11940 </pre>
11941
11942 <p>Note that state mismatch detection is performed only if we delete
11943 an object by passing the object instance to the <code>erase()</code>
11944 function. If we want to delete an object with the optimistic concurrency
11945 model regardless of its state, then we need to use the <code>erase()</code>
11946 function that deletes an object given its id, for example:</p>
11947
11948 <pre class="cxx">
11949 {
11950 transaction t (db.begin ());
11951 db.erase (p.id ());
11952 t.commit ();
11953 }
11954 </pre>
11955
11956 <p>Finally, note that for persistent classes with the optimistic concurrency
11957 model both the <code>update()</code> function as well as the
11958 <code>erase()</code> function that accepts an object instance as its
11959 argument no longer throw the <code>object_not_persistent</code>
11960 exception if there is no such object in the database. Instead,
11961 this condition is treated as a change of object state and the
11962 <code>object_changed</code> exception is thrown instead.</p>
11963
11964 <p>For complete sample code that shows how to use optimistic
11965 concurrency, refer to the <code>optimistic</code> example in
11966 the <code>odb-examples</code> package.</p>
11967
11968
11969 <!-- CHAPTER -->
11970
11971
11972 <hr class="page-break"/>
11973 <h1><a name="13">13 Database Schema Evolution</a></h1>
11974
11975 <p>When we add new persistent classes or change the existing ones, for
11976 example, by adding or deleting data members, the database schema
11977 necessary to store the new object model changes as well. At the
11978 same time, we may have existing databases that contain existing data.
11979 If new versions of your application don't need to handle
11980 old databases, then the schema creating functionality is all that
11981 you need. However, most applications will need to work with data
11982 stored by older versions of the same application.</p>
11983
11984 <p>We will call <em>database schema evolution</em> the overall task
11985 of updating the database to match the changes in the object model.
11986 Schema evolution usually consists of two sub-tasks: <em>schema
11987 migration</em> and <em>data migration</em>. Schema migration
11988 modifies the database schema to correspond to the current
11989 object model. In a relational database, this, for example, could
11990 require adding or dropping tables and columns. The data migration
11991 task involves converting the data stored in the existing database
11992 from the old format to the new one.</p>
11993
11994 <p>If performed manually, database schema evolution is a tedious and
11995 error-prone task. As a result, ODB provides comprehensive support
11996 for automated or, more precisely, semi-automated schema
11997 evolution. Specifically, ODB does fully-automatic schema
11998 migration and provides facilities to help you with data
11999 migration.</p>
12000
12001 <p>The topic of schema evolution is a complex and sensitive
12002 issue since normally there would be valuable, production data at
12003 stake. As a result, the approach taken by ODB is to provide simple
12004 and bullet-proof elementary building blocks (or migration steps)
12005 that we can understand and trust. Using these elementary blocks we
12006 can then implement more complex migration scenarios. In particular,
12007 ODB does not try to handle data migration automatically since in most
12008 cases this requires understanding of application-specific semantics.
12009 In other words, there is no magic.</p>
12010
12011 <p>There are two general approaches to working with older data: the
12012 application can either convert it to correspond to the new format
12013 or it can be made capable of working with multiple versions of this
12014 format. There is also a hybrid approach where the application
12015 may convert the data to the new format gradually as part of its
12016 normal functionality. ODB is capable of handling all these
12017 scenarios. That is, there is support for working with older
12018 models without performing any migration (schema or data).
12019 Alternatively, we can migrate the schema after
12020 which we have the choice of either also immediately migrating the
12021 data (<em>immediate data migration</em>) or doing it gradually
12022 (<em>gradual data migration</em>).</p>
12023
12024 <p>Schema evolution is already a complex task and we should not
12025 unnecessarily use a more complex approach where a simpler one
12026 would be sufficient. From the above, the simplest approach is
12027 the immediate schema migration that does not require any data
12028 migration. An example of such a change would be adding a new
12029 data member with the default value (<a href="#14.3.4">Section
12030 14.3.4, "<code>default</code>"</a>). This case ODB can handle
12031 completely automatically.</p>
12032
12033 <p>If we do require data migration, then the next simplest approach
12034 is the immediate schema and data migration. Here we have to write
12035 custom migration code. However, it is separate from the rest of
12036 the core application logic and is executed at a well defined point
12037 (database migration). In other words, the core application logic
12038 need not be aware of older model versions. The potential drawback
12039 of this approach is performance. It may take a lot of resources
12040 and/or time to convert all the data upfront.</p>
12041
12042 <p>If the immediate migration is not possible, then the next option
12043 is the immediate schema migration followed by the gradual data
12044 migration. With this approach, both old and new data must co-exist
12045 in the new database. We also have to change the application
12046 logic to both account for different sources of the same data (for
12047 example, when either an old or new version of the object is loaded)
12048 as well as migrate the data when appropriate (for example, when
12049 the old version of the object is updated). At some point, usually
12050 when the majority of the data has been converted, gradual migrations
12051 are terminated with an immediate migration.</p>
12052
12053 <p>The most complex approach is working with multiple versions of
12054 the database without performing any migrations, schema or data.
12055 ODB does provide support for implementing this approach
12056 (<a href="#13.4">Section 13.4, "Soft Object Model Changes"</a>),
12057 however we will not cover it any further in this chapter.
12058 Generally, this will require embedding knowledge about each
12059 version into the core application logic which makes it hard
12060 to maintain for any non-trivial object model.</p>
12061
12062 <p>Note also that when it comes to data migration, we can use
12063 the immediate variant for some changes and gradual for others.
12064 We will discuss various migration scenarios in greater detail
12065 in section <a href="#13.3">Section 13.3, "Data Migration"</a>.</p>
12066
12067 <h2><a name="13.1">13.1 Object Model Version and Changelog</a></h2>
12068
12069 <p>To enable schema evolution support in ODB we need to specify
12070 the object model version, or, more precisely, two versions.
12071 The first is the base model version. It is the lowest
12072 version from which we will be able to migrate. The second
12073 version is the current model version. In ODB we can migrate
12074 from multiple previous versions by successively migrating
12075 from one to the next until we reach the current version.
12076 We use the <code>db&nbsp;model&nbsp;version</code> pragma
12077 to specify both the base and current versions.</p>
12078
12079 <p>When we enable schema evolution for the first time, our
12080 base and current versions will be the same, for example:</p>
12081
12082 <pre class="cxx">
12083 #pragma db model version(1, 1)
12084 </pre>
12085
12086 <p>Once we release our application, its users may create databases
12087 with the schema corresponding to this version of the object
12088 model. This means that if we make any modifications to our
12089 object model that also change the schema, then we will need
12090 to be able to migrate the old databases to this new schema.
12091 As a result, before making any new changes after a release,
12092 we increment the current version, for example:</p>
12093
12094 <pre class="cxx">
12095 #pragma db model version(1, 2)
12096 </pre>
12097
12098 <p>To put this another way, we can stay on the same version
12099 during development and keep adding new changes to it. But
12100 once we release it, any new changes to the object model will
12101 have to be done in a new version.</p>
12102
12103 <p>It is easy to forget to increment the version before
12104 making new changes to the object model. To help solve this
12105 problem, the <code>db&nbsp;model&nbsp;version</code> pragma
12106 accepts a third optional argument that specify whether the
12107 current version is open or closed for changes. For example:</p>
12108
12109 <pre class="cxx">
12110 #pragma db model version(1, 2, open) // Can add new changes to
12111 // version 2.
12112 </pre>
12113
12114 <pre class="cxx">
12115 #pragma db model version(1, 2, closed) // Can no longer add new
12116 // changes to version 2.
12117 </pre>
12118
12119 <p>If the current version is closed, ODB will refuse to accept
12120 any new schema changes. In this situation you would
12121 normally increment the current version and mark it as open
12122 or you could re-open the existing version if, for example,
12123 you need to fix something. Note, however, that re-opening
12124 versions that have been released will most likely result
12125 in migration malfunctions. By default the version is open.</p>
12126
12127 <p>Normally, an application will have a range of older database
12128 versions from which it is able to migrate. When we change
12129 this range by removing support for older versions, we also
12130 need to adjust the base model version. This will make sure
12131 that ODB does not keep unnecessary information around.</p>
12132
12133 <p>A model version (both base and current) is a 64-bit unsigned
12134 integer (<code>unsigned&nbsp;long&nbsp;long</code>). <code>0</code>
12135 is reserved to signify special situations, such as the lack of
12136 schema in the database. Other than that, we can use any values
12137 as versions as long as they are monotonically increasing. In
12138 particular, we don't have to start with version <code>1</code>
12139 and can increase the versions by any increment.</p>
12140
12141 <p>One versioning approach is to use an independent
12142 object model version by starting from version <code>1</code>
12143 and also incrementing by <code>1</code>. The alternative
12144 is to make the model version correspond to the application
12145 version. For example, if our application is using the
12146 <code>X.Y.Z</code> version format, then we could encode it
12147 as a hexadecimal number and use that as our model version,
12148 for example:</p>
12149
12150 <pre class="cxx">
12151 #pragma db model version(0x020000, 0x020306) // 2.0.0-2.3.6
12152 </pre>
12153
12154 <p>Most real-world object models will be spread over multiple
12155 header files and it will be burdensome to repeat the
12156 <code>db&nbsp;model&nbsp;version</code> pragma in each of
12157 them. The recommended way to handle this situation is to
12158 place the <code>version</code> pragma into a separate header
12159 file and include it into the object model files. If your
12160 project already has a header file that defines the
12161 application version, then it is natural to place this
12162 pragma there. For example:</p>
12163
12164 <pre class="cxx">
12165 // version.hxx
12166 //
12167 // Define the application version.
12168 //
12169
12170 #define MYAPP_VERSION 0x020306 // 2.3.6
12171
12172 #ifdef ODB_COMPILER
12173 #pragma db model version(1, 7)
12174 #endif
12175 </pre>
12176
12177 <p>Note that we can also use macros in the <code>version</code>
12178 pragma which allows us to specify all the versions in a single
12179 place. For example:</p>
12180
12181 <pre class="cxx">
12182 #define MYAPP_VERSION 0x020306 // 2.3.6
12183 #define MYAPP_BASE_VERSION 0x020000 // 2.0.0
12184
12185 #ifdef ODB_COMPILER
12186 #pragma db model version(MYAPP_BASE_VERSION, MYAPP_VERSION)
12187 #endif
12188 </pre>
12189
12190 <p>It is also possible to have multiple object models within the
12191 same application that have different versions. Such models
12192 must be independent, that is, no headers from one model shall
12193 include a header from another. You will also need to assign
12194 different schema names to each model with the
12195 <code>--schema-name</code> ODB compiler option.</p>
12196
12197 <p>Once we specify the object model version, the ODB compiler
12198 starts tracking database schema changes in a changelog file.
12199 Changelog has an XML-based, line-oriented format. It uses
12200 XML in order to provide human readability while also
12201 facilitating, if desired, processing and analysis with
12202 custom tools. The line orientation makes it easy to review
12203 with tools like <code>diff</code>.</p>
12204
12205 <p>The changelog is maintained by the ODB compiler. Specifically,
12206 you do not need to make any manual changes to this file. You
12207 will, however, need to keep it around from one invocation of
12208 the ODB compiler to the next. In other words, the changelog
12209 file is both the input and the output of the ODB compiler. This,
12210 for example, means that if your project's source code is stored
12211 in a version control repository, then you will most likely want
12212 to store the changelog there as well. If you delete the changelog,
12213 then any ability to do schema migration will be lost.</p>
12214
12215 <p>The only operation that you may want to perform with the
12216 changelog is to review the database schema changes that resulted
12217 from the C++ object model changes. For this you can use a tool
12218 like <code>diff</code> or, better yet, the change review facilities
12219 offered by your revision control system. For this purpose the
12220 contents of a changelog will be self-explanatory.</p>
12221
12222 <p>As an example, consider the following initial object model:</p>
12223
12224 <pre class="cxx">
12225 // person.hxx
12226 //
12227
12228 #include &lt;string>
12229
12230 #pragma db model version(1, 1)
12231
12232 #pragma db object
12233 class person
12234 {
12235 ...
12236
12237 #pragma db id auto
12238 unsigned long id_;
12239
12240 std::string first_;
12241 std::string last_;
12242 };
12243 </pre>
12244
12245 <p>We then compile this header file with the ODB compiler (using the
12246 PostgreSQL database as an example):</p>
12247
12248 <pre class="terminal">
12249 odb --database pgsql --generate-schema person.hxx
12250 </pre>
12251
12252 <p>If we now look at the list of generated files, then in addition to
12253 the now familiar <code>person-odb.?xx</code> and <code>person.sql</code>,
12254 we will also see <code>person.xml</code> &mdash; the changelog file.
12255 Just for illustration, below are the contents of this changelog.</p>
12256
12257 <pre class="xml">
12258 &lt;changelog database="pgsql">
12259 &lt;model version="1">
12260 &lt;table name="person" kind="object">
12261 &lt;column name="id" type="BIGINT" null="false"/>
12262 &lt;column name="first" type="TEXT" null="false"/>
12263 &lt;column name="last" type="TEXT" null="false"/>
12264 &lt;primary-key auto="true">
12265 &lt;column name="id"/>
12266 &lt;/primary-key>
12267 &lt;/table>
12268 &lt;/model>
12269 &lt;/changelog>
12270 </pre>
12271
12272 <p>Let's say we now would like to add another data member to the
12273 <code>person</code> class &mdash; the middle name. We increment
12274 the version and make the change:</p>
12275
12276 <pre class="cxx">
12277 #pragma db model version(1, 2)
12278
12279 #pragma db object
12280 class person
12281 {
12282 ...
12283
12284 #pragma db id auto
12285 unsigned long id_;
12286
12287 std::string first_;
12288 std::string middle_;
12289 std::string last_;
12290 };
12291 </pre>
12292
12293 <p>We use exactly the same command line to re-compile our file:</p>
12294
12295 <pre class="terminal">
12296 odb --database pgsql --generate-schema person.hxx
12297 </pre>
12298
12299 <p>This time the ODB compiler will read the old changelog, update
12300 it, and write out the new version. Again, for illustration only,
12301 below are the updated changelog contents:</p>
12302
12303 <pre class="xml">
12304 &lt;changelog database="pgsql">
12305 &lt;changeset version="2">
12306 &lt;alter-table name="person">
12307 &lt;add-column name="middle" type="TEXT" null="false"/>
12308 &lt;/alter-table>
12309 &lt;/changeset>
12310
12311 &lt;model version="1">
12312 &lt;table name="person" kind="object">
12313 &lt;column name="id" type="BIGINT" null="false"/>
12314 &lt;column name="first" type="TEXT" null="false"/>
12315 &lt;column name="last" type="TEXT" null="false"/>
12316 &lt;primary-key auto="true">
12317 &lt;column name="id"/>
12318 &lt;/primary-key>
12319 &lt;/table>
12320 &lt;/model>
12321 &lt;/changelog>
12322 </pre>
12323
12324 <p>Just to reiterate, while the changelog may look like it could
12325 be written by hand, it is maintained completely automatically
12326 by the ODB compiler and the only reason you may want to look
12327 at its contents is to review the database schema changes. For
12328 example, if we compare the above two changelogs with
12329 <code>diff</code>, we will get the following summary of the
12330 database schema changes:</p>
12331
12332 <pre class="xml">
12333 --- person.xml.orig
12334 +++ person.xml
12335 @@ -1,4 +1,10 @@
12336 &lt;changelog database="pgsql">
12337 <span style="color: #009E00">+ &lt;changeset version="2">
12338 + &lt;alter-table name="person">
12339 + &lt;add-column name="middle" type="TEXT" null="false"/>
12340 + &lt;/alter-table>
12341 + &lt;/changeset>
12342 +</span>
12343 &lt;model version="1">
12344 &lt;table name="person" kind="object">
12345 &lt;column name="id" type="BIGINT" null="false"/>
12346 </pre>
12347
12348 <p>The changelog is only written when we generate the database schema,
12349 that is, the <code>--generate-schema</code> option is specified.
12350 Invocations of the ODB compiler that only produce the database
12351 support code (C++) do not read or update the changelog. To put it
12352 another way, the changelog tracks changes in the resulting database
12353 schema, not the C++ object model.</p>
12354
12355 <p>ODB ignores column order when comparing database schemas. This means
12356 that we can re-order data members in a class without causing any
12357 schema changes. Member renames, however, will result in schema
12358 changes since the column name changes as well (unless we specified
12359 the column name explicitly). From ODB's perspective such a rename
12360 looks like the deletion of one data member and the addition of
12361 another. If we don't want this to be treated as a schema change,
12362 then we will need to keep the old column name by explicitly
12363 specifying it with the <code>db&nbsp;column</code> pragma. For
12364 example, here is how we can rename <code>middle_</code> to
12365 <code>middle_name_</code> without causing any schema changes:</p>
12366
12367 <pre class="cxx">
12368 #pragma db model version(1, 2)
12369
12370 #pragma db object
12371 class person
12372 {
12373 ...
12374
12375 #pragma db column("middle") // Keep the original column name.
12376 std::string middle_name_;
12377
12378 ...
12379 };
12380 </pre>
12381
12382 <p>If your object model consists of a large number of header files and
12383 you generate the database schema for each of them individually, then
12384 a changelog will be created for each of your header files. This may
12385 be what you want, however, the large number of changelogs can quickly
12386 become unwieldy. In fact, if you are generating the database schema
12387 as standalone SQL files, then you may have already experienced a
12388 similar problem caused by a large number of <code>.sql</code> files,
12389 one for each header.</p>
12390
12391 <p>The solution to both of these problems is to generate a combined
12392 database schema file and a single changelog. For example, assume
12393 we have three header files in our object model:
12394 <code>person.hxx</code>, <code>employee.hxx</code>, and
12395 <code>employer.hxx</code>. To generate the database support code
12396 we compile them as usual but without specifying the
12397 <code>--generate-schema</code> option. In this case no changelog
12398 is created or updated:</p>
12399
12400 <pre class="terminal">
12401 odb --database pgsql person.hxx
12402 odb --database pgsql employee.hxx
12403 odb --database pgsql employer.hxx
12404 </pre>
12405
12406 <p>To generate the database schema, we perform a separate invocation
12407 of the ODB compiler. This time, however, we instruct it to only
12408 generate the schema (<code>--generate-schema-only</code>) and
12409 produce it combined (<code>--at-once</code>) for all the files
12410 in our object model:</p>
12411
12412 <pre class="terminal">
12413 odb --database pgsql --generate-schema-only --at-once \
12414 --input-name company person.hxx employee.hxx employer.hxx
12415 </pre>
12416
12417 <p>The result of the above command is a single <code>company.sql</code>
12418 file (the name is derived from the <code>--input-name</code> value)
12419 that contains the database schema for our entire object model. There
12420 is also a single corresponding changelog file &mdash;
12421 <code>company.xml</code>.</p>
12422
12423 <p>The same can be achieved for the embedded schema by instructing
12424 the ODB compiler to generate the database creation code into a
12425 separate C++ file (<code>--schema-format&nbsp;separate</code>):</p>
12426
12427 <pre class="terminal">
12428 odb --database pgsql --generate-schema-only --schema-format separate \
12429 --at-once --input-name company person.hxx employee.hxx employer.hxx
12430 </pre>
12431
12432 <p>The result of this command is a single <code>company-schema.cxx</code>
12433 file and, again, <code>company.xml</code>.</p>
12434
12435 <p>Note also that by default the changelog file is not placed into
12436 the directory specified with the <code>--output-dir</code> option.
12437 This is due to the changelog being both an input and an output file
12438 at the same time. As a result, by default, the ODB compiler will
12439 place it in the directory of the input header file.</p>
12440
12441 <p>There is, however, a number of command line options (including
12442 <code>--changelog-dir</code>) that allow us to fine-tune the name and
12443 location of the changelog file. For example, you can instruct the ODB
12444 compiler to read the changelog from one file while writing it to
12445 another. This, for example, can be useful if you want to review
12446 the changes before discarding the old file. For more information
12447 on these options, refer to the
12448 <a href="http://www.codesynthesis.com/products/odb/doc/odb.xhtml">ODB
12449 Compiler Command Line Manual</a> and search for "changelog".</p>
12450
12451 <p>When we were discussing version increments above, we used the
12452 terms <em>development</em> and <em>release</em>. Specifically,
12453 we talked about keeping the same object model versions during
12454 development periods and incrementing them after releases.
12455 What is a development period and a release in this context?
12456 These definitions can vary from project to project.
12457 Generally, during a development period we work on one or
12458 more changes to the object model that result in the changes
12459 to the database schema. A release is a point where we
12460 make our changes available to someone else who may have an
12461 older database to migrate from. In the traditional sense, a release
12462 is a point where you make a new version of your application available
12463 to its users. However, for schema evolution purposes, a release
12464 could also mean simply making your schema-altering changes
12465 available to other developers on your team. Let us consider
12466 two common scenarios to illustrate how all this fits together.</p>
12467
12468 <p>One way to setup a project would be to re-use the application
12469 development period and application release for schema evolution.
12470 That is, during a new application version development we keep
12471 a single object model version and when we release the application,
12472 we increment the model version. In this case it makes sense to
12473 also reuse the application version as a model version for
12474 consistency. Here is a step-by-step guide for this setup:</p>
12475
12476 <ol>
12477 <li>During development, keep the current object model version open.</li>
12478
12479 <li>Before the release (for example, when entering a "feature freeze")
12480 close the version.</li>
12481
12482 <li>After the release, update the version and open it.</li>
12483
12484 <li>For each new feature, review the changeset at the top of the
12485 changelog, for example, with <code>diff</code> or your
12486 version control facilities. If you are using a version
12487 control, then this is best done just before committing
12488 your changes to the repository.</li>
12489 </ol>
12490
12491 <p>An alternative way to setup schema versioning in a project would
12492 be to define the development period as working on a single
12493 feature and the release as making this feature available to
12494 other people (developers, testers, etc.) on your team, for
12495 example, by committing the changes to a public version control
12496 repository. In this case, the object model version will be
12497 independent of the application version and can simply be
12498 a sequence that starts with <code>1</code> and is
12499 incremented by <code>1</code>. Here is a step-by-step guide
12500 for this setup:</p>
12501
12502 <ol>
12503 <li>Keep the current model version closed. Once a change is made
12504 that affects the database schema, the ODB compiler will refuse
12505 to update the changelog.</li>
12506
12507 <li>If the change is legitimate, open a new version, that is,
12508 increment the current version and make it open.</li>
12509
12510 <li>Once the feature is implemented and tested, review the final
12511 set of database changes (with <code>diff</code> or your
12512 version control facilities), close the version, and commit
12513 the changes to the version control repository (if using).</li>
12514 </ol>
12515
12516 <p>If you are using a version control repository that supports
12517 pre-commit checks, then you may want to consider adding such
12518 a check to make sure the committed version is always closed.</p>
12519
12520 <p>If we are just starting schema evolution in our project, which
12521 approach should we choose? The two approaches will work better
12522 in different situations since they have a different set of
12523 advantages and disadvantages. The first approach, which we
12524 can call version per application release, is best suited
12525 for simpler projects with smaller releases since otherwise
12526 a single migration will bundle a large number of unrelated
12527 actions corresponding to different features. This can
12528 become difficult to review and, if things go wrong, debug.</p>
12529
12530 <p>The second approach, which we can call version per feature,
12531 is much more modular and provides a number of additional benefits.
12532 We can perform migrations for each feature as a discreet step
12533 which makes it easier to debug. We can also place each such
12534 migration step into a separate transaction further improving
12535 reliability. It also scales much better in larger teams
12536 where multiple developers can work concurrently on features
12537 that affect the database schema. For example, if you find
12538 yourself in a situation where another developer on your
12539 team used the same version as you and managed to commit his
12540 changes before you (that is, you have a merge conflict),
12541 then you can simply change the version to the next available
12542 one, regenerate the changelog, and continue with your commit.</p>
12543
12544 <p>Overall, unless you have strong reasons to prefer the version
12545 per application release approach, rather choose version per
12546 feature even though it may seem more complex at the
12547 beginning. Also, if you do select the first approach, consider
12548 provisioning for switching to the second method by reserving
12549 a sub-version number. For example, for an application version
12550 in the form <code>2.3.4</code> you can make the object model
12551 version to be in the form <code>0x0203040000</code>, reserving
12552 the last two bytes for a sub-version. Later on you can use it to
12553 switch to the version per feature approach.</p>
12554
12555 <h2><a name="13.2">13.2 Schema Migration</a></h2>
12556
12557 <p>Once we enable schema evolution by specifying the object model
12558 version, in addition to the schema creation statements, the
12559 ODB compiler starts generating schema migration statements
12560 for each version all the way from the base to the current.
12561 As with schema creation, schema migration can be generated
12562 either as a set of SQL files or embedded into the generated
12563 C++ code (<code>--schema-format</code> option).</p>
12564
12565 <p>For each migration step, that is from one version to the next,
12566 ODB generates two sets of statements: pre-migration and
12567 post-migration. The pre-migration statements <em>"relax"</em>
12568 the database schema so that both old and new data can co-exist.
12569 At this stage new columns and tables are added while old
12570 constraints are dropped. The post-migration statements
12571 <em>"tighten"</em> the database schema back so that only
12572 data conforming to the new format can remain. At this stage
12573 old columns and tables are dropped and new constraints are
12574 added. Now you can probably guess where the data
12575 migration fits into this &mdash; between the pre and post
12576 schema migrations where we can both access the old data
12577 and create the new one.</p>
12578
12579 <p>If the schema is being generated as standalone SQL files,
12580 then we end up with a pair of files for each step: the pre-migration
12581 file and the post-migration file. For the <code>person</code>
12582 example we started in the previous section we will have the
12583 <code>person-002-pre.sql</code> and <code>person-002-post.sql</code>
12584 files. Here <code>002</code> is the version <em>to</em> which
12585 we are migrating while the <code>pre</code> and <code>post</code>
12586 suffixes specify the migration stage. So if we wanted to migrate
12587 a <code>person</code> database from version <code>1</code>
12588 to <code>2</code>, then we would first execute
12589 <code>person-002-pre.sql</code>, then migrate the data, if any
12590 (discussed in more detail in the next section), and finally
12591 execute <code>person-002-post.sql</code>. If our database is
12592 several versions behind, for example the database has version
12593 <code>1</code> while the current version is <code>5</code>,
12594 then we simply perform this set of steps for each version
12595 until we reach the current version.</p>
12596
12597 <p>If we look at the contents of the <code>person-002-pre.sql</code>
12598 file, we will see the following (or equivalent, depending on the
12599 database used) statement:</p>
12600
12601 <pre class="sql">
12602 ALTER TABLE "person"
12603 ADD COLUMN "middle" TEXT NULL;
12604 </pre>
12605
12606 <p>As we would expect, this statement adds a new column corresponding
12607 to the new data member. An observant reader would notice,
12608 however, that the column is added as <code>NULL</code>
12609 even though we never requested this semantics in our object model.
12610 Why is the column added as <code>NULL</code>? If during migration
12611 the <code>person</code> table already contains rows (that is, existing
12612 objects), then an attempt to add a non-<code>NULL</code> column that
12613 doesn't have a default value will fail. As a result, ODB will initially
12614 add a new column that doesn't have a default value as <code>NULL</code>
12615 but then clean this up at the post-migration stage. This way your data
12616 migration code is given a chance to assign some meaningful values for
12617 the new data member for all the existing objects. Here are the contents
12618 of the <code>person-002-post.sql</code> file:</p>
12619
12620 <pre class="sql">
12621 ALTER TABLE "person"
12622 ALTER COLUMN "middle" SET NOT NULL;
12623 </pre>
12624
12625 <p>Currently ODB directly supports the following elementary database
12626 schema changes:</p>
12627
12628 <ul class="list">
12629 <li>add table</li>
12630 <li>drop table</li>
12631 <li>add column</li>
12632 <li>drop column</li>
12633 <li>alter column, set <code>NULL</code>/<code>NOT NULL</code></li>
12634 <li>add foreign key</li>
12635 <li>drop foreign key</li>
12636 <li>add index</li>
12637 <li>drop index</li>
12638 </ul>
12639
12640 <p>More complex changes can normally be implemented in terms of
12641 these building blocks. For example, to change a type of a
12642 data member (which leads to a change of a column type), we
12643 can add a new data member with the desired type (add column),
12644 migrate the data, and then delete the old data member (drop
12645 column). ODB will issue diagnostics for cases that are
12646 currently not supported directly. Note also that some database
12647 systems (notably SQLite) have a number of limitations in their
12648 support for schema changes. For more information on these
12649 database-specific limitations, refer to the "Limitations" sections
12650 in <a href="#II">Part II, "Database Systems"</a>.</p>
12651
12652 <p>How do we know what the current database version is? That is, the
12653 version <em>from</em> which we need to migrate? We need to know this,
12654 for example, in order to determine the set of migrations we have to
12655 perform. By default, when schema evolution is enabled, ODB maintains
12656 this information in a special table called <code>schema_version</code>
12657 that has the following (or equivalent, depending on the database
12658 used) definition:</p>
12659
12660 <pre class="sql">
12661 CREATE TABLE "schema_version" (
12662 "name" TEXT NOT NULL PRIMARY KEY,
12663 "version" BIGINT NOT NULL,
12664 "migration" BOOLEAN NOT NULL);
12665 </pre>
12666
12667 <p>The <code>name</code> column is the schema name as specified with
12668 the <code>--schema-name</code> option. It is empty for the default
12669 schema. The <code>version</code> column contains the current database
12670 version. And, finally, the <code>migration</code> flag indicates
12671 whether we are in the process of migrating the database, that is,
12672 between the pre and post-migration stages.</p>
12673
12674 <p>The schema creation statements (<code>person.sql</code> in our case)
12675 create this table and populate it with the initial model version. For
12676 example, if we executed <code>person.sql</code> corresponding to
12677 version <code>1</code> of our object model, then <code>name</code>
12678 would have been empty (which signifies the default schema since we
12679 didn't specify <code>--schema-name</code>), <code>version</code> will
12680 be <code>1</code> and <code>migration</code> will be
12681 <code>FALSE</code>.</p>
12682
12683 <p>The pre-migration statements update the version and set the migration
12684 flag to <code>TRUE</code>. Continuing with our example, after executing
12685 <code>person-002-pre.sql</code>, <code>version</code> will
12686 become <code>2</code> and <code>migration</code> will be set to
12687 <code>TRUE</code>. The post-migration statements simply clear the
12688 migration flag. In our case, after running
12689 <code>person-002-post.sql</code>, <code>version</code> will
12690 remain <code>2</code> while <code>migration</code> will be reset
12691 to <code>FALSE</code>.</p>
12692
12693 <p>Note also that above we mentioned that the schema creation statements
12694 (<code>person.sql</code>) create the <code>schema_version</code> table.
12695 This means that if we enable schema evolution support in the middle
12696 of a project, then we could already have existing databases that
12697 don't include this table. As a result, ODB will not be able to handle
12698 migrations for such databases unless we manually add the
12699 <code>schema_version</code> table and populate it with the correct
12700 version information. For this reason, it is highly recommended that
12701 you consider whether to use schema evolution and, if so, enable it
12702 from the beginning of your project.</p>
12703
12704 <p>The <code>odb::database</code> class provides an API for accessing
12705 and modifying the current database version:</p>
12706
12707 <pre class="cxx">
12708 namespace odb
12709 {
12710 typedef unsigned long long schema_version;
12711
12712 struct LIBODB_EXPORT schema_version_migration
12713 {
12714 schema_version_migration (schema_version = 0,
12715 bool migration = false);
12716
12717 schema_version version;
12718 bool migration;
12719
12720 // This class also provides the ==, !=, &lt;, >, &lt;=, and >= operators.
12721 // Version ordering is as follows: {1,f} &lt; {2,t} &lt; {2,f} &lt; {3,t}.
12722 };
12723
12724 class database
12725 {
12726 public:
12727 ...
12728
12729 schema_version
12730 schema_version (const std::string&amp; name = "") const;
12731
12732 bool
12733 schema_migration (const std::string&amp; name = "") const;
12734
12735 const schema_version_migration&amp;
12736 schema_version_migration (const std::string&amp; name = "") const;
12737
12738 // Set schema version and migration state manually.
12739 //
12740 void
12741 schema_version_migration (schema_version,
12742 bool migration,
12743 const std::string&amp; name = "");
12744
12745 void
12746 schema_version_migration (const schema_version_migration&amp;,
12747 const std::string&amp; name = "");
12748
12749 // Set default schema version table for all schemas.
12750 //
12751 void
12752 schema_version_table (const std::string&amp; table_name);
12753
12754 // Set schema version table for a specific schema.
12755 //
12756 void
12757 schema_version_table (const std::string&amp; table_name,
12758 const std::string&amp; name);
12759 };
12760 }
12761 </pre>
12762
12763 <p>The <code>schema_version()</code> and <code>schema_migration()</code>
12764 accessors return the current database version and migration flag,
12765 respectively. The optional <code>name</code> argument is the schema
12766 name. If the database schema hasn't been created (that is, there is
12767 no corresponding entry in the <code>schema_version</code> table or
12768 this table does not exist), then <code>schema_version()</code> returns
12769 <code>0</code>. The <code>schema_version_migration()</code> accessor
12770 returns both version and migration flag together in the
12771 <code>schema_version_migration</code> <code>struct</code>.</p>
12772
12773 <p>You may already have a version table in your database or you (or your
12774 database administrator) may prefer to keep track of versions your own
12775 way. You can instruct ODB not to create the <code>schema_version</code>
12776 table with the <code>--suppress-schema-version</code> option. However,
12777 ODB still needs to know the current database version in order for certain
12778 schema evolution mechanisms to function properly. As a result, in
12779 this case, you will need to set the schema version on the database
12780 instance manually using the schema_version_migration() modifier.
12781 Note that the modifier API is not thread-safe. That is, you should
12782 not modify the schema version while other threads may be accessing
12783 or modifying the same information.</p>
12784
12785 <p>Note also that the accessors we discussed above will only query the
12786 <code>schema_version</code> table once and, if the version could
12787 be determined, cache the result. If, however, the version could
12788 not be determined (that is, <code>schema_version()</code> returned
12789 0), then a subsequent call will re-query the table. While it is
12790 probably a bad idea to modify the database schema while the
12791 application is running (other than via the <code>schema_catalog</code>
12792 API, as discussed below), if for some reason you need ODB to re-query
12793 the version, then you can manually set it to 0 using the
12794 <code>schema_version_migration()</code> modifier.</p>
12795
12796 <p>It is also possible to change the name of the table that stores
12797 the schema version using the <code>--schema-version-table</code>
12798 option. You will also need to specify this alternative name on
12799 the <code>database</code> instance using the <code>schema_version_table()</code>
12800 modifier. The first version specifies the default table that is
12801 used for all the schema names. The second version specifies the
12802 table for a specific schema. The table name should be
12803 database-quoted, if necessary.</p>
12804
12805 <p>If we are generating our schema migrations as standalone SQL files,
12806 then the migration workflow could look like this:</p>
12807
12808 <ol>
12809 <li>The database administrator determines the current database version.
12810 If migration is required, then for each migration step (that
12811 is, from one version to the next), he performs the following:</li>
12812
12813 <li>Execute the pre-migration file.</li>
12814
12815 <li>Execute our application (or a separate migration program)
12816 to perform data migration (discussed later). Our application
12817 can determine that is is being executed in the "migration mode"
12818 by calling <code>schema_migration()</code> and then which
12819 migration code to run by calling <code>schema_version()</code>.</li>
12820
12821 <li>Execute the post-migration file.</li>
12822 </ol>
12823
12824 <p>These steps become more integrated and automatic if we embed the
12825 schema creation and migration code into the generated C++ code.
12826 Now we can perform schema creation, schema migration, and data
12827 migration as well as determine when each step is necessary
12828 programmatically from within the application.</p>
12829
12830 <p>Schema evolution support adds the following extra functions to
12831 the <code>odb::schema_catalog</code> class, which we first discussed
12832 in <a href="#3.4">Section 3.4, "Database"</a>.</p>
12833
12834 <pre class="cxx">
12835 namespace odb
12836 {
12837 class schema_catalog
12838 {
12839 public:
12840 ...
12841
12842
12843 // Schema migration.
12844 //
12845 static void
12846 migrate_schema_pre (database&amp;,
12847 schema_version,
12848 const std::string&amp; name = "");
12849
12850 static void
12851 migrate_schema_post (database&amp;,
12852 schema_version,
12853 const std::string&amp; name = "");
12854
12855 static void
12856 migrate_schema (database&amp;,
12857 schema_version,
12858 const std::string&amp; name = "");
12859
12860 // Data migration.
12861 //
12862 // Discussed in the next section.
12863
12864
12865 // Combined schema and data migration.
12866 //
12867 static void
12868 migrate (database&amp;,
12869 schema_version = 0,
12870 const std::string&amp; name = "");
12871
12872 // Schema version information.
12873 //
12874 static schema_version
12875 base_version (const database&amp;,
12876 const std::string&amp; name = "");
12877
12878 static schema_version
12879 base_version (database_id,
12880 const std::string&amp; name = "");
12881
12882 static schema_version
12883 current_version (const database&amp;,
12884 const std::string&amp; name = "");
12885
12886 static schema_version
12887 current_version (database_id,
12888 const std::string&amp; name = "");
12889
12890 static schema_version
12891 next_version (const database&amp;,
12892 schema_version = 0,
12893 const std::string&amp; name = "");
12894
12895 static schema_version
12896 next_version (database_id,
12897 schema_version,
12898 const std::string&amp; name = "");
12899 };
12900 }
12901 </pre>
12902
12903 <p>The <code>migrate_schema_pre()</code> and
12904 <code>migrate_schema_post()</code> static functions perform
12905 a single stage (that is, pre or post) of a single migration
12906 step (that is, from one version to the next). The <code>version</code>
12907 argument specifies the version we are migrating to. For
12908 instance, in our <code>person</code> example, if we know that
12909 the database version is <code>1</code> and the next version
12910 is <code>2</code>, then we can execute code like this:</p>
12911
12912 <pre class="cxx">
12913 transaction t (db.begin ());
12914
12915 schema_catalog::migrate_schema_pre (db, 2);
12916
12917 // Data migration goes here.
12918
12919 schema_catalog::migrate_schema_post (db, 2);
12920
12921 t.commit ();
12922 </pre>
12923
12924 <p>If you don't have any data migration code to run, then you can
12925 perform both stages with a single call using the
12926 <code>migrate_schema()</code> static function.</p>
12927
12928 <p>The <code>migrate()</code> static function perform both schema
12929 and data migration (we discuss data migration in the next section).
12930 It can also perform several migration steps at once. If we don't
12931 specify its target version, then it will migrate (if necessary)
12932 all the way to the current model version. As an extra convenience,
12933 <code>migrate()</code> will also create the database schema if
12934 none exists. As a result, if we don't have any data migration
12935 code or we have registered it with <code>schema_catalog</code> (as
12936 discussed later), then the database schema creation and migration,
12937 whichever is necessary, if at all, can be performed with a single
12938 function call:</p>
12939
12940 <pre class="cxx">
12941 transaction t (db.begin ());
12942 schema_catalog::migrate (db);
12943 t.commit ();
12944 </pre>
12945
12946 <p>Note also that <code>schema_catalog</code> is integrated with the
12947 <code>odb::database</code> schema version API. In particular,
12948 <code>schema_catalog</code> functions will query and synchronize
12949 the schema version on the <code>database</code> instance if and
12950 when required.</p>
12951
12952 <p>The <code>schema_catalog</code> class also allows you to iterate
12953 over known versions (remember, there could be "gaps" in version
12954 numbers) with the <code>base_version()</code>,
12955 <code>current_version()</code> and <code>next_version()</code>
12956 static functions. The <code>base_version()</code> and
12957 <code>current_version()</code> functions return the base and
12958 current object model versions, respectively. That is, the
12959 lowest version from which we can migrate and the version that
12960 we ultimately want to migrate to. The <code>next_version()</code>
12961 function returns the next known version. If the passed version is
12962 greater or equal to the current version, then this function
12963 will return the current version plus one (that is, one past
12964 current). If we don't specify the version, then
12965 <code>next_version()</code> will use the current database version
12966 as the starting point. Note also that the schema version information
12967 provided by these functions is only available if we embed the schema
12968 migration code into the generated C++ code. For standalone SQL file
12969 migrations this information is normally not needed since the migration
12970 process is directed by an external entity, such as a database
12971 administrator or a script.</p>
12972
12973 <p>Most <code>schema_catalog</code> functions presented above also
12974 accept the optional schema name argument. If the passed schema
12975 name is not found, then the <code>odb::unknown_schema</code> exception
12976 is thrown. Similarly, functions that accept the schema version
12977 argument will throw the <code>odb::unknown_schema_version</code> exception
12978 if the passed version is invalid. Refer to <a href="#3.14">Section
12979 3.14, "ODB Exceptions"</a> for more information on these exceptions.</p>
12980
12981 <p>To illustrate how all these parts fit together, consider the
12982 following more realistic database schema management example.
12983 Here we want to handle the schema creation in a special way
12984 and perform each migration step in its own transaction.</p>
12985
12986 <pre class="cxx">
12987 schema_version v (db.schema_version ());
12988 schema_version bv (schema_catalog::base_version (db));
12989 schema_version cv (schema_catalog::current_version (db));
12990
12991 if (v == 0)
12992 {
12993 // No schema in the database. Create the schema and
12994 // initialize the database.
12995 //
12996 transaction t (db.begin ());
12997 schema_catalog::create_schema (db);
12998
12999 // Populate the database with initial data, if any.
13000
13001 t.commit ();
13002 }
13003 else if (v &lt; cv)
13004 {
13005 // Old schema (and data) in the database, migrate them.
13006 //
13007
13008 if (v &lt; bv)
13009 {
13010 // Error: migration from this version is no longer supported.
13011 }
13012
13013 for (v = schema_catalog::next_version (db, v);
13014 v &lt;= cv;
13015 v = schema_catalog::next_version (db, v))
13016 {
13017 transaction t (db.begin ());
13018 schema_catalog::migrate_schema_pre (db, v);
13019
13020 // Data migration goes here.
13021
13022 schema_catalog::migrate_schema_post (db, v);
13023 t.commit ();
13024 }
13025 }
13026 else if (v > cv)
13027 {
13028 // Error: old application trying to access new database.
13029 }
13030 </pre>
13031
13032 <h2><a name="13.3">13.3 Data Migration</a></h2>
13033
13034 <p>In quite a few cases specifying the default value for new data
13035 members will be all that's required to handle the existing objects.
13036 For example, the natural default value for the new middle name
13037 that we have added is an empty string. And we can handle
13038 this case with the <code>db&nbsp;default</code> pragma and without
13039 any extra C++ code:</p>
13040
13041 <pre class="cxx">
13042 #pragma db model version(1, 2)
13043
13044 #pragma db object
13045 class person
13046 {
13047 ...
13048
13049
13050 #pragma db default("")
13051 std::string middle_;
13052 };
13053 </pre>
13054
13055 <p>However, there will be situations where we would need to perform
13056 more elaborate data migrations, that is, convert old data to the
13057 new format. As an example, suppose we want to add gender to our
13058 <code>person</code> class. And, instead of leaving it unassigned
13059 for all the existing objects, we will try to guess it from the
13060 first name. This is not particularly accurate but it could be
13061 sufficient for our hypothetical application:</p>
13062
13063 <pre class="cxx">
13064 #pragma db model version(1, 3)
13065
13066 enum gender {male, female};
13067
13068 #pragma db object
13069 class person
13070 {
13071 ...
13072
13073 gender gender_;
13074 };
13075 </pre>
13076
13077 <p>As we have discussed earlier, there are two ways to perform data
13078 migration: immediate and gradual. To recap, with immediate
13079 migration we migrate all the existing objects at once, normally
13080 after the schema pre-migration statements but before the
13081 post-migration statements. With gradual migration, we make sure
13082 the new object model can accommodate both old and new data and
13083 gradually migrate existing objects as the application runs and
13084 the opportunities to do so arise, for example, an object is
13085 updated.</p>
13086
13087 <p>There is also another option for data migration that is not
13088 discussed further in this section. Instead of using our C++
13089 object model we could execute ad-hoc SQL statements that
13090 perform the necessary conversions and migrations directly
13091 on the database server. While in certain cases this can be
13092 a better option from the performance point of view, this
13093 approach is often limited in terms of the migration logic
13094 that we can handle.</p>
13095
13096 <h2><a name="13.3.1">13.3.1 Immediate Data Migration</a></h2>
13097
13098 <p>Let's first see how we can implement an immediate migration for the
13099 new <code>gender_</code> data member we have added above. If we
13100 are using standalone SQL files for migration, then we could add
13101 code along these lines somewhere early in <code>main()</code>,
13102 before the main application logic:</p>
13103
13104 <pre class="cxx">
13105 int
13106 main ()
13107 {
13108 ...
13109
13110 odb::database&amp; db = ...
13111
13112 // Migrate data if necessary.
13113 //
13114 if (db.schema_migration ())
13115 {
13116 switch (db.schema_version ())
13117 {
13118 case 3:
13119 {
13120 // Assign gender to all the existing objects.
13121 //
13122 transaction t (db.begin ());
13123
13124 for (person&amp; p: db.query&lt;person> ())
13125 {
13126 p.gender (guess_gender (p.first ()));
13127 db.update (p);
13128 }
13129
13130 t.commit ();
13131 break;
13132 }
13133 }
13134 }
13135
13136 ...
13137 }
13138 </pre>
13139
13140 <p>If you have a large number of objects to migrate, it may also be
13141 a good idea, from the performance point of view, to break one big
13142 transaction that we now have into multiple smaller transactions
13143 (<a href="#3.5">Section 3.5, "Transactions"</a>). For example:</p>
13144
13145 <pre class="cxx">
13146 case 3:
13147 {
13148 transaction t (db.begin ());
13149
13150 size_t n (0);
13151 for (person&amp; p: db.query&lt;person> ())
13152 {
13153 p.gender (guess_gender (p.first ()));
13154 db.update (p);
13155
13156 // Commit the current transaction and start a new one after
13157 // every 100 updates.
13158 //
13159 if (n++ % 100 == 0)
13160 {
13161 t.commit ();
13162 t.reset (db.begin ());
13163 }
13164 }
13165
13166 t.commit ();
13167 break;
13168 }
13169 </pre>
13170
13171 <p>While it looks straightforward enough, as we add more migration
13172 snippets, this approach can quickly become unmaintainable. Instead
13173 of having all the migrations in a single function and determining
13174 when to run each piece ourselves, we can package each migration into
13175 a separate function, register it with the <code>schema_catalog</code>
13176 class, and let ODB figure out when to run which migration functions.
13177 To support this functionality, <code>schema_catalog</code> provides
13178 the following data migration API:</p>
13179
13180 <pre class="cxx">
13181 namespace odb
13182 {
13183 class schema_catalog
13184 {
13185 public:
13186 ...
13187
13188 // Data migration.
13189 //
13190 static std::size_t
13191 migrate_data (database&amp;,
13192 schema_version = 0,
13193 const std::string&amp; name = "");
13194
13195 typedef void data_migration_function_type (database&amp;);
13196
13197 // Common (for all the databases) data migration, C++98/03 version:
13198 //
13199 template &lt;schema_version v, schema_version base>
13200 static void
13201 data_migration_function (data_migration_function_type*,
13202 const std::string&amp; name = "");
13203
13204 // Common (for all the databases) data migration, C++11 version:
13205 //
13206 template &lt;schema_version v, schema_version base>
13207 static void
13208 data_migration_function (std::function&lt;data_migration_function_type>,
13209 const std::string&amp; name = "");
13210
13211 // Database-specific data migration, C++98/03 version:
13212 //
13213 template &lt;schema_version v, schema_version base>
13214 static void
13215 data_migration_function (database&amp;,
13216 data_migration_function_type*,
13217 const std::string&amp; name = "");
13218
13219 template &lt;schema_version v, schema_version base>
13220 static void
13221 data_migration_function (database_id,
13222 data_migration_function_type*,
13223 const std::string&amp; name = "");
13224
13225 // Database-specific data migration, C++11 version:
13226 //
13227 template &lt;schema_version v, schema_version base>
13228 static void
13229 data_migration_function (database&amp;,
13230 std::function&lt;data_migration_function_type>,
13231 const std::string&amp; name = "");
13232
13233 template &lt;schema_version v, schema_version base>
13234 static void
13235 data_migration_function (database_id,
13236 std::function&lt;data_migration_function_type>,
13237 const std::string&amp; name = "");
13238 };
13239
13240 // Static data migration function registration, C++98/03 version:
13241 //
13242 template &lt;schema_version v, schema_version base>
13243 struct data_migration_entry
13244 {
13245 data_migration_entry (data_migration_function_type*,
13246 const std::string&amp; name = "");
13247
13248 data_migration_entry (database_id,
13249 data_migration_function_type*,
13250 const std::string&amp; name = "");
13251 };
13252
13253 // Static data migration function registration, C++11 version:
13254 //
13255 template &lt;schema_version v, schema_version base>
13256 struct data_migration_entry
13257 {
13258 data_migration_entry (std::function&lt;data_migration_function_type>,
13259 const std::string&amp; name = "");
13260
13261 data_migration_entry (database_id,
13262 std::function&lt;data_migration_function_type>,
13263 const std::string&amp; name = "");
13264 };
13265 }
13266 </pre>
13267
13268 <p>The <code>migrate_data()</code> static function performs data
13269 migration for the specified version. If no version is specified,
13270 then it will use the current database version and also check
13271 whether the database is in migration, that is,
13272 <code>database::schema_migration()</code> returns <code>true</code>.
13273 As a result, all we need to do in our <code>main()</code> is call
13274 this function. It will check if migration is required and if so,
13275 call all the migration functions registered for this version. For
13276 example:</p>
13277
13278 <pre class="cxx">
13279 int
13280 main ()
13281 {
13282 ...
13283
13284 database&amp; db = ...
13285
13286 // Check if we need to migrate any data and do so
13287 // if that's the case.
13288 //
13289 schema_catalog::migrate_data (db);
13290
13291 ...
13292 }
13293 </pre>
13294
13295 <p>The <code>migrate_data()</code> function returns the number of
13296 migration functions called. You can use this value for debugging
13297 or logging.</p>
13298
13299 <p>The only other step that we need to perform is register our data
13300 migration functions with <code>schema_catalog</code>. At the
13301 lower level we can call the <code>data_migration_function()</code>
13302 static function for every migration function we have, for example,
13303 at the beginning of <code>main()</code>. For each version, data
13304 migration functions are called in the order of registration.</p>
13305
13306 <p>A more convenient approach, however, is to use the
13307 <code>data_migration_entry</code> helper class template to register the
13308 migration functions during static initialization. This way we
13309 can keep the migration function and its registration code next
13310 to each other. Here is how we can reimplement our <code>gender</code>
13311 migration code to use this mechanism:</p>
13312
13313 <pre class="cxx">
13314 static void
13315 migrate_gender (odb::database&amp; db)
13316 {
13317 transaction t (db.begin ());
13318
13319 for (person&amp; p: db.query&lt;person> ())
13320 {
13321 p.gender (guess_gender (p.first ()));
13322 db.update (p);
13323 }
13324
13325 t.commit ();
13326 }
13327
13328 static const odb::data_migration_entry&lt;3, MYAPP_BASE_VERSION>
13329 migrate_gender_entry (&amp;migrate_gender);
13330 </pre>
13331
13332 <p>The first template argument to the <code>data_migration_entry</code>
13333 class template is the version we want this data migration function
13334 to be called for. The second template argument is the base model
13335 version. This second argument is necessary to detect the situation
13336 where we no longer need this data migration function. Remember
13337 that when we move the base model version forward, migrations from
13338 any version below the new base are no longer possible. We, however,
13339 may still have migration functions registered for those lower
13340 versions. Since these functions will never be called, they are
13341 effectively dead code and it would be useful to identify and
13342 remove them. To assist with this, <code>data_migration_entry</code>
13343 (and lower lever <code>data_migration_function()</code>) will
13344 check at compile time (that is, <code>static_assert</code>) that
13345 the registration version is greater than the base model version.</p>
13346
13347 <p>In the above example we use the <code>MYAPP_BASE_VERSION</code>
13348 macro that is presumably defined in a central place, for example,
13349 <code>version.hxx</code>. This is the recommended approach since
13350 we can update the base version in a single place and have the
13351 C++ compiler automatically identify all the data migration
13352 functions that can be removed.</p>
13353
13354 <p>In C++11 we can also create a template alias so that we don't
13355 have to repeat the base model macro in every registration, for
13356 example:</p>
13357
13358 <pre class="cxx">
13359 template &lt;schema_version v>
13360 using migration_entry = odb::data_migration_entry&lt;v, MYAPP_BASE_VERSION>;
13361
13362 static const migration_entry&lt;3>
13363 migrate_gender_entry (&amp;migrate_gender);
13364 </pre>
13365
13366 <p>For cases where you need to by-pass the base version check, for
13367 example, to implement your own registration helper, ODB also
13368 provides "unsafe" versions of the <code>data_migration_function()</code>
13369 functions that take the version as a function argument rather than
13370 as a template parameter.</p>
13371
13372 <p>In C++11 we can also use lambdas as migration functions, which makes
13373 the migration code more concise:</p>
13374
13375 <pre class="cxx">
13376 static const migration_entry&lt;3>
13377 migrate_gender_entry (
13378 [] (odb::database&amp; db)
13379 {
13380 transaction t (db.begin ());
13381
13382 for (person&amp; p: db.query&lt;person> ())
13383 {
13384 p.gender (guess_gender (p.first ()));
13385 db.update (p);
13386 }
13387
13388 t.commit ();
13389 });
13390 </pre>
13391
13392 <p>If we are using embedded schema migrations, then both schema and
13393 data migration is integrated and can be performed with a single
13394 call to the <code>schema_catalog::migrate()</code> function that
13395 we discussed earlier. For example:</p>
13396
13397 <pre class="cxx">
13398 int
13399 main ()
13400 {
13401 ...
13402
13403 database&amp; db = ...
13404
13405 // Check if we need to migrate the database and do so
13406 // if that's the case.
13407 //
13408 {
13409 transaction t (db.begin ());
13410 schema_catalog::migrate (db);
13411 t.commit ();
13412 }
13413
13414 ...
13415 }
13416 </pre>
13417
13418 <p>Note, however, that in this case we call <code>migrate()</code>
13419 within a transaction (for the schema migration part) which means
13420 that our migration functions will also be called within this
13421 transaction. As a result, we will need to adjust our migration
13422 functions not to start their own transaction:</p>
13423
13424 <pre class="cxx">
13425 static void
13426 migrate_gender (odb::database&amp; db)
13427 {
13428 // Assume we are already in a transaction.
13429 //
13430 for (person&amp; p: db.query&lt;person> ())
13431 {
13432 p.gender (guess_gender (p.first ()));
13433 db.update (p);
13434 }
13435 }
13436 </pre>
13437
13438 <p>If, however, we want more granular transactions, then we can
13439 use the lower-level <code>schema_catalog</code> functions to
13440 gain more control, as we have seen at the end of the previous
13441 section. Here is the relevant part of that example with
13442 an added data migration call:</p>
13443
13444 <pre class="cxx">
13445 // Old schema (and data) in the database, migrate them.
13446 //
13447 for (v = schema_catalog::next_version (db, v);
13448 v &lt;= cv;
13449 v = schema_catalog::next_version (db, v))
13450 {
13451 transaction t (db.begin ());
13452 schema_catalog::migrate_schema_pre (db, v);
13453 schema_catalog::migrate_data (db, v);
13454 schema_catalog::migrate_schema_post (db, v);
13455 t.commit ();
13456 }
13457 </pre>
13458
13459 <h2><a name="13.3.2">13.3.2 Gradual Data Migration</a></h2>
13460
13461 <p>If the number of existing objects that require migration is large,
13462 then an all-at-once, immediate migration, while simple, may not
13463 be practical from a performance point of view. In this case,
13464 we can perform a gradual migration as the application does
13465 its normal functions.</p>
13466
13467 <p>With gradual migrations, the object model must be capable of
13468 representing data that conforms to both old and new formats at
13469 the same time since, in general, the database will contain a
13470 mixture of old and new objects. For example, in case of our
13471 <code>gender</code> data member, we need a special value that
13472 represents the "no gender assigned yet" case (an old object).
13473 We also need to assign this special value to all the existing
13474 objects during the schema pre-migration stage. One way to do
13475 this would be add a special value to our <code>gender</code>
13476 enum and then make it the default value with the
13477 <code>db&nbsp;default</code> pragma. A cleaner and easier approach,
13478 however, is to use <code>NULL</code> as a special value. We
13479 can add support for the <code>NULL</code> value semantics
13480 to any existing type by wrapping it with
13481 <code>odb::nullable</code>, <code>boost::optional</code>
13482 or similar (<a href="#7.3">Section 7.3, "Pointers and <code>NULL</code>
13483 Value Semantics"</a>). We also don't need to specify the default value
13484 explicitly since <code>NULL</code> is used automatically. Here
13485 is how we can use this approach in our <code>gender</code>
13486 example:</p>
13487
13488 <pre class="cxx">
13489 #include &lt;odb/nullable.hxx>
13490
13491 #pragma db object
13492 class person
13493 {
13494 ...
13495
13496 odb::nullable&lt;gender> gender_;
13497 };
13498 </pre>
13499
13500 <p>A variety of strategies can be employed to implement gradual
13501 migrations. For example, we can migrate the data when the object
13502 is updated as part of the normal application logic. While there
13503 is no migration cost associated with this approach (the object
13504 is updated anyway), depending on how often objects are typically
13505 updated, this strategy can take a long time to complete. An
13506 alternative strategy would be to perform an update whenever
13507 an old object is loaded. Yet another strategy is to have a
13508 separate thread that slowly migrates all the old objects as
13509 the application runs.</p>
13510
13511 <p>As an example, let us implement the first approach for our
13512 <code>gender</code> migration. While we could have added
13513 the necessary code throughout the application, from the
13514 maintenance point of view, it is best to try and localize
13515 the gradual migration logic to the persistent classes that
13516 it affects. And for this database operation callbacks
13517 (<a href="#14.1.7">Section 14.1.7, "<code>callback</code>"</a>)
13518 are a very useful mechanism. In our case, all we have to do is handle
13519 the <code>post_load</code> event where we guess the gender
13520 if it is <code>NULL</code>:</p>
13521
13522 <pre class="cxx">
13523 #include &lt;odb/core.hxx> // odb::database
13524 #include &lt;odb/callback.hxx> // odb::callback_event
13525 #include &lt;odb/nullable.hxx>
13526
13527 #pragma db object callback(migrate)
13528 class person
13529 {
13530 ...
13531
13532 void
13533 migrate (odb::callback_event e, odb::database&amp;)
13534 {
13535 if (e == odb::callback_event::post_load)
13536 {
13537 // Guess gender if not assigned.
13538 //
13539 if (gender_.null ())
13540 gender_ = guess_gender (first_);
13541 }
13542 }
13543
13544 odb::nullable&lt;gender> gender_;
13545 };
13546 </pre>
13547
13548 <p>In particular, we don't have to touch any of the accessors
13549 or modifiers or the application logic &mdash; all of them
13550 can assume that the value can never be <code>NULL</code>.
13551 And when the object is next updated, the new <code>gender</code>
13552 value will be stored automatically.</p>
13553
13554 <p>All gradual migrations normally end up with a terminating
13555 immediate migration some number of versions down the line,
13556 when the bulk of the objects has presumably been converted.
13557 This way we don't have to keep the gradual migration code
13558 around forever. Here is how we could implement a terminating
13559 migration for our example:</p>
13560
13561 <pre class="cxx">
13562 // person.hxx
13563 //
13564 #pragma db model version(1, 4)
13565
13566 #pragma db object
13567 class person
13568 {
13569 ...
13570
13571 gender gender_;
13572 };
13573
13574 // person.cxx
13575 //
13576 static void
13577 migrate_gender (odb::database&amp; db)
13578 {
13579 typedef odb::query&lt;person> query;
13580
13581 for (person&amp; p: db.query&lt;person> (query::gender.is_null ()))
13582 {
13583 p.gender (guess_gender (p.first ()));
13584 db.update (p);
13585 }
13586 }
13587
13588 static const odb::data_migration_entry&lt;4, MYAPP_BASE_VERSION>
13589 migrate_gender_entry (&amp;migrate_gender);
13590 </pre>
13591
13592 <p>A couple of points to note about this code. Firstly, we
13593 removed all the gradual migration logic (the callback)
13594 from the class and replaced it with the immediate migration
13595 function. We also removed the <code>odb::nullable</code>
13596 wrapper (and therefore disallowed the <code>NULL</code> values)
13597 since after this migration all the objects will have been
13598 converted. Finally, in the migration function, we only query
13599 the database for objects that need migration, that is, have
13600 <code>NULL</code> gender.</p>
13601
13602 <h2><a name="13.4">13.4 Soft Object Model Changes</a></h2>
13603
13604 <p>Let us consider another common kind of object model change:
13605 we delete an old member, add a new one, and need to copy
13606 the data from the old to the new, perhaps applying some
13607 conversion. For example, we may realize that in our application
13608 it is a better idea to store a person's name as a single string
13609 rather than split it into three fields. So what we would like to do
13610 is add a new data member, let's call it <code>name_</code>, convert
13611 all the existing split names, and then delete the <code>first_</code>,
13612 <code>middle_</code>, and <code>last_</code> data members.</p>
13613
13614 <p>While this sounds straightforward, there is a problem. If we
13615 delete (that is, physically remove from the source code) the
13616 old data members, then we won't be able to access the old
13617 data. The data will still be available in the database between
13618 the schema pre and post-migrations, it is just we will no longer
13619 be able to access it through our object model. And if we keep
13620 the old data members around, then the old data will remain
13621 stored in the database even after the schema post-migration.</p>
13622
13623 <p>There is also a more subtle problem that has to do with existing
13624 migrations for the previous versions. Remember, in version <code>3</code>
13625 of our <code>person</code> example we added the <code>gender_</code>
13626 data member. We also have a data migration function which guesses
13627 the gender based on the first name. Deleting the <code>first_</code>
13628 data member from our class will obviously break this code. But
13629 even adding the new <code>name_</code> data member will cause
13630 problems because when we try to update the object in order to
13631 store the new gender, ODB will try to update <code>name_</code>
13632 as well. But there is no corresponding column in the database
13633 yet. When we run this migration function, we are still several
13634 versions away from the point where the <code>name</code> column
13635 will be added.</p>
13636
13637 <p>This is a very subtle but also very important implication to
13638 understand. Unlike the main application logic, which only needs
13639 to deal with the current model version, data migration code works
13640 on databases that can be multiple versions behind the current
13641 version.</p>
13642
13643 <p>How can we resolve this problem? It appears what we need is the
13644 ability to add or delete data members starting from a specific
13645 version. In ODB this mechanism is called soft member additions
13646 and deletions. A soft-added member is only treated as persistent
13647 starting from the addition version. A soft-deleted member is
13648 persistent until the deletion version (but including the migration
13649 stage). In its essence, soft model changes allow us to maintain
13650 multiple versions of our object model all with a single set of
13651 persistent classes. Let us now see how this functionality can
13652 help implement our changes:</p>
13653
13654 <pre class="cxx">
13655 #pragma db model version(1, 4)
13656
13657 #pragma db object
13658 class person
13659 {
13660 ...
13661
13662 #pragma db id auto
13663 unsigned long id_;
13664
13665 #pragma db deleted(4)
13666 std::string first_;
13667
13668 #pragma db deleted(4)
13669 std::string middle_;
13670
13671 #pragma db deleted(4)
13672 std::string last_;
13673
13674 #pragma db added(4)
13675 std::string name_;
13676
13677 gender gender_;
13678 };
13679 </pre>
13680
13681 <p>The migration function for this change could then look like
13682 this:</p>
13683
13684 <pre class="cxx">
13685 static void
13686 migrate_name (odb::database&amp; db)
13687 {
13688 for (person&amp; p: db.query&lt;person> ())
13689 {
13690 p.name (p.first () + " " +
13691 p.middle () + (p.middle ().empty () ? "" : " ") +
13692 p.last ());
13693 db.update (p);
13694 }
13695 }
13696
13697 static const odb::data_migration_entry&lt;4, MYAPP_BASE_VERSION>
13698 migrate_name_entry (&amp;migrate_name);
13699 </pre>
13700
13701 <p>Note also that no changes are required to the gender migration
13702 function.</p>
13703
13704 <p>As you may have noticed, in the code above we assumed that the
13705 <code>person</code> class still provides public accessors for
13706 the now deleted data members. This might not be ideal since now
13707 they should not be used by the application logic. The only code
13708 that may still need to access them is the migration functions. The
13709 recommended way to resolve this is to remove the accessors/modifiers
13710 corresponding to the deleted data member, make migration functions
13711 static functions of the class being migrated, and then access
13712 the deleted data members directly. For example:</p>
13713
13714 <pre class="cxx">
13715 #pragma db model version(1, 4)
13716
13717 #pragma db object
13718 class person
13719 {
13720 ...
13721
13722 private:
13723 friend class odb::access;
13724
13725 #pragma db id auto
13726 unsigned long id_;
13727
13728 #pragma db deleted(4)
13729 std::string first_;
13730
13731 #pragma db deleted(4)
13732 std::string middle_;
13733
13734 #pragma db deleted(4)
13735 std::string last_;
13736
13737 #pragma db added(4)
13738 std::string name_;
13739
13740 gender gender_;
13741
13742 private:
13743 static void
13744 migrate_gender (odb::database&amp;);
13745
13746 static void
13747 migrate_name (odb::database&amp;);
13748 };
13749
13750 void person::
13751 migrate_gender (odb::database&amp; db)
13752 {
13753 for (person&amp; p: db.query&lt;person> ())
13754 {
13755 p.gender_ = guess_gender (p.first_);
13756 db.update (p);
13757 }
13758 }
13759
13760 static const odb::data_migration_entry&lt;3, MYAPP_BASE_VERSION>
13761 migrate_name_entry (&amp;migrate_gender);
13762
13763 void person::
13764 migrate_name (odb::database&amp; db)
13765 {
13766 for (person&amp; p: db.query&lt;person> ())
13767 {
13768 p.name_ = p.first_ + " " +
13769 p.middle_ + (p.middle_.empty () ? "" : " ") +
13770 p.last_;
13771 db.update (p);
13772 }
13773 }
13774
13775 static const odb::data_migration_entry&lt;4, MYAPP_BASE_VERSION>
13776 migrate_name_entry (&amp;migrate_name);
13777 </pre>
13778
13779 <p>Another potential issue with the soft-deletion is the requirement
13780 to keep the delete data members in the class. While they will not
13781 be initialized in the normal operation of the application (that
13782 is, not a migration), this can still be a problem if we need to
13783 minimize the memory footprint of our classes. For example, we may
13784 cache a large number of objects in memory and having three
13785 <code>std::string</code> data members can be a significant
13786 overhead.</p>
13787
13788 <p>The recommended way to resolve this issue is to place all the
13789 deleted data members into a dynamically allocated composite
13790 value type. For example:</p>
13791
13792 <pre class="cxx">
13793 #pragma db model version(1, 4)
13794
13795 #pragma db object
13796 class person
13797 {
13798 ...
13799
13800 #pragma db id auto
13801 unsigned long id_;
13802
13803 #pragma db added(4)
13804 std::string name_;
13805
13806 gender gender_;
13807
13808 #pragma db value
13809 struct deleted_data
13810 {
13811 #pragma db deleted(4)
13812 std::string first_;
13813
13814 #pragma db deleted(4)
13815 std::string middle_;
13816
13817 #pragma db deleted(4)
13818 std::string last_;
13819 };
13820
13821 #pragma db column("")
13822 std::unique_ptr&lt;deleted_data> dd_;
13823
13824 ...
13825 };
13826 </pre>
13827
13828 <p>ODB will then automatically allocate the deleted value type if
13829 any of the deleted data members are being loaded. During the normal
13830 operation, however, the pointer will stay <code>NULL</code> and
13831 therefore reduce the common case overhead to a single pointer
13832 per class. Note that we make the composite value column prefix
13833 empty (the <code>db&nbsp;column("")</code> pragma) in order to
13834 keep the same column names for the deleted data members.</p>
13835
13836 <p>Soft-added and deleted data members can be used in objects,
13837 composite values, views, and container value types. We can
13838 also soft-add and delete data members of simple, composite,
13839 pointer to object, and container types. Only special data
13840 members, such as the object id and the optimistic concurrency
13841 version, cannot be soft-added or deleted.</p>
13842
13843 <p>It is also possible to soft-delete a persistent class. We
13844 can still work with the existing objects of such a class,
13845 however, no table is created in new databases for soft-deleted
13846 classes. To put it another way, a soft-delete class is like an
13847 abstract class (no table) but which can still be loaded, updated,
13848 etc. Soft-added persistent classes do not make much sense and
13849 are therefore not supported.</p>
13850
13851 <p>As an example of a soft-deleted class, suppose we want to
13852 replace our <code>person</code> class with the new
13853 <code>employee</code> object and migrate the data. Here is
13854 how we could do this:</p>
13855
13856 <pre class="cxx">
13857 #pragma db model version(1, 5)
13858
13859 #pragma db object deleted(5)
13860 class person
13861 {
13862 ...
13863 };
13864
13865 #pragma db object
13866 class employee
13867 {
13868 ...
13869
13870 #pragma db id auto
13871 unsigned long id_;
13872
13873 std::string name_;
13874 gender gender_;
13875
13876 static void
13877 migrate_person (odb::database&amp;);
13878 };
13879
13880 void employee::
13881 migrate_person (odb::database&amp; db)
13882 {
13883 for (person&amp; p: db.query&lt;person> ())
13884 {
13885 employee e (p.name (), p.gender ());
13886 db.persist (e);
13887 }
13888 }
13889
13890 static const odb::data_migration_entry&lt;5, MYAPP_BASE_VERSION>
13891 migrate_person_entry (&amp;migrate_person);
13892 </pre>
13893
13894 <p>As we have seen above, hard member additions and deletions can
13895 (and most likely will) break existing data migration code. Why,
13896 then, not treat all the changes, or at least additions, as soft?
13897 ODB requires you to explicitly request this semantics because
13898 support for soft-added and deleted data members incurs runtime
13899 overhead. And there can be plenty of cases where there is no
13900 existing data migration and therefore hard additions and deletions
13901 are sufficient.</p>
13902
13903 <p>In some cases a hard addition or deletion will result in a
13904 compile-time error. For example, one of the data migration
13905 functions may reference the data member we just deleted. In
13906 many cases, however, such errors can only be detected at
13907 runtime, and, worse yet, only when the migration function
13908 is executed. For example, we may hard-add a new data member
13909 that an existing migration function will try to indirectly
13910 store in the database as part of an object update. As a result,
13911 it is highly recommended that you always test your application
13912 with the database that starts at the base version so that every
13913 data migration function is called and therefore ensured to
13914 still work correctly.</p>
13915
13916 <p>To help with this problem you can also instruct ODB to warn
13917 you about any hard additions or deletions with the
13918 <code>--warn-hard-add</code>, <code>--warn-hard-delete</code>,
13919 and <code>--warn-hard</code> command line options. ODB will
13920 only warn you about hard changes in the current version and
13921 only for as long as it is open, which makes this mechanism
13922 fairly usable.</p>
13923
13924 <p>You may also be wondering why we have to specify the addition
13925 and deletion versions explicitly. It may seem like the ODB compiler
13926 should be able to figure this out automatically. While it is
13927 theoretically possible, to achieve this, ODB would have to also
13928 maintain a separate changelog of the C++ object model in
13929 addition to the database schema changelog it already maintains.
13930 While being a lot more complex, such an additional changelog
13931 would also complicate the workflow significantly. In this light,
13932 maintaining this change information as part of the original
13933 source files appears to be a cleaner and simpler approach.</p>
13934
13935 <p>As we discussed before, when we move the base model version
13936 forward we essentially drop support for migrations from
13937 versions before the new base. As a result, it is no longer
13938 necessary to maintain the soft semantics of additions and
13939 deletions up to and including the new base version. ODB
13940 will issue diagnostics for all such members and classes.
13941 For soft deletions we can simply remove the data member or
13942 class entirely. For soft additions we only need to remove the
13943 <code>db&nbsp;added</code> pragma.</p>
13944
13945 <h2><a name="13.4.1">13.4.1 Reuse Inheritance Changes</a></h2>
13946
13947 <p>Besides adding and deleting data members, another way to alter
13948 the object's table is using reuse-style inheritance. If we add
13949 a new reuse base, then, from the database schema point of view,
13950 this is equivalent to adding all its columns to the derived
13951 object's table. Similarly, deleting reuse inheritance results in
13952 all the base's columns being deleted from the derived's table.</p>
13953
13954 <p>In the future ODB may provide direct support for soft addition
13955 and deletion of inheritance. Currently, however, this semantics
13956 can be emulated with soft-added and deleted data members. The
13957 following table describes the most common scenarios depending
13958 on where columns are added or deleted, that is, base table,
13959 derived table, or both.</p>
13960
13961 <!-- border="1" is necessary for html2ps -->
13962 <table class="scenarios" border="1">
13963 <tr>
13964 <th>DELETE</th>
13965 <th style="width: 40%">HARD</th>
13966 <th style="width: 40%">SOFT</th>
13967 </tr>
13968
13969 <tr>
13970 <td>In both (delete inheritance and base)</td>
13971 <td>Delete inheritance and base. Move object id to derived.</td>
13972 <td>Soft-delete base. Mark all data members (except id) in
13973 base as soft-deleted.</td>
13974 </tr>
13975
13976 <tr>
13977 <td>In base only (delete base)</td>
13978 <td>Option 1: mark base as abstract.<br/><br/>
13979 Option 2: move all the base member to derived, delete base.</td>
13980 <td>Soft-delete base.</td>
13981 </tr>
13982
13983 <tr>
13984 <td>In derived only (delete inheritance)</td>
13985 <td>Delete inheritance, add object id to derived.</td>
13986 <td>Option 1: copy base to a new soft-deleted base, inherit
13987 from it instead. Mark all the data members (expect id) in
13988 this new base as soft-deleted. Note: we add the new base
13989 as soft-deleted to get notified when we can remove it.<br/><br/>
13990 Option 2: Copy all the data members from base to derived
13991 and mark them as soft-deleted in derived.</td>
13992 </tr>
13993 </table>
13994
13995
13996 <table class="scenarios" border="1">
13997 <tr>
13998 <th>ADD</th>
13999 <th style="width: 40%">HARD</th>
14000 <th style="width: 40%">SOFT</th>
14001 </tr>
14002
14003 <tr>
14004 <td>In both (add new base and inheritance)</td>
14005 <td>Add new base and inheritance. Potentially move object id
14006 member from derived to base.</td>
14007 <td>Add new base and mark all its data members as soft-added.
14008 Add inheritance. Move object id from derived to base.</td>
14009 </tr>
14010
14011 <tr>
14012 <td>In base only (refactor existing data to new base)</td>
14013 <td>Add new base and move data members from derived to base.
14014 Note: in most cases the new base will be made abstract
14015 which make this scenario non-schema changing.</td>
14016 <td>The same as HARD.</td>
14017 </tr>
14018
14019 <tr>
14020 <td>In derived only (add inheritance to existing base)</td>
14021 <td>Add inheritance, delete object id in derived.</td>
14022 <td>Copy existing base to a new abstract base and inherit
14023 from it. Mark all the database members in the new base
14024 as soft-added (except object id). When notified by the
14025 ODB compiler that the soft addition of the data members
14026 is no longer necessary, delete the copy and inherit from
14027 the original base.</td>
14028 </tr>
14029 </table>
14030
14031 <h2><a name="13.4.2">13.4.2 Polymorphism Inheritance Changes</a></h2>
14032
14033 <p>Unlike reuse inheritance, adding or deleting a polymorphic base
14034 does not result in the base's data members being added or deleted
14035 from the derived object's table because each class in a polymorphic
14036 hierarchy is stored in a separate table. There are, however, other
14037 complications due to the presence of special columns (discriminator
14038 in the root table and object id links in derived tables) which makes
14039 altering the hierarchy structure difficult to handle automatically.
14040 Adding or deleting (including soft-deleting) of leaf classes (or
14041 leaf sub-hierarchies) in a polymorphic hierarchy is fully supported.
14042 Any more complex changes, such as adding or deleting the root or
14043 an intermediate base or getting an existing class into or out of
14044 a polymorphic hierarchy can be handled by creating a new leaf class
14045 (or leaf sub-hierarchy), soft-deleting the old class, and migrating
14046 the data.</p>
14047
14048 <!-- CHAPTER -->
14049
14050
14051 <hr class="page-break"/>
14052 <h1><a name="14">14 ODB Pragma Language</a></h1>
14053
14054 <p>As we have already seen in previous chapters, ODB uses a pragma-based
14055 language to capture database-specific information about C++ types.
14056 This chapter describes the ODB pragma language in more detail. It
14057 can be read together with other chapters in the manual to get a
14058 sense of what kind of configurations and mapping fine-tuning are
14059 possible. You can also use this chapter as a reference at a later
14060 stage.</p>
14061
14062 <p>An ODB pragma has the following syntax:</p>
14063
14064 <p><code>#pragma db <i>qualifier</i> [<i>specifier</i> <i>specifier</i> ...]</code></p>
14065
14066 <p>The <em>qualifier</em> tells the ODB compiler what kind of C++ construct
14067 this pragma describes. Valid qualifiers are <code>object</code>,
14068 <code>view</code>, <code>value</code>, <code>member</code>,
14069 <code>namespace</code>, <code>model</code>, <code>index</code>, and
14070 <code>map</code>.
14071 A pragma with the <code>object</code> qualifier describes a persistent
14072 object type. It tells the ODB compiler that the C++ class it describes
14073 is a persistent class. Similarly, pragmas with the <code>view</code>
14074 qualifier describe view types, the <code>value</code> qualifier
14075 describes value types and the <code>member</code> qualifier is used
14076 to describe data members of persistent object, view, and value types.
14077 The <code>namespace</code> qualifier is used to describe common
14078 properties of objects, views, and value types that belong to
14079 a C++ namespace while the <code>model</code> qualifier describes
14080 the whole C++ object model. The <code>index</code> qualifier defines
14081 a database index. And, finally, the <code>map</code> qualifier
14082 describes a mapping between additional database types and types
14083 for which ODB provides built-in support.</p>
14084
14085 <p>The <em>specifier</em> informs the ODB compiler about a particular
14086 database-related property of the C++ declaration. For example, the
14087 <code>id</code> member specifier tells the ODB compiler that this
14088 member contains this object's identifier. Below is the declaration
14089 of the <code>person</code> class that shows how we can use ODB
14090 pragmas:</p>
14091
14092 <pre class="cxx">
14093 #pragma db object
14094 class person
14095 {
14096 ...
14097 private:
14098 #pragma db member id
14099 unsigned long id_;
14100 ...
14101 };
14102 </pre>
14103
14104 <p>In the above example we don't explicitly specify which C++ class or
14105 data member the pragma belongs to. Rather, the pragma applies to
14106 a C++ declaration that immediately follows the pragma. Such pragmas
14107 are called <em>positioned pragmas</em>. In positioned pragmas that
14108 apply to data members, the <code>member</code> qualifier can be
14109 omitted for brevity, for example:</p>
14110
14111 <pre class="cxx">
14112 #pragma db id
14113 unsigned long id_;
14114 </pre>
14115
14116 <p>Note also that if the C++ declaration immediately following a
14117 position pragma is incompatible with the pragma qualifier, an
14118 error will be issued. For example:</p>
14119
14120 <pre class="cxx">
14121 #pragma db object // Error: expected class instead of data member.
14122 unsigned long id_;
14123 </pre>
14124
14125 <p>While keeping the C++ declarations and database declarations close
14126 together eases maintenance and increases readability, we can also
14127 place them in different parts of the same header file or even
14128 factor them to a separate file. To achieve this we use the so called
14129 <em>named pragmas</em>. Unlike positioned pragmas, named pragmas
14130 explicitly specify the C++ declaration to which they apply by
14131 adding the declaration name after the pragma qualifier. For example:</p>
14132
14133 <pre class="cxx">
14134 class person
14135 {
14136 ...
14137 private:
14138 unsigned long id_;
14139 ...
14140 };
14141
14142 #pragma db object(person)
14143 #pragma db member(person::id_) id
14144 </pre>
14145
14146 <p>Note that in the named pragmas for data members the <code>member</code>
14147 qualifier is no longer optional. The C++ declaration name in the
14148 named pragmas is resolved using the standard C++ name resolution
14149 rules, for example:</p>
14150
14151 <pre class="cxx">
14152 namespace db
14153 {
14154 class person
14155 {
14156 ...
14157 private:
14158 unsigned long id_;
14159 ...
14160 };
14161 }
14162
14163 namespace db
14164 {
14165 #pragma db object(person) // Resolves db::person.
14166 }
14167
14168 #pragma db member(db::person::id_) id
14169 </pre>
14170
14171 <p>As another example, the following code fragment shows how to use the
14172 named value type pragma to map a C++ type to a native database type:</p>
14173
14174 <pre class="cxx">
14175 #pragma db value(bool) type("INT")
14176
14177 #pragma db object
14178 class person
14179 {
14180 ...
14181 private:
14182 bool married_; // Mapped to INT NOT NULL database type.
14183 ...
14184 };
14185 </pre>
14186
14187 <p>If we would like to factor the ODB pragmas into a separate file,
14188 we can include this file into the original header file (the one
14189 that defines the persistent types) using the <code>#include</code>
14190 directive, for example:</p>
14191
14192 <pre class="cxx">
14193 // person.hxx
14194
14195 class person
14196 {
14197 ...
14198 };
14199
14200 #ifdef ODB_COMPILER
14201 # include "person-pragmas.hxx"
14202 #endif
14203 </pre>
14204
14205 <p>Alternatively, instead of using the <code>#include</code> directive,
14206 we can use the <code>--odb-epilogue</code> option to make the pragmas
14207 known to the ODB compiler when compiling the original header file,
14208 for example:</p>
14209
14210 <pre class="terminal">
14211 --odb-epilogue '#include "person-pragmas.hxx"'
14212 </pre>
14213
14214 <p>The following sections cover the specifiers applicable to all the
14215 qualifiers mentioned above.</p>
14216
14217 <p>The C++ header file that defines our persistent classes and
14218 normally contains one or more ODB pragmas is compiled by both
14219 the ODB compiler to generate the database support code and
14220 the C++ compiler to build the application. Some C++ compilers
14221 issue warnings about pragmas that they do not recognize. There
14222 are several ways to deal with this problem which are covered
14223 at the end of this chapter in <a href="#14.9">Section 14.9,
14224 "C++ Compiler Warnings"</a>.</p>
14225
14226 <h2><a name="14.1">14.1 Object Type Pragmas</a></h2>
14227
14228 <p>A pragma with the <code>object</code> qualifier declares a C++ class
14229 as a persistent object type. The qualifier can be optionally followed,
14230 in any order, by one or more specifiers summarized in the table below:</p>
14231
14232 <!-- border="1" is necessary for html2ps -->
14233 <table class="specifiers" border="1">
14234 <tr>
14235 <th>Specifier</th>
14236 <th>Summary</th>
14237 <th>Section</th>
14238 </tr>
14239
14240 <tr>
14241 <td><code>table</code></td>
14242 <td>table name for a persistent class</td>
14243 <td><a href="#14.1.1">14.1.1</a></td>
14244 </tr>
14245
14246 <tr>
14247 <td><code>pointer</code></td>
14248 <td>pointer type for a persistent class</td>
14249 <td><a href="#14.1.2">14.1.2</a></td>
14250 </tr>
14251
14252 <tr>
14253 <td><code>abstract</code></td>
14254 <td>persistent class is abstract</td>
14255 <td><a href="#14.1.3">14.1.3</a></td>
14256 </tr>
14257
14258 <tr>
14259 <td><code>readonly</code></td>
14260 <td>persistent class is read-only</td>
14261 <td><a href="#14.1.4">14.1.4</a></td>
14262 </tr>
14263
14264 <tr>
14265 <td><code>optimistic</code></td>
14266 <td>persistent class with the optimistic concurrency model</td>
14267 <td><a href="#14.1.5">14.1.5</a></td>
14268 </tr>
14269
14270 <tr>
14271 <td><code>no_id</code></td>
14272 <td>persistent class has no object id</td>
14273 <td><a href="#14.1.6">14.1.6</a></td>
14274 </tr>
14275
14276 <tr>
14277 <td><code>callback</code></td>
14278 <td>database operations callback</td>
14279 <td><a href="#14.1.7">14.1.7</a></td>
14280 </tr>
14281
14282 <tr>
14283 <td><code>schema</code></td>
14284 <td>database schema for a persistent class</td>
14285 <td><a href="#14.1.8">14.1.8</a></td>
14286 </tr>
14287
14288 <tr>
14289 <td><code>polymorphic</code></td>
14290 <td>persistent class is polymorphic</td>
14291 <td><a href="#14.1.9">14.1.9</a></td>
14292 </tr>
14293
14294 <tr>
14295 <td><code>session</code></td>
14296 <td>enable/disable session support for a persistent class</td>
14297 <td><a href="#14.1.10">14.1.10</a></td>
14298 </tr>
14299
14300 <tr>
14301 <td><code>definition</code></td>
14302 <td>definition location for a persistent class</td>
14303 <td><a href="#14.1.11">14.1.11</a></td>
14304 </tr>
14305
14306 <tr>
14307 <td><code>transient</code></td>
14308 <td>all non-virtual data members in a persistent class are transient</td>
14309 <td><a href="#14.1.12">14.1.12</a></td>
14310 </tr>
14311
14312 <tr>
14313 <td><code>sectionable</code></td>
14314 <td>support addition of new sections in derived classes</td>
14315 <td><a href="#14.1.13">14.1.13</a></td>
14316 </tr>
14317
14318 <tr>
14319 <td><code>deleted</code></td>
14320 <td>persistent class is soft-deleted</td>
14321 <td><a href="#14.1.14">14.1.14</a></td>
14322 </tr>
14323
14324 <tr>
14325 <td><code>bulk</code></td>
14326 <td>enable bulk operations for a persistent class</td>
14327 <td><a href="#14.1.15">14.1.15</a></td>
14328 </tr>
14329
14330 </table>
14331
14332 <h3><a name="14.1.1">14.1.1 <code>table</code></a></h3>
14333
14334 <p>The <code>table</code> specifier specifies the table name that should
14335 be used to store objects of the persistent class in a relational
14336 database. For example:</p>
14337
14338 <pre class="cxx">
14339 #pragma db object table("people")
14340 class person
14341 {
14342 ...
14343 };
14344 </pre>
14345
14346 <p>If the table name is not specified, the class name is used as the
14347 table name. The table name can be qualified with a database
14348 schema, for example:</p>
14349
14350 <pre class="cxx">
14351 #pragma db object table("census.people")
14352 class person
14353 {
14354 ...
14355 };
14356 </pre>
14357
14358 <p>For more information on database schemas and the format of the
14359 qualified names, refer to <a href="#14.1.8">Section 14.1.8,
14360 "<code>schema</code>"</a>.</p>
14361
14362 <h3><a name="14.1.2">14.1.2 <code>pointer</code></a></h3>
14363
14364 <p>The <code>pointer</code> specifier specifies the object pointer type
14365 for the persistent class. The object pointer type is used to return,
14366 pass, and cache dynamically allocated instances of a persistent
14367 class. For example:</p>
14368
14369 <pre class="cxx">
14370 #pragma db object pointer(std::tr1::shared_ptr&lt;person>)
14371 class person
14372 {
14373 ...
14374 };
14375 </pre>
14376
14377 <p>There are several ways to specify an object pointer with the
14378 <code>pointer</code> specifier. We can use a complete pointer
14379 type as shown in the example above. Alternatively, we can
14380 specify only the template name of a smart pointer in which
14381 case the ODB compiler will automatically append the class
14382 name as a template argument. The following example is therefore
14383 equivalent to the one above:</p>
14384
14385 <pre class="cxx">
14386 #pragma db object pointer(std::tr1::shared_ptr)
14387 class person
14388 {
14389 ...
14390 };
14391 </pre>
14392
14393 <p>If you would like to use the raw pointer as an object pointer,
14394 you can use <code>*</code> as a shortcut:</p>
14395
14396 <pre class="cxx">
14397 #pragma db object pointer(*) // Same as pointer(person*)
14398 class person
14399 {
14400 ...
14401 };
14402 </pre>
14403
14404 <p>If a pointer type is not explicitly specified, the default pointer,
14405 specified at the namespace level (<a href="#14.5.1">Section 14.5.1,
14406 "<code>pointer</code>"</a>) or with the <code>--default-pointer</code>
14407 ODB compiler option, is used. If neither of these two mechanisms is
14408 used to specify the pointer, then the raw pointer is used by default.</p>
14409
14410 <p>For a more detailed discussion of object pointers, refer to
14411 <a href="#3.3">Section 3.3, "Object and View Pointers"</a>.</p>
14412
14413 <h3><a name="14.1.3">14.1.3 <code>abstract</code></a></h3>
14414
14415 <p>The <code>abstract</code> specifier specifies that the persistent class
14416 is abstract. An instance of an abstract class cannot be stored in
14417 the database and is normally used as a base for other persistent
14418 classes. For example:</p>
14419
14420 <pre class="cxx">
14421 #pragma db object abstract
14422 class person
14423 {
14424 ...
14425 };
14426
14427 #pragma db object
14428 class employee: public person
14429 {
14430 ...
14431 };
14432
14433 #pragma db object
14434 class contractor: public person
14435 {
14436 ...
14437 };
14438 </pre>
14439
14440 <p>Persistent classes with pure virtual functions are automatically
14441 treated as abstract by the ODB compiler. For a more detailed
14442 discussion of persistent class inheritance, refer to
14443 <a href="#8">Chapter 8, "Inheritance"</a>.</p>
14444
14445 <h3><a name="14.1.4">14.1.4 <code>readonly</code></a></h3>
14446
14447 <p>The <code>readonly</code> specifier specifies that the persistent class
14448 is read-only. The database state of read-only objects cannot be
14449 updated. In particular, this means that you cannot call the
14450 <code>database::update()</code> function (<a href="#3.10">Section 3.10,
14451 "Updating Persistent Objects"</a>) for such objects. For example:</p>
14452
14453 <pre class="cxx">
14454 #pragma db object readonly
14455 class person
14456 {
14457 ...
14458 };
14459 </pre>
14460
14461 <p>Read-only and read-write objects can derive from each other without
14462 any restrictions. When a read-only object derives from a read-write
14463 object, the resulting whole object is read-only, including the part
14464 corresponding to the read-write base. On the other hand, when a
14465 read-write object derives from a read-only object, all the data
14466 members that correspond to the read-only base are treated as
14467 read-only while the rest is treated as read-write.</p>
14468
14469 <p>Note that it is also possible to declare individual data members
14470 (<a href="#14.4.12">Section 14.4.12, "<code>readonly</code>"</a>)
14471 as well as composite value types (<a href="#14.3.6">Section 14.3.6,
14472 "<code>readonly</code>"</a>) as read-only.</p>
14473
14474 <h3><a name="14.1.5">14.1.5 <code>optimistic</code></a></h3>
14475
14476 <p>The <code>optimistic</code> specifier specifies that the persistent class
14477 has the optimistic concurrency model. A class with the optimistic
14478 concurrency model must also specify the data member that is used to
14479 store the object version using the <code>version</code> pragma
14480 (<a href="#14.4.16">Section 14.4.16, "<code>version</code>"</a>).
14481 For example:</p>
14482
14483 <pre class="cxx">
14484 #pragma db object optimistic
14485 class person
14486 {
14487 ...
14488
14489 #pragma db version
14490 unsigned long version_;
14491 };
14492 </pre>
14493
14494 <p>If a base class has the optimistic concurrency model, then all its derived
14495 classes will automatically have the optimistic concurrency model. The
14496 current implementation also requires that in any given inheritance
14497 hierarchy the object id and the version data members reside in the
14498 same class.</p>
14499
14500 <p>For a more detailed discussion of optimistic concurrency, refer to
14501 <a href="#12">Chapter 12, "Optimistic Concurrency"</a>.</p>
14502
14503 <h3><a name="14.1.6">14.1.6 <code>no_id</code></a></h3>
14504
14505 <p>The <code>no_id</code> specifier specifies that the persistent class
14506 has no object id. For example:</p>
14507
14508 <pre class="cxx">
14509 #pragma db object no_id
14510 class person
14511 {
14512 ...
14513 };
14514 </pre>
14515
14516 <p>A persistent class without an object id has limited functionality.
14517 Such a class cannot be loaded with the <code>database::load()</code>
14518 or <code>database::find()</code> functions (<a href="#3.9">Section 3.9,
14519 "Loading Persistent Objects"</a>), updated with the
14520 <code>database::update()</code> function (<a href="#3.10">Section 3.10,
14521 "Updating Persistent Objects"</a>), or deleted with the
14522 <code>database::erase()</code> function (<a href="#3.11">Section 3.11,
14523 "Deleting Persistent Objects"</a>). To load and delete
14524 objects without ids you can use the <code>database::query()</code>
14525 (<a href="#4">Chapter 4, "Querying the Database"</a>) and
14526 <code>database::erase_query()</code> (<a href="#3.11">Section 3.11,
14527 "Deleting Persistent Objects"</a>) functions, respectively.
14528 There is no way to update such objects except by using native SQL
14529 statements (<a href="#3.12">Section 3.12, "Executing Native SQL
14530 Statements"</a>).</p>
14531
14532 <p>Furthermore, persistent classes without object ids cannot have container
14533 data members nor can they be used in object relationships. Such objects
14534 are not entered into the session object cache
14535 (<a href="#11.1">Section 11.1, "Object Cache"</a>) either.</p>
14536
14537 <p>To declare a persistent class with an object id, use the data member
14538 <code>id</code> specifier (<a href="#14.4.1">Section 14.4.1,
14539 "<code>id</code>"</a>).</p>
14540
14541 <h3><a name="14.1.7">14.1.7 <code>callback</code></a></h3>
14542
14543 <p>The <code>callback</code> specifier specifies the persist class
14544 member function that should be called before and after a
14545 database operation is performed on an object of this class.
14546 For example:</p>
14547
14548 <pre class="cxx">
14549 #include &lt;odb/callback.hxx>
14550
14551 #pragma db object callback(init)
14552 class person
14553 {
14554 ...
14555
14556 void
14557 init (odb::callback_event, odb::database&amp;);
14558 };
14559 </pre>
14560
14561 <p>The callback function has the following signature and can be
14562 overloaded for constant objects:</p>
14563
14564 <pre class="cxx">
14565 void
14566 name (odb::callback_event, odb::database&amp;);
14567
14568 void
14569 name (odb::callback_event, odb::database&amp;) const;
14570 </pre>
14571
14572 <p>The first argument to the callback function is the event that
14573 triggered this call. The <code>odb::callback_event</code>
14574 enum-like type is defined in the <code>&lt;odb/callback.hxx></code>
14575 header file and has the following interface:</p>
14576
14577 <pre class="cxx">
14578 namespace odb
14579 {
14580 struct callback_event
14581 {
14582 enum value
14583 {
14584 pre_persist,
14585 post_persist,
14586 pre_load,
14587 post_load,
14588 pre_update,
14589 post_update,
14590 pre_erase,
14591 post_erase
14592 };
14593
14594 callback_event (value v);
14595 operator value () const;
14596 };
14597 }
14598 </pre>
14599
14600 <p>The second argument to the callback function is the database
14601 on which the operation is about to be performed or has just
14602 been performed. A callback function can be inline or virtual.</p>
14603
14604 <p>The callback function for the <code>*_persist</code>,
14605 <code>*_update</code>, and <code>*_erase</code> events is always
14606 called on the constant object reference while for the <code>*_load</code>
14607 events &mdash; always on the unrestricted reference.</p>
14608
14609 <p>If only the non-<code>const</code> version of the callback function
14610 is provided, then only the <code>*_load</code> events will be delivered.
14611 If only the <code>const</code> version is provided, then all the
14612 events will be delivered to this function. Finally, if both versions
14613 are provided, then the <code>*_load</code> events will be delivered
14614 to the non-<code>const</code> version while all others &mdash; to the
14615 <code>const</code> version. If you need to modify the object in one
14616 of the "<code>const</code>" events, then you can safely cast away
14617 <code>const</code>-ness using the <code>const_cast</code> operator if
14618 you know that none of the objects will be created const. Alternatively,
14619 if you cannot make this assumption, then you can declare the data
14620 members you wish to modify as <code>mutable</code>.</p>
14621
14622 <p>A database operations callback can be used to implement object-specific
14623 pre and post initializations, registrations, and cleanups. As an example,
14624 the following code fragment outlines an implementation of a
14625 <code>person</code> class that maintains the transient <code>age</code>
14626 data member in addition to the persistent date of birth. A callback
14627 is used to calculate the value of the former from the latter every
14628 time a <code>person</code> object is loaded from the database.</p>
14629
14630 <pre class="cxx">
14631 #include &lt;odb/core.hxx>
14632 #include &lt;odb/callback.hxx>
14633
14634 #pragma db object callback(init)
14635 class person
14636 {
14637 ...
14638
14639 private:
14640 friend class odb::access;
14641
14642 date born_;
14643
14644 #pragma db transient
14645 unsigned short age_;
14646
14647 void
14648 init (odb::callback_event e, odb::database&amp;)
14649 {
14650 switch (e)
14651 {
14652 case odb::callback_event::post_load:
14653 {
14654 // Calculate age from the date of birth.
14655 ...
14656 break;
14657 }
14658 default:
14659 break;
14660 }
14661 }
14662 };
14663 </pre>
14664
14665 <h3><a name="14.1.8">14.1.8 <code>schema</code></a></h3>
14666
14667 <p>The <code>schema</code> specifier specifies a database schema
14668 that should be used for the persistent class.</p>
14669
14670 <p>In relational databases the term schema can refer to two related
14671 but ultimately different concepts. Normally it means a collection
14672 of tables, indexes, sequences, etc., that are created in the
14673 database or the actual DDL statements that create these
14674 database objects. Some database implementations support what
14675 would be more accurately called a <em>database namespace</em>
14676 but is also called a schema. In this sense, a schema is a
14677 separate namespace in which tables, indexes, sequences, etc.,
14678 can be created. For example, two tables that have the same
14679 name can coexist in the same database if they belong to
14680 different schemas. In this section when we talk about a
14681 schema, we refer to the <em>database namespace</em> meaning
14682 of this term. </p>
14683
14684 <p>When schemas are in use, a database object name is qualified
14685 with a schema. For example:</p>
14686
14687 <pre class="sql">
14688 CREATE TABLE accounting.employee (...)
14689
14690 SELECT ... FROM accounting.employee WHERE ...
14691 </pre>
14692
14693 <p>In the above example <code>accounting</code> is the schema
14694 and the <code>employee</code> table belongs to this
14695 schema.</p>
14696
14697 <p>Not all database implementations support schemas. Some
14698 implementation that don't support schemas (for example,
14699 MySQL, SQLite) allow the use of the above syntax to specify
14700 the database name. Yet others may support several levels
14701 of qualification. For example, Microsoft SQL Server has
14702 three levels starting with the linked database server,
14703 followed by the database, and then followed by
14704 the schema:
14705 <code>server1.company1.accounting.employee</code>.
14706 While the actual meaning of the qualifier in a qualified name
14707 vary from one database implementation to another, here we
14708 refer to all of them collectively as a schema.</p>
14709
14710 <p>In ODB, a schema for a table of a persistent class can be
14711 specified at the class level, C++ namespace level, or the
14712 file level. To assign a schema to a specific persistent class
14713 we can use the <code>schema</code> specifier, for example:</p>
14714
14715 <pre class="cxx">
14716 #pragma db object schema("accounting")
14717 class employee
14718 {
14719 ...
14720 };
14721 </pre>
14722
14723 <p>If we are also assigning a table name, then we can use
14724 a shorter notation by specifying both the schema and
14725 the table name in the <code>table</code> specifier:</p>
14726
14727 <pre class="cxx">
14728 #pragma db object table("accounting.employee")
14729 class employee
14730 {
14731 ...
14732 };
14733 </pre>
14734
14735 <p>If we want to assign a schema to all the persistent classes
14736 in a C++ namespace, then, instead of specifying the schema
14737 for each class, we can specify it once at the C++ namespace level.
14738 For example:</p>
14739
14740 <pre class="cxx">
14741 #pragma db namespace schema("accounting")
14742 namespace accounting
14743 {
14744 #pragma db object
14745 class employee
14746 {
14747 ...
14748 };
14749
14750 #pragma db object
14751 class employer
14752 {
14753 ...
14754 };
14755 }
14756 </pre>
14757
14758 <p>If we want to assign a schema to all the persistent classes in
14759 a file, then we can use the <code>--schema</code> ODB compiler
14760 option. For example:</p>
14761
14762 <pre class="terminal">
14763 odb ... --schema accounting ...
14764 </pre>
14765
14766 <p>An alternative to this approach with the same effect is to
14767 assign a schema to the global namespace:</p>
14768
14769 <pre class="cxx">
14770 #pragma db namespace() schema("accounting")
14771 </pre>
14772
14773 <p>By default schema qualifications are accumulated starting from
14774 the persistent class, continuing with the namespace hierarchy
14775 to which this class belongs, and finishing with the schema
14776 specified with the <code>--schema</code> option. For
14777 example:</p>
14778
14779 <pre class="cxx">
14780 #pragma db namespace schema("audit_db")
14781 namespace audit
14782 {
14783 #pragma db namespace schema("accounting")
14784 namespace accounting
14785 {
14786 #pragma db object
14787 class employee
14788 {
14789 ...
14790 };
14791 }
14792 }
14793 </pre>
14794
14795 <p>If we compile the above code fragment with the
14796 <code>--schema&nbsp;server1</code> option, then the
14797 <code>employee</code> table will have the
14798 <code>server1.audit_db.accounting.employee</code> qualified
14799 name.</p>
14800
14801 <p>In some situations we may want to prevent such accumulation
14802 of the qualifications. To accomplish this we can use the
14803 so-called fully-qualified names, which have the empty leading
14804 name component. This is analogous to the C++ fully-qualified
14805 names in the <code>::accounting::employee</code> form. For
14806 example:</p>
14807
14808 <pre class="cxx">
14809 #pragma db namespace schema("accounting")
14810 namespace accounting
14811 {
14812 #pragma db object schema(".hr")
14813 class employee
14814 {
14815 ...
14816 };
14817
14818 #pragma db object
14819 class employer
14820 {
14821 ...
14822 };
14823 }
14824 </pre>
14825
14826 <p>In the above code fragment, the <code>employee</code> table will
14827 have the <code>hr.employee</code> qualified name while the
14828 <code>employer</code> &mdash; <code>accounting.employer</code>.
14829 Note also that the empty leading name component is a special
14830 ODB syntax and is not propagated to the actual database names
14831 (using a name like <code>.hr.employee</code> to refer to a table
14832 will most likely result in an error).</p>
14833
14834 <p>Auxiliary database objects for a persistent class, such as indexes,
14835 sequences, triggers, etc., are all created in the same schema
14836 as the class table. By default, this is also true for the
14837 container tables. However, if you need to store a container
14838 table in a different schema, then you can provide a qualified
14839 name using the <code>table</code> specifier, for example:</p>
14840
14841 <pre class="cxx">
14842 #pragma db object table("accounting.employee")
14843 class employee
14844 {
14845 ...
14846
14847 #pragma db object table("operations.projects")
14848 std::vector&lt;std::string> projects_;
14849 };
14850 </pre>
14851
14852 <p>The standard syntax for qualified names used in the
14853 <code>schema</code> and <code>table</code> specifiers as well
14854 as the view <code>column</code> specifier (<a href="#14.4.10">Section
14855 14.4.10, "<code>column</code> (view)"</a>) has the
14856 <code>"</code><i>name</i><code>.</code><i>name</i>...<code>"</code>
14857 form where, as discussed above, the leading name component
14858 can be empty to denote a fully qualified name. This form, however,
14859 doesn't work if one of the name components contains periods. To
14860 support such cases the alternative form is available:
14861 <code>"</code><i>name</i><code>"."</code><i>name</i><code>"</code>...
14862 For example:</p>
14863
14864 <pre class="cxx">
14865 #pragma db object table("accounting_1.2"."employee")
14866 class employee
14867 {
14868 ...
14869 };
14870 </pre>
14871
14872 <p>Finally, to specify an unqualified name that contains periods
14873 we can use the following special syntax:</p>
14874
14875 <pre class="cxx">
14876 #pragma db object schema(."accounting_1.2") table("employee")
14877 class employee
14878 {
14879 ...
14880 };
14881 </pre>
14882
14883 <p>Table prefixes (<a href="#14.5.2">Section 14.5.2, "<code>table</code>"</a>)
14884 can be used as an alternative to database schemas if the target
14885 database system does not support schemas.</p>
14886
14887 <h3><a name="14.1.9">14.1.9 <code>polymorphic</code></a></h3>
14888
14889 <p>The <code>polymorphic</code> specifier specifies that the persistent
14890 class is polymorphic. For more information on polymorphism support,
14891 refer to <a href="#8">Chapter 8, "Inheritance"</a>.</p>
14892
14893 <h3><a name="14.1.10">14.1.10 <code>session</code></a></h3>
14894
14895 <p>The <code>session</code> specifier specifies whether to enable
14896 session support for the persistent class. For example:</p>
14897
14898 <pre class="cxx">
14899 #pragma db object session // Enable.
14900 class person
14901 {
14902 ...
14903 };
14904
14905 #pragma db object session(true) // Enable.
14906 class employee
14907 {
14908 ...
14909 };
14910
14911 #pragma db object session(false) // Disable.
14912 class employer
14913 {
14914 ...
14915 };
14916 </pre>
14917
14918 <p>Session support is disabled by default unless the
14919 <code>--generate-session</code> ODB compiler option is specified
14920 or session support is enabled at the namespace level
14921 (<a href="#14.5.4">Section 14.5.4, "<code>session</code>"</a>).
14922 For more information on sessions, refer to <a href="#11">Chapter
14923 11, "Session"</a>.</p>
14924
14925 <h3><a name="14.1.11">14.1.11 <code>definition</code></a></h3>
14926
14927 <p>The <code>definition</code> specifier specifies an alternative
14928 <em>definition location</em> for the persistent class. By
14929 default, the ODB compiler generates the database support code for
14930 a persistent class when we compile the header file that
14931 defines this class. However, if the <code>definition</code>
14932 specifier is used, then the ODB compiler will instead generate
14933 the database support code when we compile the header file
14934 containing this pragma.</p>
14935
14936 <p>For more information on this functionality, refer to
14937 <a href="#14.3.7">Section 14.3.7, "<code>definition</code>"</a>.</p>
14938
14939 <h3><a name="14.1.12">14.1.12 <code>transient</code></a></h3>
14940
14941 <p>The <code>transient</code> specifier instructs the ODB compiler to
14942 treat all non-virtual data members in the persistent class as transient
14943 (<a href="#14.4.1">Section 14.4.1, "<code>transient</code>"</a>).
14944 This specifier is primarily useful when declaring virtual data
14945 members, as discussed in <a href="#14.4.13">Section 14.4.13,
14946 "<code>virtual</code>"</a>.</p>
14947
14948 <h3><a name="14.1.13">14.1.13 <code>sectionable</code></a></h3>
14949
14950 <p>The <code>sectionable</code> specifier instructs the ODB compiler
14951 to generate support for the addition of new object sections in
14952 derived classes in a hierarchy with the optimistic concurrency
14953 model. For more information on this functionality, refer to
14954 <a href="#9.2">Section 9.2, "Sections and Optimistic
14955 Concurrency"</a>.</p>
14956
14957 <h3><a name="14.1.14">14.1.14 <code>deleted</code></a></h3>
14958
14959 <p>The <code>deleted</code> specifier marks the persistent class as
14960 soft-deleted. The single required argument to this specifier is
14961 the deletion version. For more information on this functionality,
14962 refer to <a href="#13.4">Section 13.4, "Soft Object Model
14963 Changes"</a>.</p>
14964
14965 <h3><a name="14.1.15">14.1.15 <code>bulk</code></a></h3>
14966
14967 <p>The <code>bulk</code> specifier enables bulk operation support for
14968 the persistent class. The single required argument to this specifier
14969 is the batch size. For more information on this functionality, refer
14970 to <a href="#15.3">Section 15.3, "Bulk Database Operations"</a>.</p>
14971
14972 <h2><a name="14.2">14.2 View Type Pragmas</a></h2>
14973
14974 <p>A pragma with the <code>view</code> qualifier declares a C++ class
14975 as a view type. The qualifier can be optionally followed,
14976 in any order, by one or more specifiers summarized in the
14977 table below:</p>
14978
14979 <!-- border="1" is necessary for html2ps -->
14980 <table class="specifiers" border="1">
14981 <tr>
14982 <th>Specifier</th>
14983 <th>Summary</th>
14984 <th>Section</th>
14985 </tr>
14986
14987 <tr>
14988 <td><code>object</code></td>
14989 <td>object associated with a view</td>
14990 <td><a href="#14.2.1">14.2.1</a></td>
14991 </tr>
14992
14993 <tr>
14994 <td><code>table</code></td>
14995 <td>table associated with a view</td>
14996 <td><a href="#14.2.2">14.2.2</a></td>
14997 </tr>
14998
14999 <tr>
15000 <td><code>query</code></td>
15001 <td>view query condition</td>
15002 <td><a href="#14.2.3">14.2.3</a></td>
15003 </tr>
15004
15005 <tr>
15006 <td><code>pointer</code></td>
15007 <td>pointer type for a view</td>
15008 <td><a href="#14.2.4">14.2.4</a></td>
15009 </tr>
15010
15011 <tr>
15012 <td><code>callback</code></td>
15013 <td>database operations callback</td>
15014 <td><a href="#14.2.5">14.2.5</a></td>
15015 </tr>
15016
15017 <tr>
15018 <td><code>definition</code></td>
15019 <td>definition location for a view</td>
15020 <td><a href="#14.2.6">14.2.6</a></td>
15021 </tr>
15022
15023 <tr>
15024 <td><code>transient</code></td>
15025 <td>all non-virtual data members in a view are transient</td>
15026 <td><a href="#14.2.7">14.2.7</a></td>
15027 </tr>
15028
15029 </table>
15030
15031 <p>For more information on view types refer to <a href="#10"> Chapter 10,
15032 "Views"</a>.</p>
15033
15034 <h3><a name="14.2.1">14.2.1 <code>object</code></a></h3>
15035
15036 <p>The <code>object</code> specifier specifies a persistent class
15037 that should be associated with the view. For more information
15038 on object associations refer to <a href="#10.1">Section 10.1, "Object
15039 Views"</a>.</p>
15040
15041 <h3><a name="14.2.2">14.2.2 <code>table</code></a></h3>
15042
15043 <p>The <code>table</code> specifier specifies a database table
15044 that should be associated with the view. For more information
15045 on table associations refer to <a href="#10.3">Section 10.3, "Table
15046 Views"</a>.</p>
15047
15048 <h3><a name="14.2.3">14.2.3 <code>query</code></a></h3>
15049
15050 <p>The <code>query</code> specifier specifies a query condition
15051 and, optionally, result modifiers for an object or table view
15052 or a native SQL query for a native view. An empty <code>query</code>
15053 specifier indicates that a native SQL query is provided at runtime.
15054 For more information on query conditions refer to
15055 <a href="#10.5">Section 10.5, "View Query Conditions"</a>. For
15056 more information on native SQL queries, refer to
15057 <a href="#10.6">Section 10.6, "Native Views"</a>.</p>
15058
15059 <h3><a name="14.2.4">14.2.4 <code>pointer</code></a></h3>
15060
15061 <p>The <code>pointer</code> specifier specifies the view pointer type
15062 for the view class. Similar to objects, the view pointer type is used
15063 to return dynamically allocated instances of a view class. The
15064 semantics of the <code>pointer</code> specifier for a view are the
15065 same as those of the <code>pointer</code> specifier for an object
15066 (<a href="#14.1.2">Section 14.1.2, "<code>pointer</code>"</a>).</p>
15067
15068 <h3><a name="14.2.5">14.2.5 <code>callback</code></a></h3>
15069
15070 <p>The <code>callback</code> specifier specifies the view class
15071 member function that should be called before and after an
15072 instance of this view class is created as part of the query
15073 result iteration. The semantics of the <code>callback</code>
15074 specifier for a view are similar to those of the
15075 <code>callback</code> specifier for an object
15076 (<a href="#14.1.7">Section 14.1.7, "<code>callback</code>"</a>)
15077 except that the only events that can trigger a callback
15078 call in the case of a view are <code>pre_load</code> and
15079 <code>post_load</code>.</p>
15080
15081 <h3><a name="14.2.6">14.2.6 <code>definition</code></a></h3>
15082
15083 <p>The <code>definition</code> specifier specifies an alternative
15084 <em>definition location</em> for the view class. By
15085 default, the ODB compiler generates the database support code for
15086 a view class when we compile the header file that
15087 defines this class. However, if the <code>definition</code>
15088 specifier is used, then the ODB compiler will instead generate
15089 the database support code when we compile the header file
15090 containing this pragma.</p>
15091
15092 <p>For more information on this functionality, refer to
15093 <a href="#14.3.7">Section 14.3.7, "<code>definition</code>"</a>.</p>
15094
15095 <h3><a name="14.2.7">14.2.7 <code>transient</code></a></h3>
15096
15097 <p>The <code>transient</code> specifier instructs the ODB compiler
15098 to treat all non-virtual data members in the view class as transient
15099 (<a href="#14.4.1">Section 14.4.1, "<code>transient</code>"</a>).
15100 This specifier is primarily useful when declaring virtual data
15101 members, as discussed in <a href="#14.4.13">Section 14.4.13,
15102 "<code>virtual</code>"</a>.</p>
15103
15104 <h2><a name="14.3">14.3 Value Type Pragmas</a></h2>
15105
15106 <p>A pragma with the <code>value</code> qualifier describes a value
15107 type. It can be optionally followed, in any order, by one or more
15108 specifiers summarized in the table below:</p>
15109
15110 <!-- border="1" is necessary for html2ps -->
15111 <table class="specifiers" border="1">
15112 <tr>
15113 <th>Specifier</th>
15114 <th>Summary</th>
15115 <th>Section</th>
15116 </tr>
15117
15118 <tr>
15119 <td><code>type</code></td>
15120 <td>database type for a value type</td>
15121 <td><a href="#14.3.1">14.3.1</a></td>
15122 </tr>
15123
15124 <tr>
15125 <td><code>id_type</code></td>
15126 <td>database type for a value type when used as an object id</td>
15127 <td><a href="#14.3.2">14.3.2</a></td>
15128 </tr>
15129
15130 <tr>
15131 <td><code>null</code>/<code>not_null</code></td>
15132 <td>type can/cannot be <code>NULL</code></td>
15133 <td><a href="#14.3.3">14.3.3</a></td>
15134 </tr>
15135
15136 <tr>
15137 <td><code>default</code></td>
15138 <td>default value for a value type</td>
15139 <td><a href="#14.3.4">14.3.4</a></td>
15140 </tr>
15141
15142 <tr>
15143 <td><code>options</code></td>
15144 <td>database options for a value type</td>
15145 <td><a href="#14.3.5">14.3.5</a></td>
15146 </tr>
15147
15148 <tr>
15149 <td><code>readonly</code></td>
15150 <td>composite value type is read-only</td>
15151 <td><a href="#14.3.6">14.3.6</a></td>
15152 </tr>
15153
15154 <tr>
15155 <td><code>definition</code></td>
15156 <td>definition location for a composite value type</td>
15157 <td><a href="#14.3.7">14.3.7</a></td>
15158 </tr>
15159
15160 <tr>
15161 <td><code>transient</code></td>
15162 <td>all non-virtual data members in a composite value are transient</td>
15163 <td><a href="#14.3.8">14.3.8</a></td>
15164 </tr>
15165
15166 <tr>
15167 <td><code>unordered</code></td>
15168 <td>ordered container should be stored unordered</td>
15169 <td><a href="#14.3.9">14.3.9</a></td>
15170 </tr>
15171
15172 <tr>
15173 <td><code>index_type</code></td>
15174 <td>database type for a container's index type</td>
15175 <td><a href="#14.3.10">14.3.10</a></td>
15176 </tr>
15177
15178 <tr>
15179 <td><code>key_type</code></td>
15180 <td>database type for a container's key type</td>
15181 <td><a href="#14.3.11">14.3.11</a></td>
15182 </tr>
15183
15184 <tr>
15185 <td><code>value_type</code></td>
15186 <td>database type for a container's value type</td>
15187 <td><a href="#14.3.12">14.3.12</a></td>
15188 </tr>
15189
15190 <tr>
15191 <td><code>value_null</code>/<code>value_not_null</code></td>
15192 <td>container's value can/cannot be <code>NULL</code></td>
15193 <td><a href="#14.3.13">14.3.13</a></td>
15194 </tr>
15195
15196 <tr>
15197 <td><code>id_options</code></td>
15198 <td>database options for a container's id column</td>
15199 <td><a href="#14.3.14">14.3.14</a></td>
15200 </tr>
15201
15202 <tr>
15203 <td><code>index_options</code></td>
15204 <td>database options for a container's index column</td>
15205 <td><a href="#14.3.15">14.3.15</a></td>
15206 </tr>
15207
15208 <tr>
15209 <td><code>key_options</code></td>
15210 <td>database options for a container's key column</td>
15211 <td><a href="#14.3.16">14.3.16</a></td>
15212 </tr>
15213
15214 <tr>
15215 <td><code>value_options</code></td>
15216 <td>database options for a container's value column</td>
15217 <td><a href="#14.3.17">14.3.17</a></td>
15218 </tr>
15219
15220 <tr>
15221 <td><code>id_column</code></td>
15222 <td>column name for a container's object id</td>
15223 <td><a href="#14.3.18">14.3.18</a></td>
15224 </tr>
15225
15226 <tr>
15227 <td><code>index_column</code></td>
15228 <td>column name for a container's index</td>
15229 <td><a href="#14.3.19">14.3.19</a></td>
15230 </tr>
15231
15232 <tr>
15233 <td><code>key_column</code></td>
15234 <td>column name for a container's key</td>
15235 <td><a href="#14.3.20">14.3.20</a></td>
15236 </tr>
15237
15238 <tr>
15239 <td><code>value_column</code></td>
15240 <td>column name for a container's value</td>
15241 <td><a href="#14.3.21">14.3.21</a></td>
15242 </tr>
15243
15244 </table>
15245
15246 <p>Many of the value type specifiers have corresponding member type
15247 specifiers with the same names (<a href="#14.4">Section 14.4,
15248 "Data Member Pragmas"</a>). The behavior of such specifiers
15249 for members is similar to that for value types. The only difference
15250 is the scope. A particular value type specifier applies to all the
15251 members of this value type that don't have a pre-member version
15252 of the specifier, while the member specifier always applies only
15253 to a single member. Also, with a few exceptions, member specifiers
15254 take precedence over and override parameters specified with value
15255 specifiers.</p>
15256
15257 <h3><a name="14.3.1">14.3.1 <code>type</code></a></h3>
15258
15259 <p>The <code>type</code> specifier specifies the native database type
15260 that should be used for data members of this type. For example:</p>
15261
15262 <pre class="cxx">
15263 #pragma db value(bool) type("INT")
15264
15265 #pragma db object
15266 class person
15267 {
15268 ...
15269
15270 bool married_; // Mapped to INT NOT NULL database type.
15271 };
15272 </pre>
15273
15274 <p>The ODB compiler provides the default mapping between common C++
15275 types, such as <code>bool</code>, <code>int</code>, and
15276 <code>std::string</code> and the database types for each supported
15277 database system. For more information on the default mapping,
15278 refer to <a href="#II">Part II, "Database Systems"</a>. The
15279 <code>null</code> and <code>not_null</code> (<a href="#14.3.3">Section
15280 14.3.3, "<code>null</code>/<code>not_null</code>"</a>) specifiers
15281 can be used to control the <code>NULL</code> semantics of a type.</p>
15282
15283 <p>In the above example we changed the mapping for the <code>bool</code>
15284 type which is now mapped to the <code>INT</code> database type. In
15285 this case, the <code>value</code> pragma is all that is necessary
15286 since the ODB compiler will be able to figure out how to store
15287 a boolean value as an integer in the database. However, there
15288 could be situations where the ODB compiler will not know how to
15289 handle the conversion between the C++ and database representations
15290 of a value. Consider, as an example, a situation where the
15291 boolean value is stored in the database as a string:</p>
15292
15293 <pre class="cxx">
15294 #pragma db value(bool) type("VARCHAR(5)")
15295 </pre>
15296
15297 <p>The possible database values for the C++ <code>true</code> value could
15298 be <code>"true"</code>, or <code>"TRUE"</code>, or <code>"True"</code>.
15299 Or, maybe, all of the above could be valid. The ODB compiler has no way
15300 of knowing how your application wants to convert <code>bool</code>
15301 to a string and back. To support such custom value type mappings,
15302 ODB allows you to provide your own database conversion functions
15303 by specializing the <code>value_traits</code> class template. The
15304 <code>mapping</code> example in the <code>odb-examples</code>
15305 package shows how to do this for all the supported database systems.</p>
15306
15307 <h3><a name="14.3.2">14.3.2 <code>id_type</code></a></h3>
15308
15309 <p>The <code>id_type</code> specifier specifies the native database type
15310 that should be used for data members of this type that are designated as
15311 object identifiers (<a href="#14.4.1">Section 14.4.1,
15312 "<code>id</code>"</a>). In combination with the <code>type</code>
15313 specifier (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>)
15314 <code>id_type</code> allows you to map a C++ type differently depending
15315 on whether it is used in an ordinary member or an object id. For
15316 example:</p>
15317
15318 <pre class="cxx">
15319 #pragma db value(std::string) type("TEXT") id_type("VARCHAR(128)")
15320
15321 #pragma db object
15322 class person
15323 {
15324 ...
15325
15326 #pragma db id
15327 std::string email_; // Mapped to VARCHAR(128) NOT NULL.
15328
15329 std::string name_; // Mapped to TEXT NOT NULL.
15330 };
15331 </pre>
15332
15333 <p>Note that there is no corresponding member type specifier for
15334 <code>id_type</code> since the desired result can be achieved
15335 with just the <code>type</code> specifier, for example:</p>
15336
15337 <pre class="cxx">
15338 #pragma db object
15339 class person
15340 {
15341 ...
15342
15343 #pragma db id type("VARCHAR(128)")
15344 std::string email_;
15345 };
15346 </pre>
15347
15348 <h3><a name="14.3.3">14.3.3 <code>null</code>/<code>not_null</code></a></h3>
15349
15350 <p>The <code>null</code> and <code>not_null</code> specifiers specify that
15351 a value type or object pointer can or cannot be <code>NULL</code>,
15352 respectively. By default, value types are assumed not to allow
15353 <code>NULL</code> values while object pointers are assumed to
15354 allow <code>NULL</code> values. Data members of types that allow
15355 <code>NULL</code> values are mapped in a relational database to
15356 columns that allow <code>NULL</code> values. For example:</p>
15357
15358 <pre class="cxx">
15359 using std::tr1::shared_ptr;
15360
15361 typedef shared_ptr&lt;std::string> string_ptr;
15362 #pragma db value(string_ptr) type("TEXT") null
15363
15364 #pragma db object
15365 class person
15366 {
15367 ...
15368
15369 string_ptr name_; // Mapped to TEXT NULL.
15370 };
15371
15372 typedef shared_ptr&lt;person> person_ptr;
15373 #pragma db value(person_ptr) not_null
15374 </pre>
15375
15376 <p>The <code>NULL</code> semantics can also be specified on the
15377 per-member basis (<a href="#14.4.6">Section 14.4.6,
15378 "<code>null</code>/<code>not_null</code>"</a>). If both a type and
15379 a member have <code>null</code>/<code>not_null</code> specifiers,
15380 then the member specifier takes precedence. If a member specifier
15381 relaxes the <code>NULL</code> semantics (that is, if a member has
15382 the <code>null</code> specifier and the type has the explicit
15383 <code>not_null</code> specifier), then a warning is issued.</p>
15384
15385 <p>It is also possible to override a previously specified
15386 <code>null</code>/<code>not_null</code> specifier. This is
15387 primarily useful if a third-party type, for example,
15388 one provided by a profile library (<a href="#III">Part III,
15389 "Profiles"</a>), allows <code>NULL</code> values but in your
15390 object model data members of this type should never be
15391 <code>NULL</code>. In this case you can use the <code>not_null</code>
15392 specifier to disable <code>NULL</code> values for this type for the
15393 entire translation unit. For example:</p>
15394
15395 <pre class="cxx">
15396 // By default, null_string allows NULL values.
15397 //
15398 #include &lt;null-string.hxx>
15399
15400 // Disable NULL values for all the null_string data members.
15401 //
15402 #pragma db value(null_string) not_null
15403 </pre>
15404
15405 <p>For a more detailed discussion of the <code>NULL</code> semantics
15406 for values, refer to <a href="#7.3">Section 7.3, "Pointers and
15407 <code>NULL</code> Value Semantics"</a>. For a more detailed
15408 discussion of the <code>NULL</code> semantics for object pointers,
15409 refer to <a href="#6">Chapter 6, "Relationships"</a>.</p>
15410
15411 <h3><a name="14.3.4">14.3.4 <code>default</code></a></h3>
15412
15413 <p>The <code>default</code> specifier specifies the database default value
15414 that should be used for data members of this type. For example:</p>
15415
15416 <pre class="cxx">
15417 #pragma db value(std::string) default("")
15418
15419 #pragma db object
15420 class person
15421 {
15422 ...
15423
15424 std::string name_; // Mapped to TEXT NOT NULL DEFAULT ''.
15425 };
15426 </pre>
15427
15428 <p>The semantics of the <code>default</code> specifier for a value type
15429 are similar to those of the <code>default</code> specifier for a
15430 data member (<a href="#14.4.7">Section 14.4.7,
15431 "<code>default</code>"</a>).</p>
15432
15433 <h3><a name="14.3.5">14.3.5 <code>options</code></a></h3>
15434
15435 <p>The <code>options</code> specifier specifies additional column
15436 definition options that should be used for data members of this
15437 type. For example:</p>
15438
15439 <pre class="cxx">
15440 #pragma db value(std::string) options("COLLATE binary")
15441
15442 #pragma db object
15443 class person
15444 {
15445 ...
15446
15447 std::string name_; // Mapped to TEXT NOT NULL COLLATE binary.
15448 };
15449 </pre>
15450
15451 <p>The semantics of the <code>options</code> specifier for a value type
15452 are similar to those of the <code>options</code> specifier for a
15453 data member (<a href="#14.4.8">Section 14.4.8,
15454 "<code>options</code>"</a>).</p>
15455
15456 <h3><a name="14.3.6">14.3.6 <code>readonly</code></a></h3>
15457
15458 <p>The <code>readonly</code> specifier specifies that the composite
15459 value type is read-only. Changes to data members of a read-only
15460 composite value type are ignored when updating the database
15461 state of an object (<a href="#3.10">Section 3.10, "Updating Persistent
15462 Objects"</a>) containing such a value type. Note that this specifier
15463 is only valid for composite value types. For example:</p>
15464
15465 <pre class="cxx">
15466 #pragma db value readonly
15467 class person_name
15468 {
15469 ...
15470 };
15471 </pre>
15472
15473 <p>Read-only and read-write composite values can derive from each other
15474 without any restrictions. When a read-only value derives from a
15475 read-write value, the resulting whole value is read-only, including
15476 the part corresponding to the read-write base. On the other hand, when a
15477 read-write value derives from a read-only value, all the data
15478 members that correspond to the read-only base are treated as
15479 read-only while the rest is treated as read-write.</p>
15480
15481 <p>Note that it is also possible to declare individual data members
15482 (<a href="#14.4.12">Section 14.4.12, "<code>readonly</code>"</a>)
15483 as well as whole objects (<a href="#14.1.4">Section 14.1.4,
15484 "<code>readonly</code>"</a>) as read-only.</p>
15485
15486 <h3><a name="14.3.7">14.3.7 <code>definition</code></a></h3>
15487
15488 <p>The <code>definition</code> specifier specifies an alternative
15489 <em>definition location</em> for the composite value type. By
15490 default, the ODB compiler generates the database support code for
15491 a composite value type when we compile the header file that
15492 defines this value type. However, if the <code>definition</code>
15493 specifier is used, then the ODB compiler will instead generate
15494 the database support code when we compile the header file containing
15495 this pragma.</p>
15496
15497 <p>This mechanism is primarily useful for converting third-party
15498 types to ODB composite value types. In such cases we normally
15499 cannot modify the header files to add the necessary pragmas.
15500 It is also often inconvenient to compile these header files
15501 with the ODB compiler. With the <code>definition</code>
15502 specifier we can create a <em>wrapper header</em> that contains
15503 the necessary pragmas and instructs the ODB compiler to generate
15504 the database support code for a third-party type when we compile
15505 the wrapper header. As an example, consider <code>struct timeval</code>
15506 that is defined in the <code>&lt;sys/time.h></code> system header.
15507 This type has the following (or similar) definition:</p>
15508
15509 <pre class="cxx">
15510 struct timeval
15511 {
15512 long tv_sec;
15513 long tv_usec;
15514 };
15515 </pre>
15516
15517 <p>If we would like to make this type an ODB composite value type,
15518 then we can create a wrapper header, for example
15519 <code>time-mapping.hxx</code>, with the following content:</p>
15520
15521 <pre class="cxx">
15522 #ifndef TIME_MAPPING_HXX
15523 #define TIME_MAPPING_HXX
15524
15525 #include &lt;sys/time.h>
15526
15527 #pragma db value(timeval) definition
15528 #pragma db member(timeval::tv_sec) column("sec")
15529 #pragma db member(timeval::tv_usec) column("usec")
15530
15531 #endif // TIME_MAPPING_HXX
15532 </pre>
15533
15534 <p>If we now compile this header with the ODB compiler, the
15535 resulting <code>time-mapping-odb.?xx</code> files will
15536 contain the database support code for <code>struct timeval</code>.
15537 To use <code>timeval</code> in our persistent classes, we simply
15538 include the <code>time-mapping.hxx</code> header:</p>
15539
15540 <pre class="cxx">
15541 #include &lt;sys/time.h>
15542 #include "time-mapping.hxx"
15543
15544 #pragma db object
15545 class object
15546 {
15547 timeval timestamp;
15548 };
15549 </pre>
15550
15551 <h3><a name="14.3.8">14.3.8 <code>transient</code></a></h3>
15552
15553 <p>The <code>transient</code> specifier instructs the ODB compiler
15554 to treat all non-virtual data members in the composite value type
15555 as transient (<a href="#14.4.1">Section 14.4.1,
15556 "<code>transient</code>"</a>). This specifier is primarily useful
15557 when declaring virtual data members, as discussed in
15558 <a href="#14.4.13">Section 14.4.13, "<code>virtual</code>"</a>.</p>
15559
15560 <h3><a name="14.3.9">14.3.9 <code>unordered</code></a></h3>
15561
15562 <p>The <code>unordered</code> specifier specifies that the ordered
15563 container should be stored unordered in the database. The database
15564 table for such a container will not contain the index column
15565 and the order in which elements are retrieved from the database may
15566 not be the same as the order in which they were stored. For example:</p>
15567
15568 <pre class="cxx">
15569 typedef std::vector&lt;std::string> names;
15570 #pragma db value(names) unordered
15571 </pre>
15572
15573 <p>For a more detailed discussion of ordered containers and their
15574 storage in the database, refer to <a href="#5.1">Section 5.1,
15575 "Ordered Containers"</a>.</p>
15576
15577 <h3><a name="14.3.10">14.3.10 <code>index_type</code></a></h3>
15578
15579 <p>The <code>index_type</code> specifier specifies the native
15580 database type that should be used for the ordered container's
15581 index column. The semantics of <code>index_type</code>
15582 are similar to those of the <code>type</code> specifier
15583 (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>). The native
15584 database type is expected to be an integer type. For example:</p>
15585
15586 <pre class="cxx">
15587 typedef std::vector&lt;std::string> names;
15588 #pragma db value(names) index_type("SMALLINT UNSIGNED")
15589 </pre>
15590
15591 <h3><a name="14.3.11">14.3.11 <code>key_type</code></a></h3>
15592
15593 <p>The <code>key_type</code> specifier specifies the native
15594 database type that should be used for the map container's
15595 key column. The semantics of <code>key_type</code>
15596 are similar to those of the <code>type</code> specifier
15597 (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>). For
15598 example:</p>
15599
15600 <pre class="cxx">
15601 typedef std::map&lt;unsigned short, float> age_weight_map;
15602 #pragma db value(age_weight_map) key_type("INT UNSIGNED")
15603 </pre>
15604
15605 <h3><a name="14.3.12">14.3.12 <code>value_type</code></a></h3>
15606
15607 <p>The <code>value_type</code> specifier specifies the native
15608 database type that should be used for the container's
15609 value column. The semantics of <code>value_type</code>
15610 are similar to those of the <code>type</code> specifier
15611 (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>). For
15612 example:</p>
15613
15614 <pre class="cxx">
15615 typedef std::vector&lt;std::string> names;
15616 #pragma db value(names) value_type("VARCHAR(255)")
15617 </pre>
15618
15619 <p>The <code>value_null</code> and <code>value_not_null</code>
15620 (<a href="#14.3.13">Section 14.3.13,
15621 "<code>value_null</code>/<code>value_not_null</code>"</a>) specifiers
15622 can be used to control the <code>NULL</code> semantics of a value
15623 column.</p>
15624
15625 <h3><a name="14.3.13">14.3.13 <code>value_null</code>/<code>value_not_null</code></a></h3>
15626
15627 <p>The <code>value_null</code> and <code>value_not_null</code> specifiers
15628 specify that the container type's element value can or cannot be
15629 <code>NULL</code>, respectively. The semantics of <code>value_null</code>
15630 and <code>value_not_null</code> are similar to those of the
15631 <code>null</code> and <code>not_null</code> specifiers
15632 (<a href="#14.3.3">Section 14.3.3, "<code>null</code>/<code>not_null</code>"</a>).
15633 For example:</p>
15634
15635 <pre class="cxx">
15636 using std::tr1::shared_ptr;
15637
15638 #pragma db object
15639 class account
15640 {
15641 ...
15642 };
15643
15644 typedef std::vector&lt;shared_ptr&lt;account> > accounts;
15645 #pragma db value(accounts) value_not_null
15646 </pre>
15647
15648 <p>For set and multiset containers (<a href="#5.2">Section 5.2, "Set and
15649 Multiset Containers"</a>) the element value is automatically treated
15650 as not allowing a <code>NULL</code> value.</p>
15651
15652
15653 <h3><a name="14.3.14">14.3.14 <code>id_options</code></a></h3>
15654
15655 <p>The <code>id_options</code> specifier specifies additional
15656 column definition options that should be used for the container's
15657 id column. For example:</p>
15658
15659 <pre class="cxx">
15660 typedef std::vector&lt;std::string> nicknames;
15661 #pragma db value(nicknames) id_options("COLLATE binary")
15662 </pre>
15663
15664 <p>The semantics of the <code>id_options</code> specifier for a container
15665 type are similar to those of the <code>id_options</code> specifier for
15666 a container data member (<a href="#14.4.29">Section 14.4.29,
15667 "<code>id_options</code>"</a>).</p>
15668
15669
15670 <h3><a name="14.3.15">14.3.15 <code>index_options</code></a></h3>
15671
15672 <p>The <code>index_options</code> specifier specifies additional
15673 column definition options that should be used for the container's
15674 index column. For example:</p>
15675
15676 <pre class="cxx">
15677 typedef std::vector&lt;std::string> nicknames;
15678 #pragma db value(nicknames) index_options("ZEROFILL")
15679 </pre>
15680
15681 <p>The semantics of the <code>index_options</code> specifier for a container
15682 type are similar to those of the <code>index_options</code> specifier for
15683 a container data member (<a href="#14.4.30">Section 14.4.30,
15684 "<code>index_options</code>"</a>).</p>
15685
15686
15687 <h3><a name="14.3.16">14.3.16 <code>key_options</code></a></h3>
15688
15689 <p>The <code>key_options</code> specifier specifies additional
15690 column definition options that should be used for the container's
15691 key column. For example:</p>
15692
15693 <pre class="cxx">
15694 typedef std::map&lt;std::string, std::string> properties;
15695 #pragma db value(properties) key_options("COLLATE binary")
15696 </pre>
15697
15698 <p>The semantics of the <code>key_options</code> specifier for a container
15699 type are similar to those of the <code>key_options</code> specifier for
15700 a container data member (<a href="#14.4.31">Section 14.4.31,
15701 "<code>key_options</code>"</a>).</p>
15702
15703
15704 <h3><a name="14.3.17">14.3.17 <code>value_options</code></a></h3>
15705
15706 <p>The <code>value_options</code> specifier specifies additional
15707 column definition options that should be used for the container's
15708 value column. For example:</p>
15709
15710 <pre class="cxx">
15711 typedef std::set&lt;std::string> nicknames;
15712 #pragma db value(nicknames) value_options("COLLATE binary")
15713 </pre>
15714
15715 <p>The semantics of the <code>value_options</code> specifier for a container
15716 type are similar to those of the <code>value_options</code> specifier for
15717 a container data member (<a href="#14.4.32">Section 14.4.32,
15718 "<code>value_options</code>"</a>).</p>
15719
15720
15721 <h3><a name="14.3.18">14.3.18 <code>id_column</code></a></h3>
15722
15723 <p>The <code>id_column</code> specifier specifies the column
15724 name that should be used to store the object id in the
15725 container's table. For example:</p>
15726
15727 <pre class="cxx">
15728 typedef std::vector&lt;std::string> names;
15729 #pragma db value(names) id_column("id")
15730 </pre>
15731
15732 <p>If the column name is not specified, then <code>object_id</code>
15733 is used by default.</p>
15734
15735 <h3><a name="14.3.19">14.3.19 <code>index_column</code></a></h3>
15736
15737 <p>The <code>index_column</code> specifier specifies the column
15738 name that should be used to store the element index in the
15739 ordered container's table. For example:</p>
15740
15741 <pre class="cxx">
15742 typedef std::vector&lt;std::string> names;
15743 #pragma db value(names) index_column("name_number")
15744 </pre>
15745
15746 <p>If the column name is not specified, then <code>index</code>
15747 is used by default.</p>
15748
15749 <h3><a name="14.3.20">14.3.20 <code>key_column</code></a></h3>
15750
15751 <p>The <code>key_column</code> specifier specifies the column
15752 name that should be used to store the key in the map
15753 container's table. For example:</p>
15754
15755 <pre class="cxx">
15756 typedef std::map&lt;unsigned short, float> age_weight_map;
15757 #pragma db value(age_weight_map) key_column("age")
15758 </pre>
15759
15760 <p>If the column name is not specified, then <code>key</code>
15761 is used by default.</p>
15762
15763 <h3><a name="14.3.21">14.3.21 <code>value_column</code></a></h3>
15764
15765 <p>The <code>value_column</code> specifier specifies the column
15766 name that should be used to store the element value in the
15767 container's table. For example:</p>
15768
15769 <pre class="cxx">
15770 typedef std::map&lt;unsigned short, float> age_weight_map;
15771 #pragma db value(age_weight_map) value_column("weight")
15772 </pre>
15773
15774 <p>If the column name is not specified, then <code>value</code>
15775 is used by default.</p>
15776
15777 <!-- Data Member Pragmas -->
15778
15779
15780 <h2><a name="14.4">14.4 Data Member Pragmas</a></h2>
15781
15782 <p>A pragma with the <code>member</code> qualifier or a positioned
15783 pragma without a qualifier describes a data member. It can
15784 be optionally followed, in any order, by one or more specifiers
15785 summarized in the table below:</p>
15786
15787 <!-- border="1" is necessary for html2ps -->
15788 <table class="specifiers" border="1">
15789 <tr>
15790 <th>Specifier</th>
15791 <th>Summary</th>
15792 <th>Section</th>
15793 </tr>
15794
15795 <tr>
15796 <td><code>id</code></td>
15797 <td>member is an object id</td>
15798 <td><a href="#14.4.1">14.4.1</a></td>
15799 </tr>
15800
15801 <tr>
15802 <td><code>auto</code></td>
15803 <td>id is assigned by the database</td>
15804 <td><a href="#14.4.2">14.4.2</a></td>
15805 </tr>
15806
15807 <tr>
15808 <td><code>type</code></td>
15809 <td>database type for a member</td>
15810 <td><a href="#14.4.3">14.4.3</a></td>
15811 </tr>
15812
15813 <tr>
15814 <td><code>id_type</code></td>
15815 <td>database type for a member when used as an object id</td>
15816 <td><a href="#14.4.4">14.4.4</a></td>
15817 </tr>
15818
15819 <tr>
15820 <td><code>get</code>/<code>set</code>/<code>access</code></td>
15821 <td>member accessor/modifier expressions</td>
15822 <td><a href="#14.4.5">14.4.5</a></td>
15823 </tr>
15824
15825 <tr>
15826 <td><code>null</code>/<code>not_null</code></td>
15827 <td>member can/cannot be <code>NULL</code></td>
15828 <td><a href="#14.4.6">14.4.6</a></td>
15829 </tr>
15830
15831 <tr>
15832 <td><code>default</code></td>
15833 <td>default value for a member</td>
15834 <td><a href="#14.4.7">14.4.7</a></td>
15835 </tr>
15836
15837 <tr>
15838 <td><code>options</code></td>
15839 <td>database options for a member</td>
15840 <td><a href="#14.4.8">14.4.8</a></td>
15841 </tr>
15842
15843 <tr>
15844 <td><code>column</code></td>
15845 <td>column name for a member of an object or composite value</td>
15846 <td><a href="#14.4.9">14.4.9</a></td>
15847 </tr>
15848
15849 <tr>
15850 <td><code>column</code></td>
15851 <td>column name for a member of a view</td>
15852 <td><a href="#14.4.10">14.4.10</a></td>
15853 </tr>
15854
15855 <tr>
15856 <td><code>transient</code></td>
15857 <td>member is not stored in the database</td>
15858 <td><a href="#14.4.11">14.4.11</a></td>
15859 </tr>
15860
15861 <tr>
15862 <td><code>readonly</code></td>
15863 <td>member is read-only</td>
15864 <td><a href="#14.4.12">14.4.12</a></td>
15865 </tr>
15866
15867 <tr>
15868 <td><code>virtual</code></td>
15869 <td>declare a virtual data member</td>
15870 <td><a href="#14.4.13">14.4.13</a></td>
15871 </tr>
15872
15873 <tr>
15874 <td><code>inverse</code></td>
15875 <td>member is an inverse side of a bidirectional relationship</td>
15876 <td><a href="#14.4.14">14.4.14</a></td>
15877 </tr>
15878
15879 <tr>
15880 <td><code>on_delete</code></td>
15881 <td><code>ON DELETE</code> clause for object pointer member</td>
15882 <td><a href="#14.4.15">14.4.15</a></td>
15883 </tr>
15884
15885 <tr>
15886 <td><code>version</code></td>
15887 <td>member stores object version</td>
15888 <td><a href="#14.4.16">14.4.16</a></td>
15889 </tr>
15890
15891 <tr>
15892 <td><code>index</code></td>
15893 <td>define database index for a member</td>
15894 <td><a href="#14.4.17">14.4.17</a></td>
15895 </tr>
15896
15897 <tr>
15898 <td><code>unique</code></td>
15899 <td>define unique database index for a member</td>
15900 <td><a href="#14.4.18">14.4.18</a></td>
15901 </tr>
15902
15903 <tr>
15904 <td><code>unordered</code></td>
15905 <td>ordered container should be stored unordered</td>
15906 <td><a href="#14.4.19">14.4.19</a></td>
15907 </tr>
15908
15909 <tr>
15910 <td><code>table</code></td>
15911 <td>table name for a container</td>
15912 <td><a href="#14.4.20">14.4.20</a></td>
15913 </tr>
15914
15915 <tr>
15916 <td><code>load</code>/<code>update</code></td>
15917 <td>loading/updating behavior for a section</td>
15918 <td><a href="#14.4.21">14.4.21</a></td>
15919 </tr>
15920
15921 <tr>
15922 <td><code>section</code></td>
15923 <td>member belongs to a section</td>
15924 <td><a href="#14.4.22">14.4.22</a></td>
15925 </tr>
15926
15927 <tr>
15928 <td><code>added</code></td>
15929 <td>member is soft-added</td>
15930 <td><a href="#14.4.23">14.4.23</a></td>
15931 </tr>
15932
15933 <tr>
15934 <td><code>deleted</code></td>
15935 <td>member is soft-deleted</td>
15936 <td><a href="#14.4.24">14.4.24</a></td>
15937 </tr>
15938
15939 <tr>
15940 <td><code>index_type</code></td>
15941 <td>database type for a container's index type</td>
15942 <td><a href="#14.4.25">14.4.25</a></td>
15943 </tr>
15944
15945 <tr>
15946 <td><code>key_type</code></td>
15947 <td>database type for a container's key type</td>
15948 <td><a href="#14.4.26">14.4.26</a></td>
15949 </tr>
15950
15951 <tr>
15952 <td><code>value_type</code></td>
15953 <td>database type for a container's value type</td>
15954 <td><a href="#14.4.27">14.4.27</a></td>
15955 </tr>
15956
15957 <tr>
15958 <td><code>value_null</code>/<code>value_not_null</code></td>
15959 <td>container's value can/cannot be <code>NULL</code></td>
15960 <td><a href="#14.4.28">14.4.28</a></td>
15961 </tr>
15962
15963 <tr>
15964 <td><code>id_options</code></td>
15965 <td>database options for a container's id column</td>
15966 <td><a href="#14.4.29">14.4.29</a></td>
15967 </tr>
15968
15969 <tr>
15970 <td><code>index_options</code></td>
15971 <td>database options for a container's index column</td>
15972 <td><a href="#14.4.30">14.4.30</a></td>
15973 </tr>
15974
15975 <tr>
15976 <td><code>key_options</code></td>
15977 <td>database options for a container's key column</td>
15978 <td><a href="#14.4.31">14.4.31</a></td>
15979 </tr>
15980
15981 <tr>
15982 <td><code>value_options</code></td>
15983 <td>database options for a container's value column</td>
15984 <td><a href="#14.4.32">14.4.32</a></td>
15985 </tr>
15986
15987 <tr>
15988 <td><code>id_column</code></td>
15989 <td>column name for a container's object id</td>
15990 <td><a href="#14.4.33">14.4.33</a></td>
15991 </tr>
15992
15993 <tr>
15994 <td><code>index_column</code></td>
15995 <td>column name for a container's index</td>
15996 <td><a href="#14.4.34">14.4.34</a></td>
15997 </tr>
15998
15999 <tr>
16000 <td><code>key_column</code></td>
16001 <td>column name for a container's key</td>
16002 <td><a href="#14.4.35">14.4.35</a></td>
16003 </tr>
16004
16005 <tr>
16006 <td><code>value_column</code></td>
16007 <td>column name for a container's value</td>
16008 <td><a href="#14.4.36">14.4.36</a></td>
16009 </tr>
16010
16011 </table>
16012
16013 <p>Many of the member specifiers have corresponding value type
16014 specifiers with the same names (<a href="#14.3">Section 14.3,
16015 "Value Type Pragmas"</a>). The behavior of such specifiers
16016 for members is similar to that for value types. The only difference
16017 is the scope. A particular value type specifier applies to all the
16018 members of this value type that don't have a pre-member version
16019 of the specifier, while the member specifier always applies only
16020 to a single member. Also, with a few exceptions, member specifiers
16021 take precedence over and override parameters specified with value
16022 specifiers.</p>
16023
16024 <h3><a name="14.4.1">14.4.1 <code>id</code></a></h3>
16025
16026 <p>The <code>id</code> specifier specifies that the data member contains
16027 the object id. In a relational database, an identifier member is
16028 mapped to a primary key. For example:</p>
16029
16030 <pre class="cxx">
16031 #pragma db object
16032 class person
16033 {
16034 ...
16035
16036 #pragma db id
16037 std::string email_;
16038 };
16039 </pre>
16040
16041 <p>Normally, every persistent class has a data member designated as an
16042 object's identifier. However, it is possible to declare a
16043 persistent class without an id using the object <code>no_id</code>
16044 specifier (<a href="#14.1.6">Section 14.1.6, "<code>no_id</code>"</a>).</p>
16045
16046 <p>Note also that the <code>id</code> specifier cannot be used for data
16047 members of composite value types or views.</p>
16048
16049 <h3><a name="14.4.2">14.4.2 <code>auto</code></a></h3>
16050
16051 <p>The <code>auto</code> specifier specifies that the object's identifier
16052 is automatically assigned by the database. Only a member that was
16053 designated as an object id can have this specifier. For example:</p>
16054
16055 <pre class="cxx">
16056 #pragma db object
16057 class person
16058 {
16059 ...
16060
16061 #pragma db id auto
16062 unsigned long id_;
16063 };
16064 </pre>
16065
16066 <p>Note that automatically-assigned object ids are not reused.
16067 If you have a high object turnover (that is, objects are routinely
16068 made persistent and then erased), then care must be taken not to
16069 run out of object ids. In such situations, using
16070 <code>unsigned&nbsp;long&nbsp;long</code> as the identifier type
16071 is a safe choice.</p>
16072
16073 <p>For additional information on the automatic identifier assignment,
16074 refer to <a href="#3.8">Section 3.8, "Making Objects Persistent"</a>.</p>
16075
16076 <p>Note also that the <code>auto</code> specifier cannot be specified
16077 for data members of composite value types or views.</p>
16078
16079 <h3><a name="14.4.3">14.4.3 <code>type</code></a></h3>
16080
16081 <p>The <code>type</code> specifier specifies the native database type
16082 that should be used for the data member. For example:</p>
16083
16084 <pre class="cxx">
16085 #pragma db object
16086 class person
16087 {
16088 ...
16089
16090 #pragma db type("INT")
16091 bool married_;
16092 };
16093 </pre>
16094
16095 <p>The <code>null</code> and <code>not_null</code> (<a href="#14.4.6">Section
16096 14.4.6, "<code>null</code>/<code>not_null</code>"</a>) specifiers
16097 can be used to control the <code>NULL</code> semantics of a data member.
16098 It is also possible to specify the database type on the per-type instead
16099 of the per-member basis using the value <code>type</code>
16100 specifier (<a href="#14.3.1">Section 14.3.1, "<code>type</code>"</a>).</p>
16101
16102 <h3><a name="14.4.4">14.4.4 <code>id_type</code></a></h3>
16103
16104 <p>The <code>id_type</code> specifier specifies the native database type
16105 that should be used for the data member when it is part of an
16106 object identifier. This specifier only makes sense when applied to
16107 a member of a composite value type that is used for both id and
16108 non-id members. For example:</p>
16109
16110 <pre class="cxx">
16111 #pragma db value
16112 class name
16113 {
16114 ...
16115
16116 #pragma db type("VARCHAR(256)") id_type("VARCHAR(64)")
16117 std::string first_;
16118
16119 #pragma db type("VARCHAR(256)") id_type("VARCHAR(64)")
16120 std::string last_;
16121 };
16122
16123 #pragma db object
16124 class person
16125 {
16126 ...
16127
16128 #pragma db id
16129 name name_; // name_.first_, name_.last_ mapped to VARCHAR(64)
16130
16131 name alias_; // alias_.first_, alias_.last_ mapped to VARCHAR(256)
16132 };
16133 </pre>
16134
16135 <h3><a name="14.4.5">14.4.5 <code>get</code>/<code>set</code>/<code>access</code></a></h3>
16136
16137 <p>The <code>get</code> and <code>set</code> specifiers specify the
16138 data member accessor and modifier expressions, respectively. If
16139 provided, the generated database support code will use these
16140 expressions to access and modify the data member when performing
16141 database operations. The <code>access</code> specifier can be used
16142 as a shortcut to specify both the accessor and modifier if they
16143 happen to be the same.</p>
16144
16145 <p>In its simplest form the accessor or modifier expression can be
16146 just a name. Such a name should resolve either to another data
16147 member of the same type or to a suitable accessor or modifier
16148 member function. For example:</p>
16149
16150 <pre class="cxx">
16151 #pragma db object
16152 class person
16153 {
16154 ...
16155
16156 public:
16157 const std::string&amp; name () const;
16158 void name (const std::string&amp;);
16159 private:
16160 #pragma db access(name)
16161 std::string name_;
16162 };
16163 </pre>
16164
16165 <p>A suitable accessor function is a <code>const</code> member function
16166 that takes no arguments and whose return value can be implicitly
16167 converted to the <code>const</code> reference to the member type
16168 (<code>const&nbsp;std::string&amp;</code> in the example above).
16169 An accessor function that returns a <code>const</code> reference
16170 to the data member is called <em>by-reference accessor</em>.
16171 Otherwise, it is called <em>by-value accessor</em>.</p>
16172
16173 <p>A suitable modifier function can be of two forms. It can be the
16174 so called <em>by-reference modifier</em> which is a member function
16175 that takes no arguments and returns a non-<code>const</code> reference
16176 to the data member (<code>std::string&amp;</code> in the example above).
16177 Alternatively, it can be the so called <em>by-value modifier</em> which
16178 is a member function taking a single argument &mdash; the new value
16179 &mdash; that can be implicitly initialized from a variable of the member
16180 type (<code>std::string</code> in the example above). The return value
16181 of a by-value modifier, if any, is ignored. If both by-reference and
16182 by-value modifiers are available, then ODB prefers the by-reference
16183 version since it is more efficient. For example:</p>
16184
16185 <pre class="cxx">
16186 #pragma db object
16187 class person
16188 {
16189 ...
16190
16191 public:
16192 std::string get_name () const; // By-value accessor.
16193 std::string&amp; set_name (); // By-reference modifier.
16194 void set_name (std::string const&amp;); // By-value modifier.
16195 private:
16196 #pragma db get(get_name) \ // Uses by-value accessor.
16197 set(set_name) // Uses by-reference modifier.
16198 std::string name_;
16199 };
16200 </pre>
16201
16202 <p>Note that in many cases it is not necessary to specify accessor and
16203 modifier functions explicitly since the ODB compiler will try to
16204 discover them automatically in case the data member will be inaccessible
16205 to the generated code. In particular, in both of the above examples
16206 the ODB compiler would have successfully discovered the necessary
16207 functions. For more information on this functionality, refer to
16208 <a href="#3.2">Section 3.2, "Declaring Persistent Objects and
16209 Values"</a>.</p>
16210
16211 <p>Note also that by-value accessors and by-value modifiers cannot be
16212 used for certain data members in certain situations. These limitations
16213 are discussed in more detail later in this section.</p>
16214
16215 <p>Accessor and modifier expressions can be more elaborate than simple
16216 names. An accessor expression is any C++ expression that can be
16217 used to initialize a <code>const</code> reference to the member
16218 type. Similar to accessor functions, which are just a special case
16219 of accessor expressions, an accessor expression that evaluates to a
16220 <code>const</code> reference to the data member is called
16221 <em>by-reference accessor expression</em>. Otherwise, it is
16222 called <em>by-value accessor expression</em>.</p>
16223
16224 <p>Modifier expressions can also be of two forms: <em>by-reference
16225 modifier expression</em> and <em>by-value modifier expression</em>
16226 (again, modifier functions are just a special case of modifier
16227 expressions). A by-reference modifier expression is any C++
16228 expression that evaluates to the non-<code>const</code> reference
16229 to the member type. A by-value modifier expression can be a
16230 single or multiple (separated by semicolon) C++ statements
16231 with the effect of setting the new member value.</p>
16232
16233 <p>There are two special placeholders that are recognized by the
16234 ODB compiler in accessor and modifier expressions. The first
16235 is the <code>this</code> keyword which denotes a reference
16236 (note: not a pointer) to the persistent object. In accessor
16237 expressions this reference is <code>const</code> while in
16238 modifier expressions it is non-<code>const</code>. If an
16239 expression does not contain the <code>this</code> placeholder,
16240 then the ODB compiler automatically prefixes it with <code>this.</code>
16241 sequence.</p>
16242
16243 <p>The second placeholder, the <code>(?)</code> sequence, is used
16244 to denote the new value in by-value modifier expressions. The
16245 ODB compiler replaces the question mark with the variable name,
16246 keeping the surrounding parenthesis. The following example shows
16247 a few more interesting accessor and modifier expressions:</p>
16248
16249 <pre class="cxx">
16250 #pragma db value
16251 struct point
16252 {
16253 point (int, int);
16254
16255 int x;
16256 int y;
16257 };
16258
16259 #pragma db object
16260 class person
16261 {
16262 ...
16263
16264 public:
16265 const char* name () const;
16266 void name (const char*);
16267 private:
16268 #pragma db get(std::string (this.name ())) \
16269 set(name ((?).c_str ())) // The same as this.name (...).
16270 std::string name_;
16271
16272 public:
16273 const std::unique_ptr&lt;account>&amp; acc () const;
16274 void acc (std::unique_ptr&lt;account>);
16275 private:
16276 #pragma db set(acc (std::move (?)))
16277 std::unique_ptr&lt;account> acc_;
16278
16279 public:
16280 int loc_x () const
16281 int loc_y () const
16282 void loc_x (int);
16283 void loc_y (int);
16284 private:
16285 #pragma db get(point (this.loc_x (), this.loc_y ())) \
16286 set(this.loc_x ((?).x); this.loc_y ((?).y))
16287 point loc_;
16288 };
16289 </pre>
16290
16291 <p>When the data member is of an array type, then the terms "reference"
16292 and "member type" in the above discussion should be replaced with
16293 "pointer" and "array element type", respectively. That is, the accessor
16294 expression for an array member is any C++ expression that can be
16295 used to initialize a <code>const</code> pointer to the array
16296 element type, and so on. The following example shows common
16297 accessor and modifier signatures for array members:</p>
16298
16299 <pre class="cxx">
16300 #pragma db object
16301 class person
16302 {
16303 ...
16304
16305 public:
16306 const char* id () const; // By-reference accessor.
16307 void id (const char*); // By-value modifier.
16308 private:
16309 char id_[16];
16310
16311 public:
16312 const char* pub_key () const; // By-reference accessor.
16313 char* pub_key (); // By-reference modifier.
16314 private:
16315 char pub_key_[2048];
16316 };
16317 </pre>
16318
16319 <p>Accessor and modifier expressions can be used with data members
16320 of simple value, composite value, container, and object pointer
16321 types. They can be used for data members in persistent classes,
16322 composite value types, and views. There is also a mechanism
16323 related to accessors and modifiers called virtual data members
16324 and which is discussed in <a href="#14.4.13">Section 14.4.13,
16325 "<code>virtual</code>"</a>.</p>
16326
16327 <p>There are, however, certain limitations when it comes to using
16328 by-value accessor and modifier expressions. First of all, if a
16329 by-value modifier is used, then the data member type should be
16330 default-constructible. Furthermore, a composite value type that
16331 has a container member cannot be modified with a by-value modifier.
16332 Only a by-reference modifier expression can be used. The ODB
16333 compiler will detect such cases and issue diagnostics. For
16334 example:</p>
16335
16336 <pre class="cxx">
16337 #pragma db value
16338 struct name
16339 {
16340 std::string first_;
16341 std::string last_;
16342 std::vector&lt;std::string> aliases_;
16343 };
16344
16345 #pragma db object
16346 class person
16347 {
16348 ...
16349
16350 public:
16351 const name&amp; name () const;
16352 void name (const name&amp;);
16353 private:
16354 #pragma db access(name) // Error: by-value modifier.
16355 name name_;
16356 };
16357 </pre>
16358
16359 <p>In certain database systems it is also not possible to use by-value
16360 accessor and modifier expression with certain database types.
16361 The ODB compiler is only able to detect such cases and issue diagnostics
16362 if you specified accessor/modifier function names as opposed to custom
16363 expressions. For more information on these database and type-specific
16364 limitations, refer to the "Limitations" sections in <a href="#II">Part
16365 II, "Database Systems"</a>.</p>
16366
16367 <h3><a name="14.4.6">14.4.6 <code>null</code>/<code>not_null</code></a></h3>
16368
16369 <p>The <code>null</code> and <code>not_null</code> specifiers specify that
16370 the data member can or cannot be <code>NULL</code>, respectively.
16371 By default, data members of basic value types for which database
16372 mapping is provided by the ODB compiler do not allow <code>NULL</code>
16373 values while data members of object pointers allow <code>NULL</code>
16374 values. Other value types, such as those provided by the profile
16375 libraries (<a href="#III">Part III, "Profiles"</a>), may or may
16376 not allow <code>NULL</code> values, depending on the semantics
16377 of each value type. Consult the relevant documentation to find
16378 out more about the <code>NULL</code> semantics for such value
16379 types. A data member containing the object id (<a href="#14.4.1">Section
16380 14.4.1, "<code>id</code>"</a>) is automatically treated as not
16381 allowing a <code>NULL</code> value. Data members that
16382 allow <code>NULL</code> values are mapped in a relational database
16383 to columns that allow <code>NULL</code> values. For example:</p>
16384
16385 <pre class="cxx">
16386 using std::tr1::shared_ptr;
16387
16388 #pragma db object
16389 class person
16390 {
16391 ...
16392
16393 #pragma db null
16394 std::string name_;
16395 };
16396
16397 #pragma db object
16398 class account
16399 {
16400 ...
16401
16402 #pragma db not_null
16403 shared_ptr&lt;person> holder_;
16404 };
16405 </pre>
16406
16407 <p>The <code>NULL</code> semantics can also be specified on the
16408 per-type basis (<a href="#14.3.3">Section 14.3.3,
16409 "<code>null</code>/<code>not_null</code>"</a>). If both a type and
16410 a member have <code>null</code>/<code>not_null</code> specifiers,
16411 then the member specifier takes precedence. If a member specifier
16412 relaxes the <code>NULL</code> semantics (that is, if a member has
16413 the <code>null</code> specifier and the type has the explicit
16414 <code>not_null</code> specifier), then a warning is issued.</p>
16415
16416 <p>For a more detailed discussion of the <code>NULL</code> semantics
16417 for values, refer to <a href="#7.3">Section 7.3, "Pointers and
16418 <code>NULL</code> Value Semantics"</a>. For a more detailed
16419 discussion of the <code>NULL</code> semantics for object pointers,
16420 refer to <a href="#6">Chapter 6, "Relationships"</a>.</p>
16421
16422 <h3><a name="14.4.7">14.4.7 <code>default</code></a></h3>
16423
16424 <p>The <code>default</code> specifier specifies the database default value
16425 that should be used for the data member. For example:</p>
16426
16427 <pre class="cxx">
16428 #pragma db object
16429 class person
16430 {
16431 ...
16432
16433 #pragma db default(-1)
16434 int age_; // Mapped to INT NOT NULL DEFAULT -1.
16435 };
16436 </pre>
16437
16438 <p>A default value can be the special <code>null</code> keyword,
16439 a <code>bool</code> literal (<code>true</code> or <code>false</code>),
16440 an integer literal, a floating point literal, a string literal, or
16441 an enumerator name. If you need to specify a default value that is
16442 an expression, for example an SQL function call, then you can use
16443 the <code>options</code> specifier (<a href="#14.4.8">Section
16444 14.4.8, "<code>options</code>"</a>) instead. For example:</p>
16445
16446 <pre class="cxx">
16447 enum gender {male, female, undisclosed};
16448
16449 #pragma db object
16450 class person
16451 {
16452 ...
16453
16454 #pragma db default(null)
16455 odb::nullable&lt;std::string> middle_; // DEFAULT NULL
16456
16457 #pragma db default(false)
16458 bool married_; // DEFAULT 0/FALSE
16459
16460 #pragma db default(0.0)
16461 float weight_; // DEFAULT 0.0
16462
16463 #pragma db default("Mr")
16464 string title_; // DEFAULT 'Mr'
16465
16466 #pragma db default(undisclosed)
16467 gender gender_; // DEFAULT 2/'undisclosed'
16468
16469 #pragma db options("DEFAULT CURRENT_TIMESTAMP()")
16470 date timestamp_; // DEFAULT CURRENT_TIMESTAMP()
16471 };
16472 </pre>
16473
16474 <p>Default values specified as enumerators are only supported for
16475 members that are mapped to an <code>ENUM</code> or an integer
16476 type in the database, which is the case for the automatic
16477 mapping of C++ enums and enum classes to suitable database
16478 types as performed by the ODB compiler. If you have mapped
16479 a C++ enum or enum class to another database type, then you
16480 should use a literal corresponding to that type to specify
16481 the default value. For example:</p>
16482
16483 <pre class="cxx">
16484 enum gender {male, female, undisclosed};
16485 #pragma db value(gender) type("VARCHAR(11)")
16486
16487 #pragma db object
16488 class person
16489 {
16490 ...
16491
16492 #pragma db default("undisclosed")
16493 gender gender_; // DEFAULT 'undisclosed'
16494 };
16495 </pre>
16496
16497 <p>A default value can also be specified on the per-type basis
16498 (<a href="#14.3.4">Section 14.3.4, "<code>default</code>"</a>).
16499 An empty <code>default</code> specifier can be used to reset
16500 a default value that was previously specified on the per-type
16501 basis. For example:</p>
16502
16503 <pre class="cxx">
16504 #pragma db value(std::string) default("")
16505
16506 #pragma db object
16507 class person
16508 {
16509 ...
16510
16511 #pragma db default()
16512 std::string name_; // No default value.
16513 };
16514 </pre>
16515
16516 <p>A data member containing the object id (<a href="#14.4.1">Section
16517 14.4.1, "<code>id</code>"</a> ) is automatically treated as not
16518 having a default value even if its type specifies a default value.</p>
16519
16520 <p>Note also that default values do not affect the generated C++ code
16521 in any way. In particular, no automatic initialization of data members
16522 with their default values is performed at any point. If you need such
16523 an initialization, you will need to implement it yourself, for example,
16524 in your persistent class constructors. The default values only
16525 affect the generated database schemas and, in the context of ODB,
16526 are primarily useful for schema evolution.</p>
16527
16528 <p>Additionally, the <code>default</code> specifier cannot be specified
16529 for view data members.</p>
16530
16531 <h3><a name="14.4.8">14.4.8 <code>options</code></a></h3>
16532
16533 <p>The <code>options</code> specifier specifies additional column
16534 definition options that should be used for the data member. For
16535 example:</p>
16536
16537 <pre class="cxx">
16538 #pragma db object
16539 class person
16540 {
16541 ...
16542
16543 #pragma db options("CHECK(email != '')")
16544 std::string email_; // Mapped to TEXT NOT NULL CHECK(email != '').
16545 };
16546 </pre>
16547
16548 <p>Options can also be specified on the per-type basis
16549 (<a href="#14.3.5">Section 14.3.5, "<code>options</code>"</a>).
16550 By default, options are accumulating. That is, the ODB compiler
16551 first adds all the options specified for a value type followed
16552 by all the options specified for a data member. To clear the
16553 accumulated options at any point in this sequence you can use
16554 an empty <code>options</code> specifier. For example:</p>
16555
16556 <pre class="cxx">
16557 #pragma db value(std::string) options("COLLATE binary")
16558
16559 #pragma db object
16560 class person
16561 {
16562 ...
16563
16564 std::string first_; // TEXT NOT NULL COLLATE binary
16565
16566 #pragma db options("CHECK(email != '')")
16567 std::string last_; // TEXT NOT NULL COLLATE binary CHECK(email != '')
16568
16569 #pragma db options()
16570 std::string title_; // TEXT NOT NULL
16571
16572 #pragma db options() options("CHECK(email != '')")
16573 std::string email_; // TEXT NOT NULL CHECK(email != '')
16574 };
16575 </pre>
16576
16577 <p>ODB provides dedicated specifiers for specifying column types
16578 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>),
16579 <code>NULL</code> constraints (<a href="#14.4.6">Section 14.4.6,
16580 "<code>null</code>/<code>not_null</code>"</a>), and default
16581 values (<a href="#14.4.7">Section 14.4.7, "<code>default</code>"</a>).
16582 For ODB to function correctly these specifiers should always be
16583 used instead of the opaque <code>options</code> specifier for
16584 these components of a column definition.</p>
16585
16586 <p>Note also that the <code>options</code> specifier cannot be specified
16587 for view data members.</p>
16588
16589 <h3><a name="14.4.9">14.4.9 <code>column</code> (object, composite value)</a></h3>
16590
16591 <p>The <code>column</code> specifier specifies the column name
16592 that should be used to store the data member of a persistent class
16593 or composite value type in a relational database. For example:</p>
16594
16595 <pre class="cxx">
16596 #pragma db object
16597 class person
16598 {
16599 ...
16600
16601 #pragma db id column("person_id")
16602 unsigned long id_;
16603 };
16604 </pre>
16605
16606 <p>For a member of a composite value type, the <code>column</code> specifier
16607 specifies the column name prefix. Refer to <a href="#7.2.2">Section 7.2.2,
16608 "Composite Value Column and Table Names"</a> for details.</p>
16609
16610 <p>If the column name is not specified, it is derived from the member's
16611 so-called public name. A public member name is obtained by removing
16612 the common data member name decorations, such as leading and trailing
16613 underscores, the <code>m_</code> prefix, etc.</p>
16614
16615 <h3><a name="14.4.10">14.4.10 <code>column</code> (view)</a></h3>
16616
16617 <p>The <code>column</code> specifier can be used to specify the associated
16618 object data member, the potentially qualified column name, or the column
16619 expression for the data member of a view class. For more information,
16620 refer to <a href="#10.1">Section 10.1, "Object Views"</a> and
16621 <a href="#10.3">Section 10.3, "Table Views"</a>.</p>
16622
16623 <h3><a name="14.4.11">14.4.11 <code>transient</code></a></h3>
16624
16625 <p>The <code>transient</code> specifier instructs the ODB compiler
16626 not to store the data member in the database. For example:</p>
16627
16628 <pre class="cxx">
16629 #pragma db object
16630 class person
16631 {
16632 ...
16633
16634 date born_;
16635
16636 #pragma db transient
16637 unsigned short age_; // Computed from born_.
16638 };
16639 </pre>
16640
16641 <p>This pragma is usually used on computed members, pointers and
16642 references that are only meaningful in the application's
16643 memory, as well as utility members such as mutexes, etc.</p>
16644
16645 <h3><a name="14.4.12">14.4.12 <code>readonly</code></a></h3>
16646
16647 <p>The <code>readonly</code> specifier specifies that the data member of
16648 an object or composite value type is read-only. Changes to a read-only
16649 data member are ignored when updating the database state of an object
16650 (<a href="#3.10">Section 3.10, "Updating Persistent Objects"</a>)
16651 containing such a member. Since views are read-only, it is not
16652 necessary to use this specifier for view data members. Object id
16653 (<a href="#14.4.1">Section 14.4.1, "<code>id</code>"</a>)
16654 and inverse (<a href="#14.4.14">Section 14.4.14,
16655 "<code>inverse</code>"</a>) data members are automatically treated
16656 as read-only and must not be explicitly declared as such. For
16657 example:</p>
16658
16659 <pre class="cxx">
16660 #pragma db object
16661 class person
16662 {
16663 ...
16664
16665 #pragma db readonly
16666 date born_;
16667 };
16668 </pre>
16669
16670 <p>Besides simple value members, object pointer, container, and composite
16671 value members can also be declared read-only. A change of a pointed-to
16672 object is ignored when updating the state of a read-only object
16673 pointer. Similarly, any changes to the number or order of
16674 elements or to the element values themselves are ignored when
16675 updating the state of a read-only container. Finally, any changes
16676 to the members of a read-only composite value type are also ignored
16677 when updating the state of such a composite value.</p>
16678
16679 <p>ODB automatically treats <code>const</code> data members as read-only.
16680 For example, the following <code>person</code> object is equivalent
16681 to the above declaration for the database persistence purposes:</p>
16682
16683 <pre class="cxx">
16684 #pragma db object
16685 class person
16686 {
16687 ...
16688
16689 const date born_; // Automatically read-only.
16690 };
16691 </pre>
16692
16693 <p>When declaring an object pointer <code>const</code>, make sure to
16694 declare the pointer as <code>const</code> rather than (or in addition
16695 to) the object itself. For example:</p>
16696
16697 <pre class="cxx">
16698 #pragma db object
16699 class person
16700 {
16701 ...
16702
16703 const person* father_; // Read-write pointer to a read-only object.
16704 person* const mother_; // Read-only pointer to a read-write object.
16705 };
16706 </pre>
16707
16708 <p>Note that in case of a wrapper type (<a href="#7.3">Section 7.3,
16709 "Pointers and <code>NULL</code> Value Semantics"</a>), both the
16710 wrapper and the wrapped type must be <code>const</code> in
16711 order for the ODB compiler to automatically treat the data
16712 member as read-only. For example:</p>
16713
16714 <pre class="cxx">
16715 #pragma db object
16716 class person
16717 {
16718 ...
16719
16720 const std::auto_ptr&lt;const date> born_;
16721 };
16722 </pre>
16723
16724 <p>Read-only members are useful when dealing with
16725 asynchronous changes to the state of a data member in the
16726 database which should not be overwritten. In other cases,
16727 where the state of a data member never changes, declaring such a member
16728 read-only allows ODB to perform more efficient object updates.
16729 In such cases, however, it is conceptually more correct to
16730 declare such a data member as <code>const</code> rather than
16731 as read-only.</p>
16732
16733 <p>Note that it is also possible to declare composite value types
16734 (<a href="#14.3.6">Section 14.3.6, "<code>readonly</code>"</a>)
16735 as well as whole objects (<a href="#14.1.4">Section 14.1.4,
16736 "<code>readonly</code>"</a>) as read-only.</p>
16737
16738 <h3><a name="14.4.13">14.4.13 <code>virtual</code></a></h3>
16739
16740 <p>The <code>virtual</code> specifier is used to declare a virtual
16741 data member in an object, view, or composite value type. A virtual
16742 data member is an <em>imaginary</em> data member that is only
16743 used for the purpose of database persistence. A virtual data
16744 member does not actually exist (that is, occupy space) in the
16745 C++ class. Note also that virtual data members have nothing to
16746 do with C++ virtual functions or virtual inheritance. Specifically,
16747 no virtual function call overhead is incurred when using virtual
16748 data members.</p>
16749
16750 <p>To declare a virtual data member we must specify the data
16751 member name using the <code>member</code> specifier. We must
16752 also specify the data member type with the <code>virtual</code>
16753 specifier. Finally, the virtual data member declaration must
16754 also specify the accessor and modifier expressions, unless
16755 suitable accessor and modifier functions can automatically be
16756 found by the ODB compiler (<a href="#14.4.5">Section 14.4.5,
16757 "<code>get</code>/<code>set</code>/<code>access</code>"</a>).
16758 For example:</p>
16759
16760 <pre class="cxx">
16761 #pragma db object
16762 class person
16763 {
16764 ...
16765
16766 // Transient real data member that actually stores the data.
16767 //
16768 #pragma db transient
16769 std::string name_;
16770
16771 // Virtual data member.
16772 //
16773 #pragma db member(name) virtual(std::string) access(name_)
16774 };
16775 </pre>
16776
16777 <p>From the pragma language point of view, a virtual data member
16778 behaves exactly like a normal data member. Specifically, we
16779 can reference the virtual data member after it has been
16780 declared and use positioned pragmas before its declaration.
16781 For example:</p>
16782
16783 <pre class="cxx">
16784 #pragma db object
16785 class person
16786 {
16787 ...
16788
16789 #pragma db transient
16790 std::string name_;
16791
16792 #pragma db access(name_)
16793 #pragma db member(name) virtual(std::string)
16794 };
16795
16796 #pragma db member(person::name) column("person_name")
16797 #pragma db index member(person::name)
16798 </pre>
16799
16800 <p>We can also declare a virtual data member outside the class
16801 scope:</p>
16802
16803 <pre class="cxx">
16804 #pragma db object
16805 class person
16806 {
16807 ...
16808
16809 std::string name_;
16810 };
16811
16812 #pragma db member(person::name_) transient
16813 #pragma db member(person::name) virtual(std::string) access(name_)
16814 </pre>
16815
16816 <p>While in the above examples using virtual data members doesn't
16817 seem to yield any benefits, this mechanism can be useful in a
16818 number of situations. As one example, consider the need to
16819 aggregate or dis-aggregate a data member:</p>
16820
16821 <pre class="cxx">
16822 #pragma db object
16823 class person
16824 {
16825 ...
16826
16827 #pragma db transient
16828 std::pair&lt;std::string, std::string> name_;
16829
16830 #pragma db member(first) virtual(std::string) access(name_.first)
16831 #pragma db member(last) virtual(std::string) access(name_.second)
16832 };
16833 </pre>
16834
16835 <p>We can also use virtual data members to implement composite
16836 object ids that are spread over multiple data members:</p>
16837
16838 <pre class="cxx">
16839 #pragma db value
16840 struct name
16841 {
16842 name () {}
16843 name (std::string const&amp; f, std::string const&amp; l)
16844 : first (f), last(l) {}
16845
16846 std::string first;
16847 std::string last;
16848 };
16849
16850 #pragma db object
16851 class person
16852 {
16853 ...
16854
16855 #pragma db transient
16856 std::string first_;
16857
16858 #pragma db transient
16859 std::string last_;
16860
16861 #pragma db member(name) virtual(name) id \
16862 get(::name (this.first_, this.last_)) \
16863 set(this.first_ = (?).first; this.last_ = (?).last)
16864 };
16865 </pre>
16866
16867 <p>Another common situation that calls for virtual data members is
16868 a class that uses the pimpl idiom. While the following code
16869 fragment outlines the idea, for details refer to the
16870 <code>pimpl</code> example in the <code>odb-examples</code>
16871 package.</p>
16872
16873 <pre class="cxx">
16874 #pragma db object
16875 class person
16876 {
16877 public:
16878 std::string const&amp; name () const;
16879 void name (std::string const&amp;);
16880
16881 unsigned short age () const;
16882 void age (unsigned short);
16883
16884 ...
16885
16886 private:
16887 class impl;
16888
16889 #pragma db transient
16890 impl* pimpl_;
16891
16892 #pragma db member(name) virtual(std::string) // Uses name().
16893 #pragma db member(age) virtual(unsigned short) // Uses age().
16894 };
16895 </pre>
16896
16897 <p>The above example also shows that names used for virtual data
16898 members (<code>name</code> and <code>age</code> in our case) can
16899 be the same as the names of accessor/modifier functions. The only
16900 names that virtual data members cannot clash with are those of
16901 other data members, virtual or real.</p>
16902
16903 <p>A common pattern in the above examples is the need to
16904 declare the real data member that actually stores the
16905 data as transient. If all the real data members in a
16906 class are treated as transient, then we can use the
16907 class-level <code>transient</code> specifier
16908 (<a href="#14.1.12">Section 14.1.12, "<code>transient</code>
16909 (object)"</a>,
16910 <a href="#14.3.8">Section 14.3.8, "<code>transient</code>
16911 (composite value)"</a>,
16912 <a href="#14.2.7">Section 14.2.7, "<code>transient</code>
16913 (view)"</a>)
16914 instead of doing it for each individual member. For example: </p>
16915
16916 <pre class="cxx">
16917 #pragma db object transient
16918 class person
16919 {
16920 ...
16921
16922 std::string first_; // Transient.
16923 std::string last_; // Transient.
16924
16925 #pragma db member(name) virtual(name) ...
16926 };
16927 </pre>
16928
16929 <p>The ability to treat all the real data members as transient
16930 becomes more important if we don't know the names of these
16931 data members. This is often the case when we are working
16932 with third-party types that document the accessor and
16933 modifier functions but not the names of their private data
16934 members. As an example, consider the <code>point</code> class
16935 defined in a third-party <code>&lt;point></code> header file:</p>
16936
16937 <pre class="cxx">
16938 class point
16939 {
16940 public:
16941 point ();
16942 point (int x, int y);
16943
16944 int x () const;
16945 int y () const;
16946
16947 void x (int);
16948 void y (int);
16949
16950 private:
16951 ...
16952 };
16953 </pre>
16954
16955 <p>To convert this class to an ODB composite value type we could
16956 create the <code>point-mapping.hxx</code> file with the following
16957 content:</p>
16958
16959 <pre class="cxx">
16960 #include &lt;point>
16961
16962 #pragma db value(point) transient definition
16963 #pragma db member(point::x) virtual(int)
16964 #pragma db member(point::y) virtual(int)
16965 </pre>
16966
16967 <p>Virtual data members can be of simple value, composite value,
16968 container, or object pointer types. They can be used in persistent
16969 classes, composite value types, and views.</p>
16970
16971 <h3><a name="14.4.14">14.4.14 <code>inverse</code></a></h3>
16972
16973 <p>The <code>inverse</code> specifier specifies that the data member of
16974 an object pointer or a container of object pointers type is an
16975 inverse side of a bidirectional object relationship. The single
16976 required argument to this specifier is the corresponding data
16977 member name in the referenced object. For example:</p>
16978
16979 <pre class="cxx">
16980 using std::tr1::shared_ptr;
16981 using std::tr1::weak_ptr;
16982
16983 class person;
16984
16985 #pragma db object pointer(shared_ptr)
16986 class employer
16987 {
16988 ...
16989
16990 std::vector&lt;shared_ptr&lt;person> > employees_;
16991 };
16992
16993 #pragma db object pointer(shared_ptr)
16994 class person
16995 {
16996 ...
16997
16998 #pragma db inverse(employee_)
16999 weak_ptr&lt;employer> employer_;
17000 };
17001 </pre>
17002
17003 <p>An inverse member does not have a corresponding column or, in case
17004 of a container, table in the resulting database schema. Instead, the
17005 column or table from the referenced object is used to retrieve the
17006 relationship information. Only ordered and set containers can be used
17007 for inverse members. If an inverse member is of an ordered container
17008 type, it is automatically marked as unordered
17009 (<a href="#14.4.19">Section 14.4.19, "<code>unordered</code>"</a>).</p>
17010
17011 <p>For a more detailed discussion of inverse members, refer to
17012 <a href="#6.2">Section 6.2, "Bidirectional Relationships"</a>.</p>
17013
17014 <h3><a name="14.4.15">14.4.15 <code>on_delete</code></a></h3>
17015
17016 <p>The <code>on_delete</code> specifier specifies the on-delete semantics
17017 for a data member of an object pointer or a container of object
17018 pointers type. The single required argument to this specifier must
17019 be either <code>cascade</code> or <code>set_null</code>.</p>
17020
17021 <p>The <code>on_delete</code> specifier is translated directly to the
17022 corresponding <code>ON DELETE</code> SQL clause. That is, if
17023 <code>cascade</code> is specified, then when a pointed-to object
17024 is erased from the database, the database state of the pointing
17025 object is automatically erased as well. If <code>set_null</code> is
17026 specified, then when a pointed-to object is erased from the database,
17027 the database state of the pointing object is automatically updated
17028 to set the pointer column to <code>NULL</code>. For example:</p>
17029
17030 <pre class="cxx">
17031 #pragma db object
17032 class employer
17033 {
17034 ...
17035
17036 #pragma db id auto
17037 unsigned long id_;
17038 };
17039
17040 #pragma db object
17041 class person
17042 {
17043 ...
17044
17045 #pragma db on_delete(cascade)
17046 employer* employer_;
17047 };
17048
17049 unsigned long id;
17050
17051 {
17052 employer e;
17053 person p;
17054 p.employer_ = &amp;e;
17055
17056 transaction t (db.begin ());
17057
17058 id = db.persist (e);
17059 db.persist (p);
17060
17061 t.commit ();
17062 }
17063
17064 {
17065 transaction t (db.begin ());
17066
17067 // Database state of the person object is erased as well.
17068 //
17069 db.erase&lt;employer> (id);
17070
17071 t.commit ();
17072 }
17073 </pre>
17074
17075
17076 <p>Note that this is a database-level functionality and care must be
17077 taken in order not to end up with inconsistent object states in the
17078 application's memory and database. The following example illustrates
17079 the kind of problems one may encounter:</p>
17080
17081 <pre class="cxx">
17082 #pragma db object
17083 class employer
17084 {
17085 ...
17086 };
17087
17088 #pragma db object
17089 class person
17090 {
17091 ...
17092
17093 #pragma db on_delete(set_null)
17094 employer* employer_;
17095 };
17096
17097 employer e;
17098 person p;
17099 p.employer_ = &amp;e;
17100
17101 {
17102 transaction t (db.begin ());
17103 db.persist (e);
17104 db.persist (p);
17105 t.commit ();
17106 }
17107
17108 {
17109 transaction t (db.begin ());
17110
17111 // The employer column is set to NULL in the database but
17112 // not the p.employer_ data member in the application.
17113 //
17114 db.erase (e);
17115 t.commit ();
17116 }
17117
17118 {
17119 transaction t (db.begin ());
17120
17121 // Override the employer column with an invalid pointer.
17122 //
17123 db.update (p);
17124
17125 t.commit ();
17126 }
17127 </pre>
17128
17129 <p>Note that even optimistic concurrency will not resolve such
17130 issues unless you are using database-level support for optimistic
17131 concurrency as well (for example, <code>ROWVERSION</code> in SQL
17132 Server).</p>
17133
17134 <p>The <code>on_delete</code> specifier is only valid for non-inverse
17135 object pointer data members. If the <code>set_null</code> semantics
17136 is used, then the pointer must allow the <code>NULL</code> value.</p>
17137
17138 <h3><a name="14.4.16">14.4.16 <code>version</code></a></h3>
17139
17140 <p>The <code>version</code> specifier specifies that the data member stores
17141 the object version used to support optimistic concurrency. If a class
17142 has a version data member, then it must also be declared as having the
17143 optimistic concurrency model using the <code>optimistic</code> pragma
17144 (<a href="#14.1.5">Section 14.1.5, "<code>optimistic</code>"</a>). For
17145 example:</p>
17146
17147 <pre class="cxx">
17148 #pragma db object optimistic
17149 class person
17150 {
17151 ...
17152
17153 #pragma db version
17154 unsigned long version_;
17155 };
17156 </pre>
17157
17158 <p>A version member must be of an integral C++ type and must map to
17159 an integer or similar database type. Note also that object versions
17160 are not reused. If you have a high update frequency, then care must
17161 be taken not to run out of versions. In such situations, using
17162 <code>unsigned&nbsp;long&nbsp;long</code> as the version type is a safe
17163 choice.</p>
17164
17165 <p>For a more detailed discussion of optimistic concurrency, refer to
17166 <a href="#12">Chapter 12, "Optimistic Concurrency"</a>.</p>
17167
17168 <h3><a name="14.4.17">14.4.17 <code>index</code></a></h3>
17169
17170 <p>The <code>index</code> specifier instructs the ODB compiler to define
17171 a database index for the data member. For example:</p>
17172
17173 <pre class="cxx">
17174 #pragma db object
17175 class person
17176 {
17177 ...
17178
17179 #pragma db index
17180 std::string name_;
17181 };
17182 </pre>
17183
17184 <p>For more information on defining database indexes, refer to
17185 <a href="#14.7">Section 14.7, "Index Definition Pragmas"</a>.</p>
17186
17187 <h3><a name="14.4.18">14.4.18 <code>unique</code></a></h3>
17188
17189 <p>The <code>index</code> specifier instructs the ODB compiler to define
17190 a unique database index for the data member. For example:</p>
17191
17192 <pre class="cxx">
17193 #pragma db object
17194 class person
17195 {
17196 ...
17197
17198 #pragma db unique
17199 std::string name_;
17200 };
17201 </pre>
17202
17203 <p>For more information on defining database indexes, refer to
17204 <a href="#14.7">Section 14.7, "Index Definition Pragmas"</a>.</p>
17205
17206 <h3><a name="14.4.19">14.4.19 <code>unordered</code></a></h3>
17207
17208 <p>The <code>unordered</code> specifier specifies that the member of
17209 an ordered container type should be stored unordered in the database.
17210 The database table for such a member will not contain the index column
17211 and the order in which elements are retrieved from the database may
17212 not be the same as the order in which they were stored. For example:</p>
17213
17214 <pre class="cxx">
17215 #pragma db object
17216 class person
17217 {
17218 ...
17219
17220 #pragma db unordered
17221 std::vector&lt;std::string> nicknames_;
17222 };
17223 </pre>
17224
17225 <p>For a more detailed discussion of ordered containers and their
17226 storage in the database, refer to <a href="#5.1">Section 5.1,
17227 "Ordered Containers"</a>.</p>
17228
17229 <h3><a name="14.4.20">14.4.20 <code>table</code></a></h3>
17230
17231 <p>The <code>table</code> specifier specifies the table name that should
17232 be used to store the contents of the container member. For example:</p>
17233
17234 <pre class="cxx">
17235 #pragma db object
17236 class person
17237 {
17238 ...
17239
17240 #pragma db table("nicknames")
17241 std::vector&lt;std::string> nicknames_;
17242 };
17243 </pre>
17244
17245 <p>If the table name is not specified, then the container table name
17246 is constructed by concatenating the object's table name, underscore,
17247 and the public member name. The public member name is obtained
17248 by removing the common member name decorations, such as leading and
17249 trailing underscores, the <code>m_</code> prefix, etc. In the example
17250 above, without the <code>table</code> specifier, the container's
17251 table name would have been <code>person_nicknames</code>.</p>
17252
17253 <p>The <code>table</code> specifier can also be used for members of
17254 composite value types. In this case it specifies the table name
17255 prefix for container members inside the composite value type. Refer
17256 to <a href="#7.2.2">Section 7.2.2, "Composite Value Column and Table
17257 Names"</a> for details.</p>
17258
17259 <p>The container table name can be qualified with a database
17260 schema, for example:</p>
17261
17262 <pre class="cxx">
17263 #pragma db object
17264 class person
17265 {
17266 ...
17267
17268 #pragma db table("extras.nicknames")
17269 std::vector&lt;std::string> nicknames_;
17270 };
17271 </pre>
17272
17273 <p>For more information on database schemas and the format of the
17274 qualified names, refer to <a href="#14.1.8">Section 14.1.8,
17275 "<code>schema</code>"</a>.</p>
17276
17277 <h3><a name="14.4.21">14.4.21 <code>load</code>/<code>update</code></a></h3>
17278
17279 <p>The <code>load</code> and <code>update</code> specifiers specify the
17280 loading and updating behavior for an object section, respectively.
17281 Valid values for the <code>load</code> specifier are
17282 <code>eager</code> (default) and <code>lazy</code>. Valid values for
17283 the <code>update</code> specifier are <code>always</code> (default),
17284 <code>change</code>, and <code>manual</code>. For more information
17285 on object sections, refer to <a href="#9">Chapter 9, "Sections"</a>.</p>
17286
17287 <h3><a name="14.4.22">14.4.22 <code>section</code></a></h3>
17288
17289 <p>The <code>section</code> specifier indicates that a data member
17290 of a persistent class belongs to an object section. The single
17291 required argument to this specifier is the name of the section
17292 data member. This specifier can only be used on direct data
17293 members of a persistent class. For more information on object
17294 sections, refer to <a href="#9">Chapter 9, "Sections"</a>.</p>
17295
17296 <h3><a name="14.4.23">14.4.23 <code>added</code></a></h3>
17297
17298 <p>The <code>added</code> specifier marks the data member as
17299 soft-added. The single required argument to this specifier is
17300 the addition version. For more information on this functionality,
17301 refer to <a href="#13.4">Section 13.4, "Soft Object Model
17302 Changes"</a>.</p>
17303
17304 <h3><a name="14.4.24">14.4.24 <code>deleted</code></a></h3>
17305
17306 <p>The <code>deleted</code> specifier marks the data member as
17307 soft-deleted. The single required argument to this specifier is
17308 the deletion version. For more information on this functionality,
17309 refer to <a href="#13.4">Section 13.4, "Soft Object Model
17310 Changes"</a>.</p>
17311
17312 <h3><a name="14.4.25">14.4.25 <code>index_type</code></a></h3>
17313
17314 <p>The <code>index_type</code> specifier specifies the native
17315 database type that should be used for an ordered container's
17316 index column of the data member. The semantics of <code>index_type</code>
17317 are similar to those of the <code>type</code> specifier
17318 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>). The native
17319 database type is expected to be an integer type. For example:</p>
17320
17321 <pre class="cxx">
17322 #pragma db object
17323 class person
17324 {
17325 ...
17326
17327 #pragma db index_type("SMALLINT UNSIGNED")
17328 std::vector&lt;std::string> nicknames_;
17329 };
17330 </pre>
17331
17332 <h3><a name="14.4.26">14.4.26 <code>key_type</code></a></h3>
17333
17334 <p>The <code>key_type</code> specifier specifies the native
17335 database type that should be used for a map container's
17336 key column of the data member. The semantics of <code>key_type</code>
17337 are similar to those of the <code>type</code> specifier
17338 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>). For
17339 example:</p>
17340
17341 <pre class="cxx">
17342 #pragma db object
17343 class person
17344 {
17345 ...
17346
17347 #pragma db key_type("INT UNSIGNED")
17348 std::map&lt;unsigned short, float> age_weight_map_;
17349 };
17350 </pre>
17351
17352 <h3><a name="14.4.27">14.4.27 <code>value_type</code></a></h3>
17353
17354 <p>The <code>value_type</code> specifier specifies the native
17355 database type that should be used for a container's
17356 value column of the data member. The semantics of <code>value_type</code>
17357 are similar to those of the <code>type</code> specifier
17358 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>). For
17359 example:</p>
17360
17361 <pre class="cxx">
17362 #pragma db object
17363 class person
17364 {
17365 ...
17366
17367 #pragma db value_type("VARCHAR(255)")
17368 std::vector&lt;std::string> nicknames_;
17369 };
17370 </pre>
17371
17372 <p>The <code>value_null</code> and <code>value_not_null</code>
17373 (<a href="#14.4.28">Section 14.4.28,
17374 "<code>value_null</code>/<code>value_not_null</code>"</a>) specifiers
17375 can be used to control the <code>NULL</code> semantics of a value
17376 column.</p>
17377
17378 <h3><a name="14.4.28">14.4.28 <code>value_null</code>/<code>value_not_null</code></a></h3>
17379
17380 <p>The <code>value_null</code> and <code>value_not_null</code> specifiers
17381 specify that a container's element value for the data member can or
17382 cannot be <code>NULL</code>, respectively. The semantics of
17383 <code>value_null</code> and <code>value_not_null</code> are similar
17384 to those of the <code>null</code> and <code>not_null</code> specifiers
17385 (<a href="#14.4.6">Section 14.4.6, "<code>null</code>/<code>not_null</code>"</a>).
17386 For example:</p>
17387
17388 <pre class="cxx">
17389 using std::tr1::shared_ptr;
17390
17391 #pragma db object
17392 class person
17393 {
17394 ...
17395 };
17396
17397 #pragma db object
17398 class account
17399 {
17400 ...
17401
17402 #pragma db value_not_null
17403 std::vector&lt;shared_ptr&lt;person> > holders_;
17404 };
17405 </pre>
17406
17407 <p>For set and multiset containers (<a href="#5.2">Section 5.2, "Set and
17408 Multiset Containers"</a>) the element value is automatically treated
17409 as not allowing a <code>NULL</code> value.</p>
17410
17411 <h3><a name="14.4.29">14.4.29 <code>id_options</code></a></h3>
17412
17413 <p>The <code>id_options</code> specifier specifies additional
17414 column definition options that should be used for a container's
17415 id column of the data member. For example:</p>
17416
17417 <pre class="cxx">
17418 #pragma db object
17419 class person
17420 {
17421 ...
17422
17423 #pragma db id options("COLLATE binary")
17424 std::string name_;
17425
17426 #pragma db id_options("COLLATE binary")
17427 std::vector&lt;std::string> nicknames_;
17428 };
17429 </pre>
17430
17431 <p>The semantics of <code>id_options</code> are similar to those
17432 of the <code>options</code> specifier (<a href="#14.4.8">Section
17433 14.4.8, "<code>options</code>"</a>).</p>
17434
17435 <h3><a name="14.4.30">14.4.30 <code>index_options</code></a></h3>
17436
17437 <p>The <code>index_options</code> specifier specifies additional
17438 column definition options that should be used for a container's
17439 index column of the data member. For example:</p>
17440
17441 <pre class="cxx">
17442 #pragma db object
17443 class person
17444 {
17445 ...
17446
17447 #pragma db index_options("ZEROFILL")
17448 std::vector&lt;std::string> nicknames_;
17449 };
17450 </pre>
17451
17452 <p>The semantics of <code>index_options</code> are similar to those
17453 of the <code>options</code> specifier (<a href="#14.4.8">Section
17454 14.4.8, "<code>options</code>"</a>).</p>
17455
17456 <h3><a name="14.4.31">14.4.31 <code>key_options</code></a></h3>
17457
17458 <p>The <code>key_options</code> specifier specifies additional
17459 column definition options that should be used for a container's
17460 key column of the data member. For example:</p>
17461
17462 <pre class="cxx">
17463 #pragma db object
17464 class person
17465 {
17466 ...
17467
17468 #pragma db key_options("COLLATE binary")
17469 std::map&lt;std::string, std::string> properties_;
17470 };
17471 </pre>
17472
17473 <p>The semantics of <code>key_options</code> are similar to those
17474 of the <code>options</code> specifier (<a href="#14.4.8">Section
17475 14.4.8, "<code>options</code>"</a>).</p>
17476
17477 <h3><a name="14.4.32">14.4.32 <code>value_options</code></a></h3>
17478
17479 <p>The <code>value_options</code> specifier specifies additional
17480 column definition options that should be used for a container's
17481 value column of the data member. For example:</p>
17482
17483 <pre class="cxx">
17484 #pragma db object
17485 class person
17486 {
17487 ...
17488
17489 #pragma db value_options("COLLATE binary")
17490 std::set&lt;std::string> nicknames_;
17491 };
17492 </pre>
17493
17494 <p>The semantics of <code>value_options</code> are similar to those
17495 of the <code>options</code> specifier (<a href="#14.4.8">Section
17496 14.4.8, "<code>options</code>"</a>).</p>
17497
17498 <h3><a name="14.4.33">14.4.33 <code>id_column</code></a></h3>
17499
17500 <p>The <code>id_column</code> specifier specifies the column
17501 name that should be used to store the object id in a
17502 container's table for the data member. The semantics of
17503 <code>id_column</code> are similar to those of the
17504 <code>column</code> specifier
17505 (<a href="#14.4.9">Section 14.4.9, "<code>column</code>"</a>).
17506 For example:</p>
17507
17508 <pre class="cxx">
17509 #pragma db object
17510 class person
17511 {
17512 ...
17513
17514 #pragma db id_column("person_id")
17515 std::vector&lt;std::string> nicknames_;
17516 };
17517 </pre>
17518
17519 <p>If the column name is not specified, then <code>object_id</code>
17520 is used by default.</p>
17521
17522 <h3><a name="14.4.34">14.4.34 <code>index_column</code></a></h3>
17523
17524 <p>The <code>index_column</code> specifier specifies the column
17525 name that should be used to store the element index in an
17526 ordered container's table for the data member. The semantics of
17527 <code>index_column</code> are similar to those of the
17528 <code>column</code> specifier
17529 (<a href="#14.4.9">Section 14.4.9, "<code>column</code>"</a>).
17530 For example:</p>
17531
17532 <pre class="cxx">
17533 #pragma db object
17534 class person
17535 {
17536 ...
17537
17538 #pragma db index_column("nickname_number")
17539 std::vector&lt;std::string> nicknames_;
17540 };
17541 </pre>
17542
17543 <p>If the column name is not specified, then <code>index</code>
17544 is used by default.</p>
17545
17546 <h3><a name="14.4.35">14.4.35 <code>key_column</code></a></h3>
17547
17548 <p>The <code>key_column</code> specifier specifies the column
17549 name that should be used to store the key in a map
17550 container's table for the data member. The semantics of
17551 <code>key_column</code> are similar to those of the
17552 <code>column</code> specifier
17553 (<a href="#14.4.9">Section 14.4.9, "<code>column</code>"</a>).
17554 For example:</p>
17555
17556 <pre class="cxx">
17557 #pragma db object
17558 class person
17559 {
17560 ...
17561
17562 #pragma db key_column("age")
17563 std::map&lt;unsigned short, float> age_weight_map_;
17564 };
17565 </pre>
17566
17567 <p>If the column name is not specified, then <code>key</code>
17568 is used by default.</p>
17569
17570 <h3><a name="14.4.36">14.4.36 <code>value_column</code></a></h3>
17571
17572 <p>The <code>value_column</code> specifier specifies the column
17573 name that should be used to store the element value in a
17574 container's table for the data member. The semantics of
17575 <code>value_column</code> are similar to those of the
17576 <code>column</code> specifier
17577 (<a href="#14.4.9">Section 14.4.9, "<code>column</code>"</a>).
17578 For example:</p>
17579
17580 <pre class="cxx">
17581 #pragma db object
17582 class person
17583 {
17584 ...
17585
17586 #pragma db value_column("weight")
17587 std::map&lt;unsigned short, float> age_weight_map_;
17588 };
17589 </pre>
17590
17591 <p>If the column name is not specified, then <code>value</code>
17592 is used by default.</p>
17593
17594 <h2><a name="14.5">14.5 Namespace Pragmas</a></h2>
17595
17596 <p>A pragma with the <code>namespace</code> qualifier describes a
17597 C++ namespace. Similar to other qualifiers, <code>namespace</code>
17598 can also refer to a named C++ namespace, for example:</p>
17599
17600 <pre class="cxx">
17601 namespace test
17602 {
17603 ...
17604 }
17605
17606 #pragma db namespace(test) ...
17607 </pre>
17608
17609 <p>To refer to the global namespace in the <code>namespace</code>
17610 qualifier the following special syntax is used:</p>
17611
17612 <pre class="cxx">
17613 #pragma db namespace() ....
17614 </pre>
17615
17616 <p>The <code>namespace</code> qualifier can be optionally followed,
17617 in any order, by one or more specifiers summarized in the
17618 table below:</p>
17619
17620 <!-- border="1" is necessary for html2ps -->
17621 <table class="specifiers" border="1">
17622 <tr>
17623 <th>Specifier</th>
17624 <th>Summary</th>
17625 <th>Section</th>
17626 </tr>
17627
17628 <tr>
17629 <td><code>pointer</code></td>
17630 <td>pointer type for persistent classes and views inside a namespace</td>
17631 <td><a href="#14.5.1">14.5.1</a></td>
17632 </tr>
17633
17634 <tr>
17635 <td><code>table</code></td>
17636 <td>table name prefix for persistent classes inside a namespace</td>
17637 <td><a href="#14.5.2">14.5.2</a></td>
17638 </tr>
17639
17640 <tr>
17641 <td><code>schema</code></td>
17642 <td>database schema for persistent classes inside a namespace</td>
17643 <td><a href="#14.5.3">14.5.3</a></td>
17644 </tr>
17645
17646 <tr>
17647 <td><code>session</code></td>
17648 <td>enable/disable session support for persistent classes inside a namespace</td>
17649 <td><a href="#14.5.4">14.5.4</a></td>
17650 </tr>
17651
17652 </table>
17653
17654 <h3><a name="14.5.1">14.5.1 <code>pointer</code></a></h3>
17655
17656 <p>The <code>pointer</code> specifier specifies the default pointer
17657 type for persistent classes and views inside the namespace. For
17658 example:</p>
17659
17660 <pre class="cxx">
17661 #pragma db namespace pointer(std::tr1::shared_ptr)
17662 namespace accounting
17663 {
17664 #pragma db object
17665 class employee
17666 {
17667 ...
17668 };
17669
17670 #pragma db object
17671 class employer
17672 {
17673 ...
17674 };
17675 }
17676 </pre>
17677
17678 <p>There are only two valid ways to specify a pointer with the
17679 <code>pointer</code> specifier at the namespace level. We can
17680 specify the template name of a smart pointer in which
17681 case the ODB compiler will automatically append the class
17682 name as a template argument. Or we can use <code>*</code>
17683 to denote a raw pointer.</p>
17684
17685 <p>Note also that we can always override the default pointer
17686 specified at the namespace level for any persistent class
17687 or view inside this namespace. For example:</p>
17688
17689 <pre class="cxx">
17690 #pragma db namespace pointer(std::unique_ptr)
17691 namespace accounting
17692 {
17693 #pragma db object pointer(std::shared_ptr)
17694 class employee
17695 {
17696 ...
17697 };
17698
17699 #pragma db object
17700 class employer
17701 {
17702 ...
17703 };
17704 }
17705 </pre>
17706
17707 <p>For a more detailed discussion of object and view pointers, refer
17708 to <a href="#3.3">Section 3.3, "Object and View Pointers"</a>.</p>
17709
17710 <h3><a name="14.5.2">14.5.2 <code>table</code></a></h3>
17711
17712 <p>The <code>table</code> specifier specifies a table prefix
17713 that should be added to table names of persistent classes inside
17714 the namespace. For example:</p>
17715
17716 <pre class="cxx">
17717 #pragma db namespace table("acc_")
17718 namespace accounting
17719 {
17720 #pragma db object table("employees")
17721 class employee
17722 {
17723 ...
17724 };
17725
17726 #pragma db object table("employers")
17727 class employer
17728 {
17729 ...
17730 };
17731 }
17732 </pre>
17733
17734 <p>In the above example the resulting table names will be
17735 <code>acc_employees</code> and <code>acc_employers</code>.</p>
17736
17737 <p>The table name prefix can also be specified with the
17738 <code>--table-prefix</code> ODB compiler option. Note
17739 that table prefixes specified at the namespace level as well
17740 as with the command line option are accumulated. For example:</p>
17741
17742 <pre class="cxx">
17743 #pragma db namespace() table("audit_")
17744
17745 #pragma db namespace table("hr_")
17746 namespace hr
17747 {
17748 #pragma db object table("employees")
17749 class employee
17750 {
17751 ...
17752 };
17753 }
17754
17755 #pragma db object table("employers")
17756 class employer
17757 {
17758 ...
17759 };
17760 </pre>
17761
17762 <p>If we compile the above example with the
17763 <code>--table-prefix&nbsp;test_</code> option, then the
17764 <code>employee</code> class table will be called
17765 <code>test_audit_hr_employees</code> and <code>employer</code> &mdash;
17766 <code>test_audit_employers</code>.</p>
17767
17768 <p>Table prefixes can be used as an alternative to database schemas
17769 (<a href="#14.1.8">Section 14.1.8, "<code>schema</code>"</a>) if
17770 the target database system does not support schemas.</p>
17771
17772 <h3><a name="14.5.3">14.5.3 <code>schema</code></a></h3>
17773
17774 <p>The <code>schema</code> specifier specifies a database schema
17775 that should be used for persistent classes inside the namespace.
17776 For more information on specifying a database schema refer to
17777 <a href="#14.1.8">Section 14.1.8, "<code>schema</code>"</a>.</p>
17778
17779 <h3><a name="14.5.4">14.5.4 <code>session</code></a></h3>
17780
17781 <p>The <code>session</code> specifier specifies whether to enable
17782 session support for persistent classes inside the namespace. For
17783 example:</p>
17784
17785 <pre class="cxx">
17786 #pragma db namespace session
17787 namespace hr
17788 {
17789 #pragma db object // Enabled.
17790 class employee
17791 {
17792 ...
17793 };
17794
17795 #pragma db object session(false) // Disabled.
17796 class employer
17797 {
17798 ...
17799 };
17800 }
17801 </pre>
17802
17803 <p>Session support is disabled by default unless the
17804 <code>--generate-session</code> ODB compiler option is specified.
17805 Session support specified at the namespace level can be overridden
17806 on the per object basis (<a href="#14.1.10">Section 14.1.10,
17807 "<code>session</code>"</a>). For more information on sessions,
17808 refer to <a href="#11">Chapter 11, "Session"</a>.</p>
17809
17810 <h2><a name="14.6">14.6 Object Model Pragmas</a></h2>
17811
17812 <p>A pragma with the <code>model</code> qualifier describes the
17813 whole C++ object model. For example:</p>
17814
17815 <pre class="cxx">
17816 #pragma db model ...
17817 </pre>
17818
17819 <p>The <code>model</code> qualifier can be followed, in any order,
17820 by one or more specifiers summarized in the table below:</p>
17821
17822 <!-- border="1" is necessary for html2ps -->
17823 <table class="specifiers" border="1">
17824 <tr>
17825 <th>Specifier</th>
17826 <th>Summary</th>
17827 <th>Section</th>
17828 </tr>
17829
17830 <tr>
17831 <td><code>version</code></td>
17832 <td>object model version</td>
17833 <td><a href="#14.6.1">14.6.1</a></td>
17834 </tr>
17835
17836 </table>
17837
17838 <h3><a name="14.6.1">14.6.1 <code>version</code></a></h3>
17839
17840 <p>The <code>version</code> specifier specifies the object model
17841 version when schema evolution support is used. The first two
17842 required arguments to this specifier are the base and current
17843 model versions, respectively. The third optional argument
17844 specifies whether the current version is open for changes.
17845 Valid values for this argument are <code>open</code> (the
17846 default) and <code>closed</code>. For more information on
17847 this functionality, refer to <a href="#13">Chapter 13,
17848 "Database Schema Evolution"</a>.</p>
17849
17850
17851 <h2><a name="14.7">14.7 Index Definition Pragmas</a></h2>
17852
17853 <p>While it is possible to manually add indexes to the generated
17854 database schema, it is more convenient to do this as part of
17855 the persistent class definitions. A pragma with the <code>index</code>
17856 qualifier describes a database index. It has the following
17857 general format:</p>
17858
17859 <pre class="cxx">
17860 #pragma db index[("&lt;name>")] \
17861 [unique|type("&lt;type>")] \
17862 [method("&lt;method>")] \
17863 [options("&lt;index-options>")] \
17864 member(&lt;name>[, "&lt;column-options>"])... \
17865 members(&lt;name>[,&lt;name>...])...
17866 </pre>
17867
17868 <p>The <code>index</code> qualifier can optionally specify the
17869 index name. If the index name is not specified, then one is
17870 automatically derived by appending the <code>_i</code> suffix
17871 to the column name of the index member. If the name is not
17872 specified and the index contains multiple members, then the
17873 index definition is invalid.</p>
17874
17875 <p>The optional <code>type</code>, <code>method</code>, and
17876 <code>options</code> clauses specify the index type, for
17877 example <code>UNIQUE</code>, index method, for example
17878 <code>BTREE</code>, and index options, respectively. The
17879 <code>unique</code> clause is a shortcut for
17880 <code>type("UNIQUE")</code>. Note that not all database
17881 systems support specifying an index method or options.
17882 For more information on the database system-specific index
17883 types, methods, and options, refer to <a href="#II">Part II,
17884 "Database Systems"</a>.</p>
17885
17886 <p>To specify index members we can use the <code>member</code>
17887 or <code>members</code> clauses, or a mix of the two. The
17888 <code>member</code> clause allows us to specify a single
17889 index member with optional column options, for example,
17890 <code>"ASC"</code>. If we need to create a composite
17891 index that contains multiple members, then we can repeat
17892 the <code>member</code> clause several times or, if the
17893 members don't have any column options, we can use a single
17894 <code>members</code> clause instead. Similar to the index
17895 type, method, and options, the format of column options is
17896 database system-specific. For more details, refer to
17897 <a href="#II">Part II, "Database Systems"</a>.</p>
17898
17899 <p>The following code fragment shows some typical examples
17900 of index definitions:</p>
17901
17902 <pre class="cxx">
17903 #pragma db object
17904 class object
17905 {
17906 ...
17907
17908 int x;
17909 int y;
17910 int z1;
17911 int z2;
17912
17913 // An index for member x with automatically-assigned name x_i.
17914 //
17915 #pragma db index member(x)
17916
17917 // A unique index named y_index for member y which is sorted in
17918 // the descending order. The index is using the BTREE method.
17919 //
17920 #pragma db index("y_index") unique method("BTREE") member(y, "DESC")
17921
17922 // A composite BITMAP index named z_i for members z1 and z2.
17923 //
17924 #pragma db index("z_i") type("BITMAP") members(z1, z2)
17925 };
17926 </pre>
17927
17928 <p>ODB also offers a shortcut for defining an index with the default
17929 method and options for a single data member. Such an index can
17930 be defined using the <code>index</code> (<a href="#14.4.17">Section
17931 14.4.17, "<code>index</code>"</a>) or <code>unique</code>
17932 (<a href="#14.4.18">Section 14.4.18, "<code>unique</code>"</a>)
17933 member specifier. For example:</p>
17934
17935 <pre class="cxx">
17936 #pragma db object
17937 class object
17938 {
17939 ...
17940
17941 #pragma db index
17942 int x;
17943
17944 #pragma db type("INT") unique
17945 int y;
17946 };
17947 </pre>
17948
17949 <p>The above example is semantically equivalent to the following
17950 more verbose version:</p>
17951
17952 <pre class="cxx">
17953 #pragma db object
17954 class object
17955 {
17956 ...
17957
17958 int x;
17959
17960 #pragma db type("INT")
17961 int y;
17962
17963 #pragma db index member(x)
17964 #pragma db index unique member(y)
17965 };
17966 </pre>
17967
17968 <p>While it is convenient to define an index inside a persistent
17969 class, it is also possible to do that out of the class body. In this
17970 case, the index name, if specified, must be prefixed with the
17971 potentially-qualified class name. For example:</p>
17972
17973 <pre class="cxx">
17974 namespace n
17975 {
17976 #pragma db object
17977 class object
17978 {
17979 ...
17980
17981 int x;
17982 int y;
17983 };
17984
17985 // An index for member x in persistent class object with automatically-
17986 // assigned name x_i.
17987 //
17988 #pragma db index(object) member(x)
17989 }
17990
17991 // An index named y_index for member y in persistent class n::object.
17992 //
17993 #pragma db index(n::object::"y_index") member(y)
17994 </pre>
17995
17996 <p>It is possible to define an index on a member that is of a
17997 composite value type or on some of its nested members. For
17998 example:</p>
17999
18000 <pre class="cxx">
18001 #pragma db value
18002 struct point
18003 {
18004 int x;
18005 int y;
18006 int z;
18007 };
18008
18009 #pragma db object
18010 class object
18011 {
18012 // An index that includes all of the p1's nested members.
18013 //
18014 #pragma db index
18015 point p1;
18016
18017 point p2;
18018
18019 // An index that includes only p2.x and p2.y.
18020 //
18021 #pragma db index("p2_xy_i") members(p2.x, p2.y)
18022 };
18023 </pre>
18024
18025 <p>When generating a schema for a container member (<a href="#5">Chapter 5,
18026 "Containers"</a>), ODB automatically defines two indexes on the container
18027 table. One is for the object id that references the object table and the
18028 other is for the index column in case the container is ordered
18029 (<a href="#5.1">Section 5.1, "Ordered Containers"</a>). By default these
18030 indexes use the default index name, type, method, and options. The
18031 <code>index</code> pragma allows us to customize these two indexes by
18032 recognizing the special <code>id</code> and <code>index</code> nested
18033 member names when specified after a container member. For example:</p>
18034
18035 <pre class="cxx">
18036 #pragma db object
18037 class object
18038 {
18039 std::vector&lt;int> v;
18040
18041 // Change the container id index name.
18042 //
18043 #pragma db index("id_index") member(v.id)
18044
18045 // Change the container index index method.
18046 //
18047 #pragma db index method("BTREE") member(v.index)
18048 };
18049 </pre>
18050
18051 <h2><a name="14.8">14.8 Database Type Mapping Pragmas</a></h2>
18052
18053 <p>A pragma with the <code>map</code> qualifier describes a
18054 mapping between two database types. For each database system
18055 ODB provides built-in support for a core set of database types,
18056 such as integers, strings, binary, etc. However, many database
18057 systems provide extended types such as geospatial types,
18058 user-defined types, and collections (arrays, table types,
18059 key-value stores, etc). In order to support such extended types,
18060 ODB allows us to map them to one of the built-in types, normally
18061 a string or a binary. Given the text or binary representation
18062 of the data we can then extract it into our chosen C++ data type
18063 and thus establish a mapping between an extended database type and
18064 its C++ equivalent.</p>
18065
18066 <p>The <code>map</code> pragma has the following format:</p>
18067
18068 <pre class="cxx">
18069 #pragma db map type("regex") as("subst") [to("subst")] [from("subst")]
18070 </pre>
18071
18072 <p>The <code>type</code> clause specifies the name of the database type
18073 that we are mapping. We will refer to it as the <em>mapped type</em>
18074 from now on. The name of the mapped type is a Perl-like regular
18075 expression pattern that is matched in the case-insensitive mode.</p>
18076
18077 <p>The <code>as</code> clause specifies the name of the database type
18078 that we are mapping the mapped type to. We will refer to it as
18079 the <em>interface type</em> from now on. The name of the interface
18080 type is a regular expression substitution and should expand to a
18081 name of a database type for which ODB provides built-in support.</p>
18082
18083 <p>The optional <code>to</code> and <code>from</code> clauses specify the
18084 database conversion expressions between the mapped type and the
18085 interface type. The <code>to</code> expression converts from the
18086 interface type to the mapped type and <code>from</code> converts
18087 in the other direction. If no explicit conversion is required for
18088 either direction, then the corresponding clause can be omitted.
18089 The conversion expressions are regular expression substitutions.
18090 They must contain the special <code>(?)</code> placeholder which will
18091 be replaced with the actual value to be converted. Turning on SQL
18092 statement tracing (<a href="#3.13">Section 3.13, "Tracing SQL
18093 Statement Execution"</a>) can be useful for debugging conversion
18094 expressions. This allows you to see the substituted expressions
18095 as used in the actual statements.</p>
18096
18097 <p>As an example, the following <code>map</code> pragma maps the
18098 PostgreSQL array of <code>INTEGER</code>'s to <code>TEXT</code>:</p>
18099
18100 <pre class="cxx">
18101 #pragma db map type("INTEGER *\\[(\\d*)\\]") \
18102 as("TEXT") \
18103 to("(?)::INTEGER[$1]") \
18104 from("(?)::TEXT")
18105 </pre>
18106
18107 <p>With the above mapping we can now have a persistent class that
18108 has a member of the PostgreSQL array type:</p>
18109
18110 <pre class="cxx">
18111 #pragma db object
18112 class object
18113 {
18114 ...
18115
18116 #pragma db type("INTEGER[]")
18117 std::string array_;
18118 };
18119 </pre>
18120
18121 <p>In PostgreSQL the array literal has the <code>{n1,n2,...}</code> form.
18122 As a result, we need to make sure that we pass the correct text
18123 representation in the <code>array_</code> member, for example:</p>
18124
18125 <pre class="cxx">
18126 object o;
18127 o.array_ = "{1,2,3}";
18128 db.persist (o);
18129 </pre>
18130
18131 <p>Of course, <code>std::string</code> is not the most natural
18132 representation of an array of integers in C++. Instead,
18133 <code>std::vector&lt;int></code> would have been much more
18134 appropriate. To add support for mapping
18135 <code>std::vector&lt;int></code> to PostgreSQL <code>INTEGER[]</code>
18136 we need to provide a <code>value_traits</code> specialization
18137 that implements conversion between the PostgreSQL text representation
18138 of an array and <code>std::vector&lt;int></code>. Below is a sample
18139 implementation:</p>
18140
18141 <pre class="cxx">
18142 namespace odb
18143 {
18144 namespace pgsql
18145 {
18146 template &lt;>
18147 class value_traits&lt;std::vector&lt;int>, id_string>
18148 {
18149 public:
18150 typedef std::vector&lt;int> value_type;
18151 typedef value_type query_type;
18152 typedef details::buffer image_type;
18153
18154 static void
18155 set_value (value_type&amp; v,
18156 const details::buffer&amp; b,
18157 std::size_t n,
18158 bool is_null)
18159 {
18160 v.clear ();
18161
18162 if (!is_null)
18163 {
18164 char c;
18165 std::istringstream is (std::string (b.data (), n));
18166
18167 is >> c; // '{'
18168
18169 for (c = static_cast&lt;char> (is.peek ()); c != '}'; is >> c)
18170 {
18171 v.push_back (int ());
18172 is >> v.back ();
18173 }
18174 }
18175 }
18176
18177 static void
18178 set_image (details::buffer&amp; b,
18179 std::size_t&amp; n,
18180 bool&amp; is_null,
18181 const value_type&amp; v)
18182 {
18183 is_null = false;
18184 std::ostringstream os;
18185
18186 os &lt;&lt; '{';
18187
18188 for (value_type::const_iterator i (v.begin ()), e (v.end ());
18189 i != e;)
18190 {
18191 os &lt;&lt; *i;
18192
18193 if (++i != e)
18194 os &lt;&lt; ',';
18195 }
18196
18197 os &lt;&lt; '}';
18198
18199 const std::string&amp; s (os.str ());
18200 n = s.size ();
18201
18202 if (n > b.capacity ())
18203 b.capacity (n);
18204
18205 std::memcpy (b.data (), s.c_str (), n);
18206 }
18207 };
18208 }
18209 }
18210 </pre>
18211
18212 <p>Once this specialization is included in the generated code (see
18213 the <code>mapping</code> example in the <code>odb-examples</code>
18214 package for details), we can use <code>std::vector&lt;int></code>
18215 instead of <code>std::string</code> in our persistent class:</p>
18216
18217 <pre class="cxx">
18218 #pragma db object
18219 class object
18220 {
18221 ...
18222
18223 #pragma db type("INTEGER[]")
18224 std::vector&lt;int> array_;
18225 };
18226 </pre>
18227
18228 <p>If we wanted to always map <code>std::vector&lt;int></code>
18229 to PostgreSQL <code>INTEGER[]</code>, then we could instead
18230 write:</p>
18231
18232 <pre class="cxx">
18233 typedef std::vector&lt;int> int_vector;
18234 #pragma db value(int_vector) type("INTEGER[]")
18235
18236 #pragma db object
18237 class object
18238 {
18239 ...
18240
18241 std::vector&lt;int> array_; // Mapped to INTEGER[].
18242 };
18243 </pre>
18244
18245 <p>While the above example only shows how to handle PostgreSQL arrays,
18246 other types in PostgreSQL and in other databases can be supported
18247 in a similar way. The <code>odb-tests</code> package contains a
18248 set of tests in the <code>&lt;database>/custom</code> directories that,
18249 for each database, shows how to provide custom mapping for some of
18250 the extended types.</p>
18251
18252 <h2><a name="14.9">14.9 C++ Compiler Warnings</a></h2>
18253
18254 <p>When a C++ header file defining persistent classes and containing
18255 ODB pragmas is used to build the application, the C++ compiler may
18256 issue warnings about pragmas that it doesn't recognize. There
18257 are several ways to deal with this problem. The easiest is to
18258 disable such warnings using one of the compiler-specific command
18259 line options or warning control pragmas. This method is described
18260 in the following sub-section for popular C++ compilers.</p>
18261
18262 <p>There are also several C++ compiler-independent methods that we
18263 can employ. The first is to use the <code>PRAGMA_DB</code> macro,
18264 defined in <code>&lt;odb/core.hxx></code>, instead of using
18265 <code>#pragma&nbsp;db</code> directly. This macro expands to the
18266 ODB pragma when compiled with the ODB compiler and to an empty
18267 declaration when compiled with other compilers. The following example
18268 shows how we can use this macro:</p>
18269
18270 <pre class="cxx">
18271 #include &lt;odb/core.hxx>
18272
18273 PRAGMA_DB(object)
18274 class person
18275 {
18276 ...
18277
18278 PRAGMA_DB(id)
18279 unsigned long id_;
18280 };
18281 </pre>
18282
18283 <p>An alternative to using the <code>PRAGMA_DB</code> macro is to
18284 group the <code>#pragma&nbsp;db</code> directives in blocks that are
18285 conditionally included into compilation only when compiled with the
18286 ODB compiler. For example:</p>
18287
18288 <pre class="cxx">
18289 class person
18290 {
18291 ...
18292
18293 unsigned long id_;
18294 };
18295
18296 #ifdef ODB_COMPILER
18297 # pragma db object(person)
18298 # pragma db member(person::id_) id
18299 #endif
18300 </pre>
18301
18302 <p>The disadvantage of this approach is that it can quickly become
18303 overly verbose when positioned pragmas are used.</p>
18304
18305 <h3><a name="14.9.1">14.9.1 GNU C++</a></h3>
18306
18307 <p>GNU g++ does not issue warnings about unknown pragmas
18308 unless requested with the <code>-Wall</code> command line option.
18309 To disable only the unknown pragma warning, we can add the
18310 <code>-Wno-unknown-pragmas</code> option after <code>-Wall</code>,
18311 for example:</p>
18312
18313 <pre class="terminal">
18314 g++ -Wall -Wno-unknown-pragmas ...
18315 </pre>
18316
18317 <h3><a name="14.9.2">14.9.2 Visual C++</a></h3>
18318
18319 <p>Microsoft Visual C++ issues an unknown pragma warning (C4068) at
18320 warning level 1 or higher. This means that unless we have disabled
18321 the warnings altogether (level 0), we will see this warning.</p>
18322
18323 <p>To disable this warning via the compiler command line, we can add
18324 the <code>/wd4068</code> C++ compiler option in Visual Studio 2008
18325 and earlier. In Visual Studio 2010 and later there is now a special
18326 GUI field where we can enter warning numbers that should be disabled.
18327 Simply enter 4068 into this field.</p>
18328
18329 <p>We can also disable this warning for only a specific header or
18330 a fragment of a header using the warning control pragma. For
18331 example:</p>
18332
18333 <pre class="cxx">
18334 #include &lt;odb/core.hxx>
18335
18336 #pragma warning (push)
18337 #pragma warning (disable:4068)
18338
18339 #pragma db object
18340 class person
18341 {
18342 ...
18343
18344 #pragma db id
18345 unsigned long id_;
18346 };
18347
18348 #pragma warning (pop)
18349 </pre>
18350
18351 <h3><a name="14.9.3">14.9.3 Sun C++</a></h3>
18352
18353 <p>The Sun C++ compiler does not issue warnings about unknown pragmas
18354 unless the <code>+w</code> or <code>+w2</code> option is specified.
18355 To disable only the unknown pragma warning we can add the
18356 <code>-erroff=unknownpragma</code> option anywhere on the
18357 command line, for example:</p>
18358
18359 <pre class="terminal">
18360 CC +w -erroff=unknownpragma ...
18361 </pre>
18362
18363 <h3><a name="14.9.4">14.9.4 IBM XL C++</a></h3>
18364
18365 <p>IBM XL C++ issues an unknown pragma warning (1540-1401) by default.
18366 To disable this warning we can add the <code>-qsuppress=1540-1401</code>
18367 command line option, for example:</p>
18368
18369 <pre class="terminal">
18370 xlC -qsuppress=1540-1401 ...
18371 </pre>
18372
18373 <h3><a name="14.9.5">14.9.5 HP aC++</a></h3>
18374
18375 <p>HP aC++ (aCC) issues an unknown pragma warning (2161) by default.
18376 To disable this warning we can add the <code>+W2161</code>
18377 command line option, for example:</p>
18378
18379 <pre class="terminal">
18380 aCC +W2161 ...
18381 </pre>
18382
18383 <h3><a name="14.9.6">14.9.6 Clang</a></h3>
18384
18385 <p>Clang does not issue warnings about unknown pragmas
18386 unless requested with the <code>-Wall</code> command line option.
18387 To disable only the unknown pragma warning, we can add the
18388 <code>-Wno-unknown-pragmas</code> option after <code>-Wall</code>,
18389 for example:</p>
18390
18391 <pre class="terminal">
18392 clang++ -Wall -Wno-unknown-pragmas ...
18393 </pre>
18394
18395 <p>We can also disable this warning for only a specific header or
18396 a fragment of a header using the warning control pragma. For
18397 example:</p>
18398
18399 <pre class="cxx">
18400 #include &lt;odb/core.hxx>
18401
18402 #pragma clang diagnostic push
18403 #pragma clang diagnostic ignored "-Wunknown-pragmas"
18404
18405 #pragma db object
18406 class person
18407 {
18408 ...
18409
18410 #pragma db id
18411 unsigned long id_;
18412 };
18413
18414 #pragma clang diagnostic pop
18415 </pre>
18416
18417
18418 <!-- CHAPTER -->
18419
18420
18421 <hr class="page-break"/>
18422 <h1><a name="15">15 Advanced Techniques and Mechanisms</a></h1>
18423
18424 <p>This chapter covers more advanced techniques and mechanisms
18425 provided by ODB that may be useful in certain situations.</p>
18426
18427 <h2><a name="15.1">15.1 Transaction Callbacks</a></h2>
18428
18429 <p>The ODB transaction class (<code>odb::transaction</code>) allows
18430 an application to register a callback that will be called after
18431 the transaction is finalized, that is, committed or rolled back.
18432 This mechanism can be used, for example, to restore values that
18433 were updated during the transaction execution to their original
18434 states if the transaction is rolled back.</p>
18435
18436 <p>The callback management interface of the <code>transaction</code>
18437 class is shown below.</p>
18438
18439 <pre class="cxx">
18440 namespace odb
18441 {
18442 class transaction
18443 {
18444 ...
18445
18446 public:
18447 static const unsigned short event_commit = 0x01;
18448 static const unsigned short event_rollback = 0x02;
18449 static const unsigned short event_all = event_commit | event_rollback;
18450
18451 typedef void (*callback_type) (
18452 unsigned short event, void* key, unsigned long long data);
18453
18454 void
18455 callback_register (callback_type callback,
18456 void* key,
18457 unsigned short event = event_all,
18458 unsigned long long data = 0,
18459 transaction** state = 0);
18460
18461
18462 void
18463 callback_unregister (void* key);
18464
18465 void
18466 callback_update (void* key,
18467 unsigned short event,
18468 unsigned long long data = 0,
18469 transaction** state = 0);
18470 }
18471 }
18472 </pre>
18473
18474 <p>The <code>callback_register()</code> function registers a
18475 post-commit/rollback callback. The <code>callback</code>
18476 argument is the function that should be called. The
18477 <code>key</code> argument is used by the transaction
18478 to identify this callback. It is also normally used
18479 to pass an address of the data object on which the
18480 callback function will work. The <code>event</code>
18481 argument is the bitwise-or of the events that should
18482 trigger the callback.</p>
18483
18484 <p>The optional data argument can be used to store any POD
18485 user data that doesn't exceed 8 bytes in size and doesn't require
18486 alignment greater than <code>unsigned long long</code>. For
18487 example, we could store an old value of a flag or a counter
18488 that needs to be restored in case of a roll back.</p>
18489
18490 <p>The optional <code>state</code> argument can be used to
18491 indicate that the callback has been unregistered because
18492 the transaction was finalized. In this case the transaction
18493 automatically resets the passed pointer to 0. This is
18494 primarily useful if we are interested in only one of
18495 the events (commit or rollback).</p>
18496
18497 <p>The <code>callback_unregister()</code> function unregisters a previously
18498 registered callback. If the number of registered callbacks is
18499 large, then this can be a slow operation. Generally, the callback
18500 mechanism is optimized for cases where the callbacks stay
18501 registered until the transaction is finalized.</p>
18502
18503 <p>Note also that you don't need to unregister a callback that has
18504 been called or auto-reset using the <code>state</code> argument
18505 passed to <code>callback_register()</code>. This function does nothing
18506 if the key is not found.</p>
18507
18508 <p>The <code>callback_update()</code> function can be used to update
18509 the <code>event</code>, <code>data</code>, and <code>state</code>
18510 values of a previously registered callback. Similar to
18511 <code>callback_unregister()</code>, this is a potentially slow
18512 operation.</p>
18513
18514 <p>When the callback is called, it is passed the event that
18515 triggered it, as well as the <code>key</code> and
18516 <code>data</code> values that were passed to the
18517 <code>callback_register()</code> function. Note also that the order
18518 in which the callbacks are called is unspecified. The rollback
18519 event can be triggered by an exception. In this case, if the
18520 callback throws, the program will be terminated.</p>
18521
18522 <p>The following example shows how we can use transaction
18523 callbacks together with database operation callbacks
18524 (<a href="#14.1.7">Section 14.1.7, "<code>callback</code>"</a>)
18525 to manage the object's "dirty" flag.</p>
18526
18527 <pre class="cxx">
18528 #include &lt;odb/callback.hxx>
18529 #include &lt;odb/transaction.hxx>
18530
18531 #pragma db object callback(update)
18532 class object
18533 {
18534 ...
18535
18536 #pragma db transient
18537 mutable bool dirty_;
18538
18539 // Non-NULL value indicates that we are registered
18540 // with this transaction.
18541 //
18542 #pragma db transient
18543 mutable odb::transaction* tran_;
18544
18545 void
18546 update (odb::callback_event e, odb::database&amp;) const
18547 {
18548 using namespace odb::core;
18549
18550 if (e == callback_event::post_update)
18551 return;
18552
18553 // Mark the object as clean again but register a
18554 // transaction callback in case the update is rolled
18555 // back.
18556 //
18557 tran_ = &amp;transaction::current ();
18558 tran_->callback_register (&amp;rollback,
18559 const_cast&lt;object*> (this),
18560 transaction::event_rollback,
18561 0,
18562 &amp;tran_);
18563 dirty_ = false;
18564 }
18565
18566 static void
18567 rollback (unsigned short, void* key, unsigned long long)
18568 {
18569 // Restore the dirty flag since the changes have been
18570 // rolled back.
18571 //
18572 object&amp; o (*static_cast&lt;object*> (key));
18573 o.dirty_ = true;
18574 }
18575
18576 ~object ()
18577 {
18578 // Unregister the callback if we are going away before
18579 // the transaction.
18580 //
18581 if (tran_ != 0)
18582 tran_->callback_unregister (this);
18583 }
18584 };
18585 </pre>
18586
18587 <h2><a name="15.2">15.2 Persistent Class Template Instantiations</a></h2>
18588
18589 <p>Similar to composite value types (<a href="#7.2">Section 7.2, "Composite
18590 Value Types"</a>), a persistent object can be defined as an instantiation
18591 of a C++ class template, for example:</p>
18592
18593 <pre class="cxx">
18594 template &lt;typename T>
18595 class person
18596 {
18597 ...
18598
18599 T first_;
18600 T last_;
18601 };
18602
18603 typedef person&lt;std::string> std_person;
18604
18605 #pragma db object(std_person)
18606 #pragma db member(std_person::last_) id
18607 </pre>
18608
18609 <p>Note that the database support code for such a persistent object
18610 is generated when compiling the header containing the
18611 <code>db&nbsp;object</code> pragma and not the header containing
18612 the template definition or the <code>typedef</code> name. This
18613 allows us to use templates defined in other files, for example:</p>
18614
18615 <pre class="cxx">
18616 #include &lt;utility> // std::pair
18617
18618 typedef std::pair&lt;unsigned int, std::string> person;
18619 #pragma db object(person)
18620 #pragma db member(person::first) id auto column("id")
18621 #pragma db member(person::second) column("name")
18622 </pre>
18623
18624 <p>You may also have to explicitly specify the object type in
18625 calls to certain <code>database</code> class functions due
18626 to the inability do distinguish, at the API level, between
18627 smart pointers and persistent objects defined as class
18628 template instantiations. For example:</p>
18629
18630 <pre class="cxx">
18631 person p;
18632
18633 db.update (p); // Error.
18634 db.reload (p); // Error.
18635 db.erase (p); // Error.
18636
18637 db.update&lt;person> (p); // Ok.
18638 db.reload&lt;person> (p); // Ok.
18639 db.erase&lt;person> (p); // Ok.
18640 </pre>
18641
18642 <p>It also makes sense to factor persistent data members that do not
18643 depend on template arguments into a common, non-template base class.
18644 The following more realistic example illustrates this approach:</p>
18645
18646 <pre class="cxx">
18647 #pragma db object abstract
18648 class base_common
18649 {
18650 ...
18651
18652 #pragma db id auto
18653 unsigned long id;
18654 };
18655
18656 template &lt;typename T>
18657 class base: public base_common
18658 {
18659 ...
18660
18661 T value;
18662 };
18663
18664 typedef base&lt;std::string> string_base;
18665 #pragma db object(string_base) abstract
18666
18667 #pragma db object
18668 class derived: public string_base
18669 {
18670 ...
18671 };
18672 </pre>
18673
18674 <h2><a name="15.3">15.3 Bulk Database Operations</a></h2>
18675
18676 <p>Some database systems supported by ODB provide a mechanism, often
18677 called bulk or batch statement execution, that allows us to execute
18678 the same SQL statement on multiple sets of data at once and with a
18679 single database API call. This often results in significantly
18680 better performance if we need to execute the same statement for a
18681 large number of data sets (thousands to millions).</p>
18682
18683 <p>ODB translates this mechanism to bulk operations which allow
18684 us to persist, update, or erase a range of objects in the database.
18685 Currently, from all the database systems supported by ODB, only
18686 Oracle and Microsoft SQL Server are capable of bulk operations.
18687 There is also currently no emulation of the bulk API for other
18688 databases nor dynamic multi-database support. As a result, if
18689 you are using dynamic multi-database support, you will need to
18690 "drop down" to static support in order to access the bulk API.
18691 Refer to <a href="#16">Chapter 16, "Multi-Database Support"</a>
18692 for details.</p>
18693
18694 <p>As we will discuss later in this section, bulk operations have
18695 complex failure semantics that is dictated by the underlying
18696 database API. As a result, support for bulk persist, update,
18697 and erase is limited to persistent classes for which these
18698 operations can be performed with a single database statement
18699 execution. In particular, bulk operations are not available
18700 for polymorphic objects (<a href="#8.2">Section 8.2,
18701 "Polymorphism Inheritance"</a>) or objects that have
18702 containers (inverse containers of object pointers are an
18703 exception). Furthermore, for objects that have sections
18704 (<a href="#9">Chapter 9, "Sections"</a>) the bulk update operation
18705 will only be available if all the sections are manually-updated.
18706 On the other hand, bulk operations are supported for objects
18707 that use optimistic concurrency (<a href="#12">Chapter 12,
18708 "Optimistic Concurrency"</a>) or have no object id
18709 (<a href="#14.1.6">Section 14.1.6, "<code>no_id</code>"</a>).</p>
18710
18711 <p>To enable the generation of bulk operation support for a persistent
18712 class we use the <code>bulk</code> pragma. For example:</p>
18713
18714 <pre class="cxx">
18715 #pragma db object bulk(5000)
18716 class person
18717 {
18718 ...
18719
18720 #pragma db id auto
18721 unsigned long id;
18722 };
18723 </pre>
18724
18725 <p>The single argument to the <code>bulk</code> pragma is the batch
18726 size. The batch size specifies the maximum number of data sets
18727 that should be handled with a single underlying statement execution.
18728 If the range that we want to perform the bulk operation on contains
18729 more objects than the batch size, then ODB will split this operation
18730 into multiple underlying statement executions (batches). To illustrate
18731 this point with an example, suppose we want to persist 53,000 objects
18732 and the batch size is 5,000. ODB will then execute the statement
18733 11 times, the first 10 times with 5,000 data sets each, and the
18734 last time with the remaining 3,000 data sets.</p>
18735
18736 <p>The commonly used batch sizes are in the 2,000-5,000 range, though
18737 smaller or larger batches could provide better performance,
18738 depending on the situation. As a result, it is recommended to
18739 experiment with different batch sizes to determine the optimum
18740 number for a particular object and its use-cases. Note also that
18741 you may achieve better performance by also splitting a large bulk
18742 operation into multiple transactions (<a href="#3.5">Section 3.5,
18743 "Transactions"</a>).</p>
18744
18745 <p>For database systems that do not support bulk operations the
18746 <code>bulk</code> pragma is ignored. It is also possible to
18747 specify different batch sizes for different database systems
18748 by using the database prefix, for example:</p>
18749
18750 <pre class="cxx">
18751 #pragma db object mssql:bulk(3000) oracle:bulk(4000)
18752 class person
18753 {
18754 ...
18755 };
18756 </pre>
18757
18758 <p>Note that while specifying the batch size at compile time might
18759 seem inflexible, this approach allows ODB to place internal
18760 arrays of the fixed batch size on the stack rather than
18761 allocating them in the dynamic memory. However, specifying the
18762 batch size at runtime may be supported in the future.</p>
18763
18764 <p>Once the bulk support is enabled for a particular object, we can
18765 use the following <code>database</code> functions to perform bulk
18766 operations:</p>
18767
18768 <pre class="cxx">
18769 template &lt;typename I>
18770 void
18771 persist (I begin, I end, bool continue_failed = true);
18772
18773 template &lt;typename I>
18774 void
18775 update (I begin, I end, bool continue_failed = true);
18776
18777 template &lt;typename I>
18778 void
18779 erase (I obj_begin, I obj_end, bool continue_failed = true);
18780
18781 template &lt;typename T, typename I>
18782 void
18783 erase (I id_begin, I id_end, bool continue_failed = true);
18784 </pre>
18785
18786 <p>Every bulk API function expects a range of elements, passed in
18787 the canonical C++ form as a pair of input iterators. In case of
18788 <code>persist()</code>, <code>update()</code>, and the first
18789 <code>erase()</code> overload, we pass a range of objects,
18790 either as references or as pointers, raw or smart. The following
18791 example illustrates the most common scenarios using the
18792 <code>persist()</code> call:</p>
18793
18794 <pre class="cxx">
18795 // C array of objects.
18796 //
18797 person a[2] {{"John", "Doe"}, {"Jane", "Doe"}};
18798
18799 db.persist (a, a + sizeof(a) / sizeof(a[0]));
18800
18801
18802 // Vector of objects.
18803 //
18804 std::vector&lt;person> v {{"John", "Doe"}, {"Jane", "Doe"}};
18805
18806 db.persist (v.begin (), v.end ());
18807
18808
18809 // C array of raw pointers to objects.
18810 //
18811 person p1 ("John", "Doe");
18812 person p2 ("Jane", "Doe");
18813 person* pa[2] {&amp;p1, &amp;p2};
18814
18815 db.persist (pa, pa + sizeof(pa) / sizeof(pa[0]));
18816
18817
18818 // Vector of raw pointers to objects.
18819 //
18820 std::vector&lt;person*> pv {&amp;p1, &amp;p2};
18821
18822 db.persist (pv.begin (), pv.end ());
18823
18824
18825 // Vector of smart (shared) pointers to objects.
18826 //
18827 std::vector&lt;std::shared_ptr&lt;person>> sv {
18828 std::make_shared&lt;person> ("John", "Doe"),
18829 std::make_shared&lt;person> ("Jane", "Doe")};
18830
18831 db.persist (sv.begin (), sv.end ());
18832 </pre>
18833
18834 <p>The ability to perform a bulk operation on a range of raw pointers
18835 to objects can be especially useful when the application stores
18836 objects in a way that does not easily conform to the pair of
18837 iterators interface. In such cases we can create a temporary
18838 container of shallow pointers to objects and use that to perform
18839 the bulk operation, for example:</p>
18840
18841 <pre class="cxx">
18842 struct person_entry
18843 {
18844 person obj;
18845
18846 // Some additional data.
18847 ...
18848 };
18849
18850 typedef std::vector&lt;person_entry> people;
18851
18852 void
18853 persist (odb::database&amp; db, people&amp; p)
18854 {
18855 std::vector&lt;person*> tmp;
18856 tmp.reserve (p.size ());
18857 std::for_each (p.begin (),
18858 p.end (),
18859 [&amp;tmp] (person_entry&amp; pe)
18860 {
18861 tmp.push_back (&amp;pe.obj);
18862 });
18863
18864
18865 db.persist (tmp.begin (), tmp.end ());
18866 }
18867 </pre>
18868
18869 <p>The second overload of the bulk <code>erase()</code> function
18870 allows us to pass a range of object ids rather than objects
18871 themselves. As with the corresponding non-bulk version, we
18872 have to specify the object type explicitly, for example:</p>
18873
18874 <pre class="cxx">
18875 std::vector&lt;unsigned long> ids {1, 2};
18876
18877 db.erase&lt;person> (ids.begin (), ids.end ());
18878 </pre>
18879
18880 <p>Conceptually, a bulk operation is equivalent to performing the
18881 corresponding non-bulk version in a loop, except when it comes to the
18882 failure semantics. Both databases that currently are capable of
18883 bulk operations (Oracle and SQL Server) do not stop when a data
18884 set in a batch fails (for example, because of a unique constraint
18885 violation). Instead, they continue executing subsequent data
18886 sets until every element in the batch has been attempted. The
18887 <code>continue_failed</code> argument in the bulk functions listed
18888 above specifies whether ODB should extend this behavior and continue
18889 with subsequent batches if the one it has tried to execute has failed
18890 elements. The default behavior is to continue.</p>
18891
18892 <p>The consequence of this failure semantics is that we may have
18893 multiple elements in the range failed for different reasons.
18894 For example, if we tried to persist a number of objects, some
18895 of them might have failed because they are already persistent
18896 while others &mdash; because of a unique constraint violation.
18897 As a result, ODB uses the special <code>odb::multiple_exceptions</code>
18898 class to report failures in the bulk API functions. This
18899 exception is thrown if one or more elements in the range have
18900 failed and it contains the error information in the form of other
18901 ODB exception for each failed position. The
18902 <code>multiple_exceptions</code> class has the following interface:</p>
18903
18904 <pre class="cxx">
18905 struct multiple_exceptions: odb::exception
18906 {
18907 // Element type.
18908 //
18909 struct value_type
18910 {
18911 std::size_t
18912 position () const;
18913
18914 const odb::exception&amp;
18915 exception () const;
18916
18917 bool
18918 maybe () const;
18919 };
18920
18921 // Iteration.
18922 //
18923 typedef std::set&lt;value_type> set_type;
18924
18925 typedef set_type::const_iterator iterator;
18926 typedef set_type::const_iterator const_iterator;
18927
18928 iterator
18929 begin () const;
18930
18931 iterator
18932 end () const;
18933
18934 // Lookup.
18935 //
18936 const value_type*
18937 operator[] (std::size_t) const;
18938
18939 // Severity, failed and attempted counts.
18940 //
18941 std::size_t
18942 attempted () const;
18943
18944 std::size_t
18945 failed () const;
18946
18947 bool
18948 fatal () const;
18949
18950 void
18951 fatal (bool);
18952
18953 // Direct data access.
18954 //
18955 const set_type&amp;
18956 set () const;
18957
18958 // odb::exception interface.
18959 //
18960 virtual const char*
18961 what () const throw ();
18962 };
18963 </pre>
18964
18965 <p>The <code>multiple_exceptions</code> class has a map-like interface
18966 with the key being the position in the range and the value being
18967 the exception plus the <code>maybe</code> flag (discussed below).
18968 As a result, we can either iterate over the failed positions or
18969 we can check whether a specific position in the range has failed.
18970 The following example shows what a <code>catch</code>-handler for
18971 this exception might look like:</p>
18972
18973 <pre class="cxx">
18974 std::vector&lt;person> objs {{"John", "Doe"}, {"Jane", "Doe"}};
18975
18976 try
18977 {
18978 db.persist (objs.begin (), objs.end ());
18979 }
18980 catch (const odb::multiple_exceptions&amp; me)
18981 {
18982 for (const auto&amp; v: me)
18983 {
18984 size_t p (v.position ());
18985
18986 try
18987 {
18988 throw v.exception ();
18989 }
18990 catch (const odb::object_already_persistent&amp;)
18991 {
18992 cerr &lt;&lt; p &lt;&lt; ": duplicate id: " &lt;&lt; objs[p].id () &lt;&lt; endl;
18993 }
18994 catch (const odb::exception&amp; e)
18995 {
18996 cerr &lt;&lt; p &lt;&lt; ": " &lt;&lt; e.what () &lt;&lt; endl;
18997 }
18998 }
18999 }
19000 </pre>
19001
19002 <p>If, however, all we want is to show the diagnostics to the user,
19003 then the string returned by the <code>what()</code> function
19004 will contain the error information for each failed position.
19005 Here is what it might look like (using Oracle as an example):</p>
19006
19007 <pre class="terminal">
19008 multiple exceptions, 4 elements attempted, 2 failed:
19009 [0] object already persistent
19010 [3] 1: ORA-00001: unique constraint (ODB_TEST.person_last_i) violated
19011 </pre>
19012
19013 <p>Both databases that currently are capable of bulk operations return
19014 a total count of affected rows rather than individual counts for
19015 each data set. This limitation prevents ODB from being able to
19016 always determine which elements in the batch haven't affected
19017 any rows and, for the update and erase operations, translate
19018 this to the <code>object_not_persistent</code> exceptions. As
19019 a result, if some elements in the batch haven't affected any
19020 rows and ODB is unable to determine exactly which ones, it will mark
19021 all the elements in this batch as "maybe not persistent". That
19022 is, it will insert the <code>object_not_persistent</code> exception
19023 and set the <code>maybe</code> flag for every position in the
19024 batch. The diagnostics string returned by <code>what()</code>
19025 will also reflect this situation, for example (assuming batch
19026 size of 3):</p>
19027
19028 <pre class="terminal">
19029 multiple exceptions, 4 elements attempted, 4 failed:
19030 [0-2] (some) object not persistent
19031 [3] object not persistent
19032 </pre>
19033
19034 <p>The way to handle and recover from such "maybe failures" will have
19035 to be application-specific. For example, for some applications the
19036 fact that some objects no longer exist in the database when
19037 performing bulk erase might be an ignorable error. If, however,
19038 the application needs to determine exactly which elements in the batch
19039 have failed, then a <code>load()</code> call will be required for each
19040 element in the batch (or a query using a view to avoid loading all
19041 the data members; <a href="#10">Chapter 10, "Views"</a>). This is also
19042 something to keep in mind when selecting the batch size since for
19043 larger sizes it will be more expensive (more loads to perform) to
19044 handle such "maybe failures". If the failures are not uncommon, as
19045 is the case, for example, when using optimistic concurrency, then
19046 it may make sense to use a smaller batch.</p>
19047
19048 <p>The lookup operator (<code>operator[]</code>) returns <code>NULL</code>
19049 if the element at this position has no exception. Note also that the
19050 returned value is <code>value_type*</code> and not
19051 <code>odb::exception*</code> in order to provide access to the
19052 <code>maybe</code> flag discussed above.</p>
19053
19054 <p>The <code>multiple_exceptions</code> class also provides access
19055 to the number of positions attempted (the <code>attempted()</code>
19056 accessor) and failed (the <code>failed()</code> accessor). Note
19057 that the failed count includes the "maybe failed" positions.</p>
19058
19059 <p>The <code>multiple_exceptions</code> exception can also be fatal.
19060 If the <code>fatal()</code> accessor returns <code>true</code>, then
19061 (some of) the exceptions were fatal. In this case, even for positions
19062 that did not fail, no attempts were made to complete the operation
19063 and the transaction must be aborted.</p>
19064
19065 <p>If <code>fatal()</code> returns false, then the operation on the
19066 elements that don't have an exception has succeeded. The application
19067 can ignore the errors or try to correct the errors and re-attempt
19068 the operation on the elements that did fail. In either case, the
19069 transaction can be committed.</p>
19070
19071 <p>An example of a fatal exception would be the situation where the
19072 execution of the underlying statement failed summarily, without
19073 attempting any data sets, for instance, because of an error in
19074 the statement itself.</p>
19075
19076 <p>The <code>fatal()</code> modifier allows you to "upgrade" an
19077 exception to fatal, for example, for specific database error
19078 codes.</p>
19079
19080
19081 <!-- PART -->
19082
19083
19084 <hr class="page-break"/>
19085 <h1><a name="II">PART II&nbsp;&nbsp;
19086 <span style="font-weight: normal;">DATABASE SYSTEMS</span></a></h1>
19087
19088 <p>Part II covers topics specific to the database system
19089 implementations and their support in ODB. The first chapter in
19090 Part II discusses how to use multiple database systems in the
19091 same application. The subsequent chapters describe the system-specific
19092 <code>database</code> classes as well as the default mapping
19093 between basic C++ value types and native database types. Part
19094 II consists of the following chapters.</p>
19095
19096 <table class="toc">
19097 <tr><th>16</th><td><a href="#16">Multi-Database Support</a></td></tr>
19098 <tr><th>17</th><td><a href="#17">MySQL Database</a></td></tr>
19099 <tr><th>18</th><td><a href="#18">SQLite Database</a></td></tr>
19100 <tr><th>19</th><td><a href="#19">PostgreSQL Database</a></td></tr>
19101 <tr><th>20</th><td><a href="#20">Oracle Database</a></td></tr>
19102 <tr><th>21</th><td><a href="#21">Microsoft SQL Server Database</a></td></tr>
19103 </table>
19104
19105
19106 <!-- CHAPTER -->
19107
19108
19109 <hr class="page-break"/>
19110 <h1><a name="16">16 Multi-Database Support</a></h1>
19111
19112 <p>Some applications may need to access multiple database systems, either
19113 simultaneously or one at a time. For example, an application may
19114 utilize an embedded database such as SQLite as a local cache and use
19115 a client-server database such as PostgreSQL for more permanent
19116 but slower to access remote storage. Or an application may need
19117 to be able to store its data in any database selected at runtime
19118 by the user. Yet another scenario is the data migration from one
19119 database system to another. In this case, multi-database support
19120 is only required for a short period. It is also plausible that an
19121 application implements all three of these scenarios, that is, it
19122 uses SQLite as a local cache, allows the user to select the remote
19123 database system, and supports data migration from one remote database
19124 system to another.</p>
19125
19126 <p>ODB provides two types of multi-database support: <em>static</em>
19127 and <em>dynamic</em>. With static support we use the
19128 database system-specific interfaces to perform database
19129 operations. That is, instead of using <code>odb::database</code>,
19130 <code>odb::transaction</code>, or <code>odb::query</code>, we
19131 would use, for example, <code>odb::sqlite::database</code>,
19132 <code>odb::sqlite::transaction</code>, or
19133 <code>odb::sqlite::query</code> to access an SQLite database.</p>
19134
19135 <p>In contrast, with <em>dynamic</em> multi-database support we can
19136 use the common interface to access any database without having to
19137 know which one it is. At runtime, ODB will automatically dispatch
19138 a call on the common interface to the specific database implementation
19139 based on the actual <code>database</code> instance being
19140 used. In fact, this mechanism is very similar to C++ virtual
19141 functions.</p>
19142
19143 <p>Both static and dynamic multi-database support have a different set
19144 of advantages and disadvantages which makes them more or less suitable
19145 for different use cases. Static support has zero overhead compared
19146 to single-database support and allows us to use database
19147 system-specific features, extensions, etc. At the same time, the
19148 code that we write will be tied to the specific database system.
19149 As a result, this type of multi-database support is more
19150 suitable for situations where different parts of an application
19151 access different but specific database systems. For example,
19152 using SQLite as a local cache most likely falls into this
19153 category since we are using a specific database system (SQLite)
19154 and the code that will check the cache will most likely (but
19155 not necessarily) be separate from the code that interact with
19156 the remote database. Another example where static multi-database
19157 support might be more suitable is a once-off data migration from
19158 one database system to another. In this case both the source and
19159 target are specific database systems. In contrast, if data migration
19160 from one database system to another is a general feature in an
19161 application, then dynamic multi-database support might be more
19162 suitable.</p>
19163
19164 <p>The main advantage of dynamic multi-database support is the
19165 database system-independence of the code that we write. The same
19166 application code will work with any database system supported by
19167 ODB and the generated database support code can be packaged into
19168 separate libraries and loaded dynamically by the application. The
19169 disadvantages of dynamic support are slight overhead and certain
19170 limitations in functionality compared to static support (see
19171 <a href="#16.2">Section 16.2, "Dynamic Multi-Database Support"</a>
19172 for details). As a result, dynamic multi-database support is most
19173 suitable to situations where we need the same code to
19174 work with a range of database systems. For example, if your
19175 application must be able to store its data in any database
19176 selected by the user, then dynamic support is probably the
19177 best option.</p>
19178
19179 <p>Note also that it is possible to mix and match static and dynamic
19180 support in the same application. In fact, dynamic support is built
19181 on top of static support so it is possible to use the same database
19182 system both "statically" and "dynamically". In particular, the ability
19183 to "drop down" from dynamic to static support can be used to overcome
19184 the functionality limitations mentioned above. Finally,
19185 single-database support is just a special case of static
19186 multi-database support with a single database system.</p>
19187
19188 <p>By default ODB assumes single-database support. To enable
19189 multi-database support we use the <code>--multi-database</code>
19190 (or <code>-m</code>) ODB compiler option. This option is also used to
19191 specify the support type: <code>static</code> or <code>dynamic</code>.
19192 For example:</p>
19193
19194 <pre class="terminal">
19195 odb -m static ... person.hxx
19196 </pre>
19197
19198 <p>With multi-database support enabled, we can now generate the database
19199 support code for several database systems. This can be accomplished
19200 either with a single ODB compiler invocation by specifying multiple
19201 <code>--database</code> (or <code>-d</code>) options or with multiple
19202 ODB compiler invocations. Both approaches produce the same result,
19203 for example:</p>
19204
19205 <pre class="terminal">
19206 odb -m static -d common -d sqlite -d pgsql person.hxx
19207 </pre>
19208
19209 <p>Is equivalent to:</p>
19210
19211 <pre class="terminal">
19212 odb -m static -d common person.hxx
19213 odb -m static -d sqlite person.hxx
19214 odb -m static -d pgsql person.hxx
19215 </pre>
19216
19217 <p>Notice that the first <code>-d</code> option has <code>common</code>
19218 as its value. This is not a real database system. Rather, it instructs
19219 the ODB compiler to generate code that is common to all the database
19220 systems and, in case of dynamic support, is also the common
19221 interfaces.</p>
19222
19223 <p>If you look at the result of the above commands, you will also notice
19224 changes in the output file names. In the single-database mode the ODB
19225 compiler produces a single set of the <code>person-odb.?xx</code> files
19226 which contain both the common as well as the database specific
19227 generated code (since there is only one database system in use,
19228 there is no reason to split the two). In contrast, in the
19229 multi-database mode, the <code>person-odb.?xx</code> set of files
19230 contains the common code while the database system-specific code is
19231 written to files in the form <code>person-odb-&lt;db>.?xx</code>.
19232 That is, <code>person-odb-sqlite.?xx</code> for SQLite,
19233 <code>person-odb-pgsql.?xx</code> for PostgreSQL, etc.</p>
19234
19235 <p>If we need dynamic support for some databases and static for
19236 others, then the <code>common</code> code must be generated
19237 in the dynamic mode. For example, if we need static support
19238 for SQLite and dynamic support for PostgreSQL and Oracle, then
19239 the ODB compiler invocations could look like this:</p>
19240
19241 <pre class="terminal">
19242 odb -m dynamic -d common person.hxx
19243 odb -m static -d sqlite person.hxx
19244 odb -m dynamic -d pgsql person.hxx
19245 odb -m dynamic -d oracle person.hxx
19246 </pre>
19247
19248 <p>With multi-database support enabled, it is possible to restrict ODB
19249 pragmas to apply only to a specific database system (unrestricted
19250 pragmas apply to all the databases). For example:</p>
19251
19252 <pre class="cxx">
19253 #pragma db object
19254 class person
19255 {
19256 ...
19257
19258 #pragma db pgsql:type("VARCHAR(128)") sqlite:type("TEXT")
19259 std::string name_;
19260
19261 unsigned short age_;
19262
19263 #pragma db pgsql index member(age_)
19264 };
19265 </pre>
19266
19267 <p>Above, the pragma for the <code>name_</code> data member shows the
19268 use of a database prefix (for example, <code>pgsql:</code>) that
19269 only applies to the specifier that follows. The pragma that defines
19270 an index on the <code>age_</code> data member shows the use of a
19271 database prefix that applies to the whole pragma. In this case the
19272 database name must immediately follow the <code>db</code> keyword.</p>
19273
19274
19275 <p>Similar to pragmas, ODB compiler options that determine the kind
19276 (for example, <code>--schema-format</code>), names (for example,
19277 <code>--odb-file-suffix</code>), or content (for example, prologue
19278 and epilogue options) of the output files can be prefixed with the
19279 database name. For example:</p>
19280
19281 <pre class="terminal">
19282 odb --odb-file-suffix common:-odb-common ...
19283 </pre>
19284
19285 <p>Dynamic multi-database support requires consistent mapping across
19286 all the databases. That is, the same classes and data members
19287 should be mapped to objects, simple/composite values, etc., for
19288 all the databases. In contrast, static multi-database support
19289 does not have this restriction. Specifically, with static support,
19290 some data members can be transient for some database systems.
19291 Similarly, the same class (for example, <code>point</code>) can
19292 be mapped to a simple value in one database (for example, to the
19293 <code>POINT</code> PostgreSQL type) and to a composite value
19294 in another (for example, in SQLite, which does not have a
19295 built-in point type).</p>
19296
19297 <p>The following sections discuss static and dynamic multi-database
19298 support in more detail.</p>
19299
19300
19301 <h2><a name="16.1">16.1 Static Multi-Database Support</a></h2>
19302
19303 <p>With static multi-database support, instead of including
19304 <code>person-odb.hxx</code>, application source code has
19305 to include <code>person-odb-&lt;db>.hxx</code> header files
19306 corresponding to the database systems that will be used.</p>
19307
19308 <p>The application code has to also use database system-specific
19309 interfaces when performing database operations. As an example,
19310 consider the following transaction in a single-database
19311 application. It uses the common interfaces, that is, classes
19312 from the <code>odb</code> namespace.</p>
19313
19314 <pre class="cxx">
19315 #include "person-odb.hxx"
19316
19317 odb::database&amp; db = ...
19318
19319 typedef odb::query&lt;person> query;
19320 typedef odb::result&lt;person> result;
19321
19322 odb::transaction t (db.begin ());
19323 result r (db.query&lt;person> (query::age &lt; 30));
19324 ...
19325 t.commit ();
19326 </pre>
19327
19328 <p>In an application that employs static multi-database support
19329 the same transaction for SQLite would be rewritten like this:</p>
19330
19331 <pre class="cxx">
19332 #include "person-odb-sqlite.hxx"
19333
19334 odb::sqlite::database&amp; db = ...
19335
19336 typedef odb::sqlite::query&lt;person> query;
19337 typedef odb::result&lt;person> result; // odb:: not odb::sqlite::
19338
19339 odb::sqlite::transaction t (db.begin ());
19340 result r (db.query&lt;person> (query::age &lt; 30));
19341 ...
19342 t.commit ();
19343 </pre>
19344
19345 <p>That is, the <code>database</code>, <code>transaction</code>, and
19346 <code>query</code> classes now come from the <code>odb::sqlite</code>
19347 namespace instead of <code>odb</code>. Other classes that have
19348 database system-specific interfaces are <code>connection</code>,
19349 <code>statement</code>, and <code>tracer</code>. Note that
19350 all of them derive from the corresponding common versions. It
19351 is also possible to use common <code>transaction</code>,
19352 <code>connection</code>, and <code>statement</code> classes
19353 with static support, if desired.</p>
19354
19355 <p>Notice that we didn't use the <code>odb::sqlite</code> namespace
19356 for the <code>result</code> class template. This is because
19357 <code>result</code> is database system-independent. All other
19358 classes defined in namespace <code>odb</code>, except those
19359 specifically mentioned above, are database system-independent.
19360 In particular, <code>result</code>, <code>prepared_query</code>,
19361 <code>session</code>, <code>schema_catalog</code>, and all the
19362 exceptions are database system-independent.</p>
19363
19364 <p>Writing <code>odb::sqlite::</code> before every name can quickly
19365 become burdensome. As we have seen before, in single-database
19366 applications that use the common interface we can add the
19367 <code>using namespace</code> directive to avoid qualifying
19368 each name. For example:</p>
19369
19370 <pre class="cxx">
19371 #include "person-odb.hxx"
19372
19373 odb::database&amp; db = ...
19374
19375 {
19376 using namespace odb::core;
19377
19378 typedef query&lt;person> person_query;
19379 typedef result&lt;person> person_result;
19380
19381 transaction t (db.begin ());
19382 person_result r (db.query&lt;person> (person_query::age &lt; 30));
19383 ...
19384 t.commit ();
19385 }
19386 </pre>
19387
19388 <p>A similar mechanism is available in multi-database support. Each
19389 database runtime defines the <code>odb::&lt;db>::core</code>
19390 namespace that contains all the database system-independent
19391 names as well as the database system-specific ones for this
19392 database. Here is how we can rewire the above transaction
19393 using this approach:</p>
19394
19395 <pre class="cxx">
19396 #include "person-odb-sqlite.hxx"
19397
19398 odb::sqlite::database&amp; db = ...
19399
19400 {
19401 using namespace odb::sqlite::core;
19402
19403 typedef query&lt;person> person_query;
19404 typedef result&lt;person> person_result;
19405
19406 transaction t (db.begin ());
19407 person_result r (db.query&lt;person> (person_query::age &lt; 30));
19408 ...
19409 t.commit ();
19410 }
19411 </pre>
19412
19413 <p>If the <code>using namespace</code> directive cannot be used, for
19414 example, because the same code fragment accesses several databases,
19415 then we can still make the namespace qualifications more concise
19416 by assigning shorter aliases to database namespaces. For example:</p>
19417
19418 <pre class="cxx">
19419 #include "person-odb-pgsql.hxx"
19420 #include "person-odb-sqlite.hxx"
19421
19422 namespace pg = odb::pgsql;
19423 namespace sl = odb::sqlite;
19424
19425 pg::database&amp; pg_db = ...
19426 sl::database&amp; sl_db = ...
19427
19428 typedef pg::query&lt;person> pg_query;
19429 typedef sl::query&lt;person> sl_query;
19430 typedef odb::result&lt;person> result;
19431
19432 // First check the local cache.
19433 //
19434 odb::transaction t (sl_db.begin ()); // Note: using common transaction.
19435 result r (sl_db.query&lt;person> (sl_query::age &lt; 30));
19436
19437 // If no hits, try the remote database.
19438 //
19439 if (r.empty ())
19440 {
19441 t.commit (); // End the SQLite transaction.
19442 t.reset (pg_db.begin ()); // Start the PostgreSQL transaction.
19443
19444 r = pg_db.query&lt;person> (pg_query::age &lt; 30);
19445 }
19446
19447 // Handle the result.
19448 //
19449 ...
19450
19451 t.commit ();
19452 </pre>
19453
19454 <p>With static multi-database support we can make one of the databases
19455 the default database with the <code>--default-database</code> option.
19456 The default database can be accessed via the common interface, just
19457 like with single-database support. For example:</p>
19458
19459 <pre class="terminal">
19460 odb -m static -d common -d pgsql -d sqlite --default-database pgsql ...
19461 </pre>
19462
19463 <p>The default database mechanism can be useful when one of the
19464 databases is primary or when retrofitting multi-database support
19465 into an existing single-database application. For example, if
19466 we are adding SQLite as a local cache into an existing
19467 application that uses PostgreSQL as its only database, then
19468 by making PostgreSQL the default database we avoid having to
19469 change all the existing code. Note that if dynamic multi-database
19470 support is enabled, then the common (dynamic) interface is always
19471 made the default database.</p>
19472
19473 <h2><a name="16.2">16.2 Dynamic Multi-Database Support</a></h2>
19474
19475 <p>With dynamic multi-database support, application source code only
19476 needs to include the <code>person-odb.hxx</code> header file, just
19477 like with single-database support. In particular, we don't need
19478 to include any of the <code>person-odb-&lt;db>.hxx</code> files
19479 unless we would also like to use certain database systems in the
19480 static multi-database mode.</p>
19481
19482 <p>When performing database operations, the application code
19483 uses the common interfaces from the <code>odb</code> namespace,
19484 just like with single-database support. As an example, consider
19485 a function that can be used to load an object either from a local
19486 SQLite cache or a remote PostgreSQL database (in reality, this
19487 function can be used with any database system support by ODB
19488 provided we generated the database support code for this database
19489 and linked it into our application):</p>
19490
19491 <pre class="cxx">
19492 #include "person-odb.hxx"
19493
19494 std::unique_ptr&lt;person>
19495 load (odb::database&amp; db, const std::string&amp; name)
19496 {
19497 odb::transaction t (db.begin ());
19498 std::unique_ptr&lt;person> p (db.find (name));
19499 t.commit ();
19500 return p;
19501 }
19502
19503 odb::pgsql::database&amp; pg_db = ...
19504 odb::sqlite::database&amp; sl_db = ...
19505
19506 // First try the local cache.
19507 //
19508 std::unique_ptr&lt;person> p (load (sl_db, "John Doe"));
19509
19510 // If not found, try the remote database.
19511 //
19512 if (p == 0)
19513 p = load (pg_db, "John Doe");
19514
19515 ...
19516 </pre>
19517
19518 <p>As you can see, we can use dynamic multi-database support just like
19519 single-database support except that now our code can work with
19520 different database systems. Note, however, one difference: with
19521 single-database support we could perform database operations using
19522 either the common <code>odb::database</code> or a database system-specific
19523 (for example, <code>odb::sqlite::database</code>) interface
19524 with the same effect. In contrast, with dynamic multi-database support,
19525 the use of the database system-specific interface results in the
19526 switch to the static mode (for which, as was mentioned earlier, we would
19527 need to include the corresponding <code>person-odb-&lt;db>.hxx</code>
19528 header file). As we will discuss shortly, switching from dynamic to
19529 static mode can be used to overcome limitations imposed by dynamic
19530 multi-database support.</p>
19531
19532 <p>Dynamic multi-database support has certain overheads and limitations
19533 compared to static support. For database operations, the generated code
19534 maintains function tables that are used to dispatch calls to the database
19535 system-specific implementations. In single-database and static
19536 multi-database support, the <code>query</code> type implements a thin
19537 wrapper around the underlying database system's <code>SELECT</code>
19538 statement. With dynamic multi-database support, because the
19539 underlying database system is only known at query execution
19540 (or preparation) time, the <code>query</code> type stores a
19541 database system-independent representation of the query that
19542 is then translated to the database system-specific form. Because
19543 of this database system-independent representation, dynamic
19544 support queries have a number of limitations. Specifically, dynamic
19545 queries do not support parameter binding in native query fragments.
19546 They also make copies of by-value parameterd (by-reference parameters
19547 can be used to remove this overhead). Finally, parameters of array
19548 types (for example, <code>char[256]</code>) can only be bound
19549 by-reference.</p>
19550
19551 <p>As we mentioned earlier, switching from dynamic to static mode
19552 can be an effective way to overcome these limitations. As an
19553 example, consider a function that prints the list of people of
19554 a certain age. The caller also specified the limit on the number
19555 of entries to print. Some database systems, for example, PostgreSQL,
19556 allow us to propagate this limit to the database server with the
19557 <code>LIMIT</code> clause. To add this clause we would need to
19558 construct a native query fragment and, as we discussed above, we
19559 won't be able to bind a parameter (the limit) while in the dynamic
19560 mode. The following implementation shows how we can overcome this
19561 by switching to the static mode and using the PostgreSQL-specific
19562 interface:</p>
19563
19564 <pre class="cxx">
19565 #include "person-odb.hxx"
19566 #include "person-odb-pgsql.hxx" // Needed for static mode.
19567
19568 void
19569 print (odb::database&amp; db, unsigned short age, unsigned long limit)
19570 {
19571 typedef odb::query&lt;person> query;
19572 typedef odb::result&lt;person> result;
19573
19574 odb::transaction t (db.begin ());
19575
19576 query q (query::age == age);
19577 result r;
19578
19579 if (db.id () == odb::id_pgsql)
19580 {
19581 // We are using PostgreSQL. Drop down to the static mode and
19582 // add the LIMIT clause to the query.
19583 //
19584 namespace pg = odb::pgsql;
19585 typedef pg::query&lt;person> pg_query;
19586
19587 pg::database&amp; pg_db (static_cast&lt;pg::database&amp;> (db));
19588 pg_query pg_q (pg_query (q) + "LIMIT" + pg_query::_val (limit));
19589 r = pg_db.query&lt;person> (pg_q);
19590 }
19591 else
19592 r = db.query&lt;person> (q);
19593
19594 // Handle the result up to the limit elements.
19595 //
19596 ...
19597
19598 t.commit ();
19599 }
19600
19601 odb::pgsql::database&amp; pg_db = ...
19602 odb::sqlite::database&amp; sl_db = ...
19603
19604 print (sl_db, 30, 100);
19605 print (sl_db, 30, 100);
19606 </pre>
19607
19608 <p>A few things to note about this example. First, we use the
19609 <code>database::id()</code> function to determine the actual database
19610 system we use. This function has the following signature:</p>
19611
19612 <pre class="cxx">
19613 namespace odb
19614 {
19615 enum database_id
19616 {
19617 id_mysql,
19618 id_sqlite,
19619 id_pgsql,
19620 id_oracle,
19621 id_mssql,
19622 id_common
19623 };
19624
19625 class database
19626 {
19627 public:
19628 ...
19629
19630 database_id
19631 id () const;
19632 }
19633 }
19634 </pre>
19635
19636 <p>Note that <code>database::id()</code> can never return the
19637 <code>id_common</code> value.</p>
19638
19639 <p>The other thing to note is how we translate the dynamic query
19640 to the database system-specific one (the <code>pg_query (q)</code>
19641 expression). Every <code>odb::&lt;db>::query</code> class provides
19642 such a translation constructor.</p>
19643
19644 <h3><a name="16.2.2">16.2.2 Dynamic Loading of Database Support Code</a></h3>
19645
19646 <p>With dynamic multi-database support, the generated database support
19647 code automatically registers itself with the function tables that
19648 we mentioned earlier. This makes it possible to package the generated
19649 code for each database into a separate dynamic-link library (Windows
19650 DLL) or dynamic shared object (Unix DSO; collectively referred to as
19651 DLLs from now on) and load/unload them from the application
19652 dynamically using APIs such as Win32 <code>LoadLibrary()</code> or
19653 POSIX <code>dlopen()</code>. This allows the application address
19654 space to contain code only for database systems that are actually
19655 needed in any particular moment. Another advantage of this approach
19656 is the ability to distribute individual database system support
19657 separately.</p>
19658
19659 <p>This section provides an overview of how to package the generated
19660 database support code into DLLs for both Windows and Unix using
19661 GNU/Linux as an example. Note also that if static multi-database
19662 support is used for a particular database system, then the dynamic
19663 loading cannot be used for this database. It is, however, still
19664 possible to package the generated code into a DLL but this DLL
19665 will have to be linked to the executable at link-time rather
19666 than at runtime. If dynamic loading is desirable in this situation,
19667 then another alternative would be to package the functionality
19668 that requires static support together with the database support
19669 code into the DLL and import this functionality dynamically
19670 using the <code>GetProcAddress()</code> (Win32) or <code>dlsym()</code>
19671 (Unix) function.</p>
19672
19673 <p>The first step in packaging the generated code into DLLs is to
19674 set up the symbol exporting. This step is required for
19675 Windows DLLs but is optional for Unix DSOs. Most modern Unix
19676 systems (such as GNU/Linux) provide control over symbol
19677 visibility, which is a mechanism similar to Windows symbol
19678 exporting. Notable advantages of using this mechanism to
19679 explicitly specify which symbols are visible include
19680 smaller Unix DSOs and faster load times. If, however, you are
19681 not planning to control symbol visibility on Unix, then you can
19682 skip directly to the second step below.</p>
19683
19684 <p>An important point to understand is that we only need to export
19685 the common interface, that is, the classes defined in the
19686 <code>person-odb.hxx</code> header. In particular, we don't need
19687 to export the database system-specific classes defined in
19688 the <code>person-odb-&lt;db>.hxx</code>, unless we are also using
19689 this database in the static mode (in which case, the procedure
19690 described below will need to be repeated for that database as
19691 well).</p>
19692
19693 <p>The ODB compiler provides two command line options,
19694 <code>--export-symbol</code> and <code>--extern-symbol</code>,
19695 which can be used to insert the export and extern
19696 macros in all the necessary places in the generated header file.
19697 You are probably familiar with the concept of export macro which
19698 expands to an export directive if we are building the DLL and to
19699 an import directive if we are building client code. The
19700 extern macro is a supplementary mechanism which is necessary to
19701 export explicit template instantiations used by the generated
19702 code when query support is enabled. As we will see shortly, the
19703 extern macro must expand into the <code>extern</code> C++ keyword
19704 in certain situations and must be left undefined in others. To
19705 manage all these macro definitions, it is customary to create the
19706 so called export header. Based on a single macro that is normally
19707 defined in the project file or on the command line and which
19708 indicates whether we are building the DLL or client code, the
19709 export header file sets the export and extern macros to their
19710 appropriate values. Continuing with our person example, on Windows
19711 the export header, which we will call <code>person-export.hxx</code>,
19712 could look like this:</p>
19713
19714 <pre class="cxx">
19715 // person-export.hxx
19716 //
19717 // Define PERSON_BUILD_DLL if we are building the DLL. Leave it
19718 // undefined in client code.
19719 //
19720 #ifndef PERSON_EXPORT_HXX
19721 #define PERSON_EXPORT_HXX
19722
19723 #ifdef PERSON_BUILD_DLL
19724 # define PERSON_EXPORT __declspec(dllexport)
19725 #else
19726 # define PERSON_EXPORT __declspec(dllimport)
19727 # define PERSON_EXTERN extern
19728 #endif
19729
19730 #endif // PERSON_EXPORT_HXX
19731 </pre>
19732
19733 <p>The equivalent export header for GCC on GNU/Linux is shown below.
19734 Note also that on GNU/Linux, by default, all symbols are visible
19735 and we need to add the GCC <code>-fvisibility=hidden</code> option to
19736 make them hidden by default.</p>
19737
19738 <pre class="cxx">
19739 // person-export.hxx
19740 //
19741 #ifndef PERSON_EXPORT_HXX
19742 #define PERSON_EXPORT_HXX
19743
19744 #define PERSON_EXPORT __attribute__ ((visibility ("default")))
19745 #define PERSON_EXTERN extern
19746
19747 #endif // PERSON_EXPORT_HXX
19748 </pre>
19749
19750 <p>Next we need to export the <code>person</code> persistent class
19751 using the export macro and re-compile our <code>person.hxx</code> file
19752 with the <code>--export-symbol</code> and <code>--extern-symbol</code>
19753 options. We will also need to include <code>person-export.hxx</code>
19754 into the generated <code>person-odb.hxx</code> file. For that we use
19755 the <code>--hxx-prologue</code> option. Here is how we can do
19756 this with multiple invocations of the ODB compiler:</p>
19757
19758 <pre class="terminal">
19759 odb -m dynamic -d common --hxx-prologue "#include \"person-export.hxx\"" \
19760 --export-symbol PERSON_EXPORT --extern-symbol PERSON_EXTERN person.hxx
19761
19762 odb -m dynamic -d sqlite person.hxx
19763 odb -m dynamic -d pgsql person.hxx
19764 </pre>
19765
19766 <p>It is also possible to achieve the same with a single invocation.
19767 Here we need to restrict some option values to apply only to the
19768 <code>common</code> database:</p>
19769
19770 <pre class="terminal">
19771 odb -m dynamic -d common -d sqlite -d pgsql \
19772 --hxx-prologue "common:#include \"person-export.hxx\"" \
19773 --export-symbol common:PERSON_EXPORT --extern-symbol common:PERSON_EXTERN \
19774 person.hxx
19775 </pre>
19776
19777 <p>The second step in packaging the generated code into DLLs is to
19778 decide where to place the generated common interface code. One
19779 option is to place it into a DLL of its own so that we will end
19780 up with (replace <code>*.dll</code> with <code>lib*.so</code> for
19781 Unix): <code>person.dll</code> plus <code>person-sqlite.dll</code> and
19782 <code>person-pgsql.dll</code>, which both link to <code>person.dll</code>,
19783 as well as <code>person.exe</code>, which links to <code>person.dll</code>
19784 and dynamically loads <code>person-sqlite.dll</code>
19785 and/or <code>person-pgsql.dll</code>. If this is the organization
19786 that you prefer, then the next step is to build all the DLLs as you
19787 normally would any other DLL, placing <code>person-odb.cxx</code>
19788 and <code>person.cxx</code> into <code>person.dll</code>,
19789 <code>person-odb-sqlite.cxx</code> into <code>person-sqlite.dll</code>,
19790 etc. Note that in the pure dynamic multi-database support,
19791 <code>person-sqlite.dll</code> and <code>person-pgsql.dll</code>
19792 do not export any symbols.</p>
19793
19794 <p>We can improve on the above organization by getting rid of
19795 <code>person.dll</code>, which is not really necessary unless
19796 we have multiple executables sharing the same database support.
19797 To achieve this, we will place <code>person-odb.cxx</code> into
19798 <code>person.exe</code> and export its symbols from the executable
19799 instead of a DLL. Exporting symbols from an executable is a seldom
19800 used functionality, especially on Windows, however, it is well
19801 supported on both Windows and most Unix platforms. Note also that
19802 this approach won't work if we also use one of the databases in the
19803 static mode.</p>
19804
19805 <p>On Windows all we have to do is place <code>person-odb.cxx</code>
19806 into the executable and compile it as we would in a DLL (that is,
19807 with the <code>PERSON_BUILD_DLL</code> macro defined). If Windows
19808 linker detects that an executable exports any symbols, then it
19809 will automatically create the corresponding import library
19810 (<code>person.lib</code> in our case). We then use this import
19811 library to build <code>person-sqlite.dll</code> and
19812 <code>person-pgsql.dll</code> as before.</p>
19813
19814 <p>To export symbols from an executable on GNU/Linux all we need to
19815 do is add the <code>-rdynamic</code> option when linking our
19816 executable.</p>
19817
19818 <!-- CHAPTER -->
19819
19820
19821 <hr class="page-break"/>
19822 <h1><a name="17">17 MySQL Database</a></h1>
19823
19824 <p>To generate support code for the MySQL database you will need
19825 to pass the "<code>--database&nbsp;mysql</code>"
19826 (or "<code>-d&nbsp;mysql</code>") option to the ODB compiler.
19827 Your application will also need to link to the MySQL ODB runtime
19828 library (<code>libodb-mysql</code>). All MySQL-specific ODB
19829 classes are defined in the <code>odb::mysql</code> namespace.</p>
19830
19831 <h2><a name="17.1">17.1 MySQL Type Mapping</a></h2>
19832
19833 <p>The following table summarizes the default mapping between basic
19834 C++ value types and MySQL database types. This mapping can be
19835 customized on the per-type and per-member basis using the ODB
19836 Pragma Language (<a href="#14">Chapter 14, "ODB Pragma
19837 Language"</a>).</p>
19838
19839 <!-- border="1" is necessary for html2ps -->
19840 <table id="mapping" border="1">
19841 <tr>
19842 <th>C++ Type</th>
19843 <th>MySQL Type</th>
19844 <th>Default <code>NULL</code> Semantics</th>
19845 </tr>
19846
19847 <tr>
19848 <td><code>bool</code></td>
19849 <td><code>TINYINT(1)</code></td>
19850 <td><code>NOT NULL</code></td>
19851 </tr>
19852
19853 <tr>
19854 <td><code>char</code></td>
19855 <td><code>CHAR(1)</code></td>
19856 <td><code>NOT NULL</code></td>
19857 </tr>
19858
19859 <tr>
19860 <td><code>signed char</code></td>
19861 <td><code>TINYINT</code></td>
19862 <td><code>NOT NULL</code></td>
19863 </tr>
19864
19865 <tr>
19866 <td><code>unsigned char</code></td>
19867 <td><code>TINYINT UNSIGNED</code></td>
19868 <td><code>NOT NULL</code></td>
19869 </tr>
19870
19871 <tr>
19872 <td><code>short</code></td>
19873 <td><code>SMALLINT</code></td>
19874 <td><code>NOT NULL</code></td>
19875 </tr>
19876
19877 <tr>
19878 <td><code>unsigned short</code></td>
19879 <td><code>SMALLINT UNSIGNED</code></td>
19880 <td><code>NOT NULL</code></td>
19881 </tr>
19882
19883 <tr>
19884 <td><code>int</code></td>
19885 <td><code>INT</code></td>
19886 <td><code>NOT NULL</code></td>
19887 </tr>
19888
19889 <tr>
19890 <td><code>unsigned int</code></td>
19891 <td><code>INT UNSIGNED</code></td>
19892 <td><code>NOT NULL</code></td>
19893 </tr>
19894
19895 <tr>
19896 <td><code>long</code></td>
19897 <td><code>BIGINT</code></td>
19898 <td><code>NOT NULL</code></td>
19899 </tr>
19900
19901 <tr>
19902 <td><code>unsigned long</code></td>
19903 <td><code>BIGINT UNSIGNED</code></td>
19904 <td><code>NOT NULL</code></td>
19905 </tr>
19906
19907 <tr>
19908 <td><code>long long</code></td>
19909 <td><code>BIGINT</code></td>
19910 <td><code>NOT NULL</code></td>
19911 </tr>
19912
19913 <tr>
19914 <td><code>unsigned long long</code></td>
19915 <td><code>BIGINT UNSIGNED</code></td>
19916 <td><code>NOT NULL</code></td>
19917 </tr>
19918
19919 <tr>
19920 <td><code>float</code></td>
19921 <td><code>FLOAT</code></td>
19922 <td><code>NOT NULL</code></td>
19923 </tr>
19924
19925 <tr>
19926 <td><code>double</code></td>
19927 <td><code>DOUBLE</code></td>
19928 <td><code>NOT NULL</code></td>
19929 </tr>
19930
19931 <tr>
19932 <td><code>std::string</code></td>
19933 <td><code>TEXT/VARCHAR(255)</code></td>
19934 <td><code>NOT NULL</code></td>
19935 </tr>
19936
19937 <tr>
19938 <td><code>char[N]</code></td>
19939 <td><code>VARCHAR(N-1)</code></td>
19940 <td><code>NOT NULL</code></td>
19941 </tr>
19942 </table>
19943
19944 <p>It is possible to map the <code>char</code> C++ type to an integer
19945 database type (for example, <code>TINYINT</code>) using the
19946 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
19947 "<code>type</code>"</a>).</p>
19948
19949 <p>Note that the <code>std::string</code> type is mapped
19950 differently depending on whether a member of this type
19951 is an object id or not. If the member is an object id,
19952 then for this member <code>std::string</code> is mapped
19953 to the <code>VARCHAR(255)</code> MySQL type. Otherwise,
19954 it is mapped to <code>TEXT</code>.</p>
19955
19956 <p>Additionally, by default, C++ enums and C++11 enum classes are
19957 automatically mapped to suitable MySQL types. Contiguous
19958 enumerations with the zero first enumerator are mapped to
19959 the MySQL <code>ENUM</code> type. All other enumerations
19960 are mapped to the MySQL types corresponding to their
19961 underlying integral types (see table above). In both
19962 cases the default <code>NULL</code> semantics is
19963 <code>NOT NULL</code>. For example:</p>
19964
19965 <pre class="cxx">
19966 enum color {red, green, blue};
19967 enum class taste: unsigned char
19968 {
19969 bitter = 1, // Non-zero first enumerator.
19970 sweet,
19971 sour = 4, // Non-contiguous.
19972 salty
19973 };
19974
19975 #pragma db object
19976 class object
19977 {
19978 ...
19979
19980 color color_; // Mapped to ENUM ('red', 'green', 'blue') NOT NULL.
19981 taste taste_; // Mapped to TINYNT UNSIGNED NOT NULL.
19982 };
19983 </pre>
19984
19985 <p>It is also possible to add support for additional MySQL types,
19986 such as geospatial types. For more information, refer to
19987 <a href="#14.8">Section 14.8, "Database Type Mapping
19988 Pragmas"</a>.</p>
19989
19990 <h3><a name="17.1.1">17.1.1 String Type Mapping</a></h3>
19991
19992 <p>The MySQL ODB runtime library provides support for mapping the
19993 <code>std::string</code>, <code>char[N]</code>, and
19994 <code>std::array&lt;char, N></code> types to the MySQL <code>CHAR</code>,
19995 <code>VARCHAR</code>, <code>TEXT</code>, <code>NCHAR</code>, and
19996 <code>NVARCHAR</code> types. However, these mappings are not enabled
19997 by default (in particular, by default, <code>std::array</code> will
19998 be treated as a container). To enable the alternative mappings for
19999 these types we need to specify the database type explicitly using
20000 the <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section
20001 14.4.3, "<code>type</code>"</a>), for example:</p>
20002
20003 <pre class="cxx">
20004 #pragma db object
20005 class object
20006 {
20007 ...
20008
20009 #pragma db type("CHAR(2)")
20010 char state_[2];
20011
20012 #pragma db type("VARCHAR(128)")
20013 std::string name_;
20014 };
20015 </pre>
20016
20017 <p>Alternatively, this can be done on the per-type basis, for example:</p>
20018
20019 <pre class="cxx">
20020 #pragma db value(std::string) type("VARCHAR(128)")
20021
20022 #pragma db object
20023 class object
20024 {
20025 ...
20026
20027 std::string name_; // Mapped to VARCHAR(128).
20028 };
20029 </pre>
20030
20031 <p>The <code>char[N]</code> and <code>std::array&lt;char, N></code> values
20032 may or may not be zero-terminated. When extracting such values from the
20033 database, ODB will append the zero terminator if there is enough
20034 space.</p>
20035
20036 <h3><a name="17.1.2">17.1.2 Binary Type Mapping</a></h3>
20037
20038 <p>The MySQL ODB runtime library provides support for mapping the
20039 <code>std::vector&lt;char></code>,
20040 <code>std::vector&lt;unsigned&nbsp;char></code>,
20041 <code>char[N]</code>, <code>unsigned&nbsp;char[N]</code>,
20042 <code>std::array&lt;char, N></code>, and
20043 <code>std::array&lt;unsigned char, N></code>
20044 types to the MySQL <code>BINARY</code>, <code>VARBINARY</code>,
20045 and <code>BLOB</code> types. However, these mappings are not enabled
20046 by default (in particular, by default, <code>std::vector</code> and
20047 <code>std::array</code> will be treated as containers). To enable the
20048 alternative mappings for these types we need to specify the database
20049 type explicitly using the <code>db&nbsp;type</code> pragma
20050 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), for
20051 example:</p>
20052
20053 <pre class="cxx">
20054 #pragma db object
20055 class object
20056 {
20057 ...
20058
20059 #pragma db type("BLOB")
20060 std::vector&lt;char> buf_;
20061
20062 #pragma db type("BINARY(16)")
20063 unsigned char uuid_[16];
20064 };
20065 </pre>
20066
20067 <p>Alternatively, this can be done on the per-type basis, for example:</p>
20068
20069 <pre class="cxx">
20070 typedef std::vector&lt;char> buffer;
20071 #pragma db value(buffer) type("BLOB")
20072
20073 #pragma db object
20074 class object
20075 {
20076 ...
20077
20078 buffer buf_; // Mapped to BLOB.
20079 };
20080 </pre>
20081
20082 <p>Note also that in native queries (<a href="#4">Chapter 4, "Querying
20083 the Database"</a>) <code>char[N]</code> and
20084 <code>std::array&lt;char, N></code> parameters are by default passed
20085 as a string rather than a binary. To pass such parameters as a binary,
20086 we need to specify the database type explicitly in the
20087 <code>_val()</code>/<code>_ref()</code> calls. Note also that we
20088 don't need to do this for the integrated queries, for example:</p>
20089
20090 <pre class="cxx">
20091 char u[16] = {...};
20092
20093 db.query&lt;object> ("uuid = " + query::_val&lt;odb::mysql::id_blob> (u));
20094 db.query&lt;object> (query::uuid == query::_ref (u));
20095 </pre>
20096
20097 <h2><a name="17.2">17.2 MySQL Database Class</a></h2>
20098
20099 <p>The MySQL <code>database</code> class has the following
20100 interface:</p>
20101
20102 <pre class="cxx">
20103 namespace odb
20104 {
20105 namespace mysql
20106 {
20107 class database: public odb::database
20108 {
20109 public:
20110 database (const char* user,
20111 const char* passwd,
20112 const char* db,
20113 const char* host = 0,
20114 unsigned int port = 0,
20115 const char* socket = 0,
20116 const char* charset = 0,
20117 unsigned long client_flags = 0,
20118 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20119
20120 database (const std::string&amp; user,
20121 const std::string&amp; passwd,
20122 const std::string&amp; db,
20123 const std::string&amp; host = "",
20124 unsigned int port = 0,
20125 const std::string* socket = 0,
20126 const std::string&amp; charset = "",
20127 unsigned long client_flags = 0,
20128 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20129
20130 database (const std::string&amp; user,
20131 const std::string* passwd,
20132 const std::string&amp; db,
20133 const std::string&amp; host = "",
20134 unsigned int port = 0,
20135 const std::string* socket = 0,
20136 const std::string&amp; charset = "",
20137 unsigned long client_flags = 0,
20138 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20139
20140 database (const std::string&amp; user,
20141 const std::string&amp; passwd,
20142 const std::string&amp; db,
20143 const std::string&amp; host,
20144 unsigned int port,
20145 const std::string&amp; socket,
20146 const std::string&amp; charset = "",
20147 unsigned long client_flags = 0,
20148 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20149
20150 database (const std::string&amp; user,
20151 const std::string* passwd,
20152 const std::string&amp; db,
20153 const std::string&amp; host,
20154 unsigned int port,
20155 const std::string&amp; socket,
20156 const std::string&amp; charset = "",
20157 unsigned long client_flags = 0,
20158 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20159
20160 database (int&amp; argc,
20161 char* argv[],
20162 bool erase = false,
20163 const std::string&amp; charset = "",
20164 unsigned long client_flags = 0,
20165 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20166
20167 static void
20168 print_usage (std::ostream&amp;);
20169
20170 public:
20171 const char*
20172 user () const;
20173
20174 const char*
20175 password () const;
20176
20177 const char*
20178 db () const;
20179
20180 const char*
20181 host () const;
20182
20183 unsigned int
20184 port () const;
20185
20186 const char*
20187 socket () const;
20188
20189 const char*
20190 charset () const;
20191
20192 unsigned long
20193 client_flags () const;
20194
20195 public:
20196 connection_ptr
20197 connection ();
20198 };
20199 }
20200 }
20201 </pre>
20202
20203 <p>You will need to include the <code>&lt;odb/mysql/database.hxx></code>
20204 header file to make this class available in your application.</p>
20205
20206 <p>The overloaded <code>database</code> constructors allow us
20207 to specify MySQL database parameters that should be used when
20208 connecting to the database. In MySQL <code>NULL</code> and an
20209 empty string are treated as the same values for all the
20210 string parameters except <code>password</code> and
20211 <code>socket</code>.</p>
20212
20213 <p>The <code>charset</code> argument allows us to specify the client
20214 character set, that is, the character set in which the application
20215 will encode its text data. Note that this can be different from
20216 the MySQL server character set. If this argument is not specified or
20217 is empty, then the default MySQL client character set is used, normally
20218 <code>latin1</code>. Commonly used values for this argument are
20219 <code>latin1</code> (equivalent to Windows cp1252 and similar to
20220 ISO-8859-1) and <code>utf8</code>. For other possible values
20221 as well as more information on character set support in MySQL,
20222 refer to the MySQL documentation.</p>
20223
20224 <p>The <code>client_flags</code> argument allows us to specify various
20225 MySQL client library flags. For more information on the possible
20226 values, refer to the MySQL C API documentation. The
20227 <code>CLIENT_FOUND_ROWS</code> flag is always set by the MySQL ODB
20228 runtime regardless of whether it was passed in the
20229 <code>client_flags</code> argument.</p>
20230
20231 <p>The last constructor extracts the database parameters
20232 from the command line. The following options are recognized:</p>
20233
20234 <pre class="terminal">
20235 --user &lt;login>
20236 --password &lt;password>
20237 --database &lt;name>
20238 --host &lt;host>
20239 --port &lt;integer>
20240 --socket &lt;socket>
20241 --options-file &lt;file>
20242 </pre>
20243
20244 <p>The <code>--options-file</code> option allows us to specify some
20245 or all of the database options in a file with each option appearing
20246 on a separate line followed by a space and an option value.</p>
20247
20248 <p>If the <code>erase</code> argument to this constructor is true,
20249 then the above options are removed from the <code>argv</code>
20250 array and the <code>argc</code> count is updated accordingly.
20251 This is primarily useful if your application accepts other
20252 options or arguments and you would like to get the MySQL
20253 options out of the <code>argv</code> array.</p>
20254
20255 <p>This constructor throws the <code>odb::mysql::cli_exception</code>
20256 exception if the MySQL option values are missing or invalid.
20257 See section <a href="#17.4">Section 17.4, "MySQL Exceptions"</a>
20258 for more information on this exception.</p>
20259
20260 <p>The static <code>print_usage()</code> function prints the list of options
20261 with short descriptions that are recognized by this constructor.</p>
20262
20263 <p>The last argument to all of the constructors is a pointer to the
20264 connection factory. In C++98/03, it is <code>std::auto_ptr</code> while
20265 in C++11 <code>std::unique_ptr</code> is used instead. If we pass a
20266 non-<code>NULL</code> value, the database instance assumes ownership
20267 of the factory instance. The connection factory interface as well as
20268 the available implementations are described in the next section.</p>
20269
20270 <p>The set of accessor functions following the constructors allows us
20271 to query the parameters of the <code>database</code> instance.</p>
20272
20273 <p>The <code>connection()</code> function returns a pointer to the
20274 MySQL database connection encapsulated by the
20275 <code>odb::mysql::connection</code> class. For more information
20276 on <code>mysql::connection</code>, refer to <a href="#17.3">Section
20277 17.3, "MySQL Connection and Connection Factory"</a>.</p>
20278
20279 <h2><a name="17.3">17.3 MySQL Connection and Connection Factory</a></h2>
20280
20281 <p>The <code>mysql::connection</code> class has the following interface:</p>
20282
20283 <pre class="cxx">
20284 namespace odb
20285 {
20286 namespace mysql
20287 {
20288 class connection: public odb::connection
20289 {
20290 public:
20291 connection (database&amp;);
20292 connection (database&amp;, MYSQL*);
20293
20294 MYSQL*
20295 handle ();
20296 };
20297
20298 typedef details::shared_ptr&lt;connection> connection_ptr;
20299 }
20300 }
20301 </pre>
20302
20303 <p>For more information on the <code>odb::connection</code> interface,
20304 refer to <a href="#3.6">Section 3.6, "Connections"</a>. The first
20305 overloaded <code>mysql::connection</code> constructor establishes a
20306 new MySQL connection. The second constructor allows us to create
20307 a <code>connection</code> instance by providing an already connected
20308 native MySQL handle. Note that the <code>connection</code>
20309 instance assumes ownership of this handle. The <code>handle()</code>
20310 accessor returns the MySQL handle corresponding to the connection.</p>
20311
20312 <p>The <code>mysql::connection_factory</code> abstract class has the
20313 following interface:</p>
20314
20315 <pre class="cxx">
20316 namespace odb
20317 {
20318 namespace mysql
20319 {
20320 class connection_factory
20321 {
20322 public:
20323 virtual void
20324 database (database&amp;) = 0;
20325
20326 virtual connection_ptr
20327 connect () = 0;
20328 };
20329 }
20330 }
20331 </pre>
20332
20333 <p>The <code>database()</code> function is called when a connection
20334 factory is associated with a database instance. This happens in
20335 the <code>odb::mysql::database</code> class constructors. The
20336 <code>connect()</code> function is called whenever a database
20337 connection is requested.</p>
20338
20339 <p>The two implementations of the <code>connection_factory</code>
20340 interface provided by the MySQL ODB runtime are
20341 <code>new_connection_factory</code> and
20342 <code>connection_pool_factory</code>. You will need to include
20343 the <code>&lt;odb/mysql/connection-factory.hxx></code>
20344 header file to make the <code>connection_factory</code> interface
20345 and these implementation classes available in your application.</p>
20346
20347 <p>The <code>new_connection_factory</code> class creates a new
20348 connection whenever one is requested. When a connection is no
20349 longer needed, it is released and closed. The
20350 <code>new_connection_factory</code> class has the following
20351 interface:</p>
20352
20353 <pre class="cxx">
20354 namespace odb
20355 {
20356 namespace mysql
20357 {
20358 class new_connection_factory: public connection_factory
20359 {
20360 public:
20361 new_connection_factory ();
20362 };
20363 };
20364 </pre>
20365
20366 <p>The <code>connection_pool_factory</code> class implements a
20367 connection pool. It has the following interface:</p>
20368
20369 <pre class="cxx">
20370 namespace odb
20371 {
20372 namespace mysql
20373 {
20374 class connection_pool_factory: public connection_factory
20375 {
20376 public:
20377 connection_pool_factory (std::size_t max_connections = 0,
20378 std::size_t min_connections = 0,
20379 bool ping = true);
20380
20381 protected:
20382 class pooled_connection: public connection
20383 {
20384 public:
20385 pooled_connection (database_type&amp;);
20386 pooled_connection (database_type&amp;, MYSQL*);
20387 };
20388
20389 typedef details::shared_ptr&lt;pooled_connection> pooled_connection_ptr;
20390
20391 virtual pooled_connection_ptr
20392 create ();
20393 };
20394 };
20395 </pre>
20396
20397 <p>The <code>max_connections</code> argument in the
20398 <code>connection_pool_factory</code> constructor specifies the maximum
20399 number of concurrent connections that this pool factory will
20400 maintain. Similarly, the <code>min_connections</code> argument
20401 specifies the minimum number of available connections that
20402 should be kept open. The <code>ping</code> argument specifies
20403 whether the factory should validate the connection before
20404 returning it to the caller.</p>
20405
20406 <p>Whenever a connection is requested, the pool factory first
20407 checks if there is an unused connection that can be returned.
20408 If there is none, the pool factory checks the
20409 <code>max_connections</code> value to see if a new connection
20410 can be created. If the total number of connections maintained
20411 by the pool is less than this value, then a new connection is
20412 created and returned. Otherwise, the caller is blocked until
20413 a connection becomes available.</p>
20414
20415 <p>When a connection is released, the pool factory first checks
20416 if there are blocked callers waiting for a connection. If so, then
20417 one of them is unblocked and is given the connection. Otherwise,
20418 the pool factory checks whether the total number of connections
20419 maintained by the pool is greater than the <code>min_connections</code>
20420 value. If that's the case, the connection is closed. Otherwise, the
20421 connection is added to the pool of available connections to be
20422 returned on the next request. In other words, if the number of
20423 connections maintained by the pool exceeds <code>min_connections</code>
20424 and there are no callers waiting for a new connection,
20425 then the pool will close the excess connections.</p>
20426
20427 <p>If the <code>max_connections</code> value is 0, then the pool will
20428 create a new connection whenever all of the existing connections
20429 are in use. If the <code>min_connections</code> value is 0, then
20430 the pool will never close a connection and instead maintain all
20431 the connections that were ever created.</p>
20432
20433 <p>Connection validation (the <code>ping</code> argument) is useful
20434 if your application may experience long periods of inactivity. In
20435 such cases the MySQL server may close network connections that have
20436 been inactive for too long. If during connection validation the pool
20437 factory detects that the connection has been terminated, it silently
20438 closes it and tries to find or create another connection instead.</p>
20439
20440 <p>The <code>create()</code> virtual function is called whenever the
20441 pool needs to create a new connection. By deriving from the
20442 <code>connection_pool_factory</code> class and overriding this
20443 function we can implement custom connection establishment
20444 and configuration.</p>
20445
20446 <p>If you pass <code>NULL</code> as the connection factory to
20447 one of the <code>database</code> constructors, then the
20448 <code>connection_pool_factory</code> instance will be
20449 created by default with the min and max connections values
20450 set to <code>0</code> and connection validation enabled.
20451 The following code fragment shows how we can pass our own
20452 connection factory instance:</p>
20453
20454 <pre class="cxx">
20455 #include &lt;odb/database.hxx>
20456
20457 #include &lt;odb/mysql/database.hxx>
20458 #include &lt;odb/mysql/connection-factory.hxx>
20459
20460 int
20461 main (int argc, char* argv[])
20462 {
20463 auto_ptr&lt;odb::mysql::connection_factory> f (
20464 new odb::mysql::connection_pool_factory (20));
20465
20466 auto_ptr&lt;odb::database> db (
20467 new mysql::database (argc, argv, false, 0, f));
20468 }
20469 </pre>
20470
20471 <h2><a name="17.4">17.4 MySQL Exceptions</a></h2>
20472
20473 <p>The MySQL ODB runtime library defines the following MySQL-specific
20474 exceptions:</p>
20475
20476 <pre class="cxx">
20477 namespace odb
20478 {
20479 namespace mysql
20480 {
20481 class database_exception: odb::database_exception
20482 {
20483 public:
20484 unsigned int
20485 error () const;
20486
20487 const std::string&amp;
20488 sqlstate () const;
20489
20490 const std::string&amp;
20491 message () const;
20492
20493 virtual const char*
20494 what () const throw ();
20495 };
20496
20497 class cli_exception: odb::exception
20498 {
20499 public:
20500 virtual const char*
20501 what () const throw ();
20502 };
20503 }
20504 }
20505 </pre>
20506
20507 <p>You will need to include the <code>&lt;odb/mysql/exceptions.hxx></code>
20508 header file to make these exceptions available in your application.</p>
20509
20510 <p>The <code>odb::mysql::database_exception</code> is thrown if
20511 a MySQL database operation fails. The MySQL-specific error
20512 information is accessible via the <code>error()</code>,
20513 <code>sqlstate()</code>, and <code>message()</code> functions.
20514 All this information is also combined and returned in a
20515 human-readable form by the <code>what()</code> function.</p>
20516
20517 <p>The <code>odb::mysql::cli_exception</code> is thrown by the
20518 command line parsing constructor of the <code>odb::mysql::database</code>
20519 class if the MySQL option values are missing or invalid. The
20520 <code>what()</code> function returns a human-readable description
20521 of an error.</p>
20522
20523 <h2><a name="17.5">17.5 MySQL Limitations</a></h2>
20524
20525 <p>The following sections describe MySQL-specific limitations imposed
20526 by the current MySQL and ODB runtime versions.</p>
20527
20528 <h3><a name="17.5.1">17.5.1 Foreign Key Constraints</a></h3>
20529
20530 <p>ODB relies on standard SQL behavior which requires that foreign
20531 key constraints checking is deferred until the transaction is
20532 committed. The only behaviors supported by MySQL are to either
20533 check such constraints immediately (InnoDB engine) or to ignore
20534 foreign key constraints altogether (all other engines). As a
20535 result, by default, schemas generated by the ODB compiler for
20536 MySQL have foreign key definitions commented out. They are
20537 retained only for documentation.</p>
20538
20539 <p>You can override the default behavior and instruct the ODB
20540 compiler to generate non-deferrable foreign keys by specifying
20541 the <code>--fkeys-deferrable-mode not_deferrable</code> ODB
20542 compiler option. Note, however, that in this case the order in
20543 which you persist, update, and erase objects within a transaction
20544 becomes important.</p>
20545
20546 <h2><a name="17.6">17.6 MySQL Index Definitions</a></h2>
20547
20548 <p>When the <code>index</code> pragma (<a href="#14.7">Section 14.7,
20549 "Index Definition Pragmas"</a>) is used to define a MySQL index,
20550 the <code>type</code> clause specifies the index type (for example,
20551 <code>UNIQUE</code>, <code>FULLTEXT</code>, <code>SPATIAL</code>),
20552 the <code>method</code> clause specifies the index method (for
20553 example, <code>BTREE</code>, <code>HASH</code>), and the
20554 <code>options</code> clause is not used. The column options
20555 can be used to specify column length limits and the sort order.
20556 For example:</p>
20557
20558 <pre class="cxx">
20559 #pragma db object
20560 class object
20561 {
20562 ...
20563
20564 std::string name_;
20565
20566 #pragma db index method("HASH") member(name_, "(100) DESC")
20567 };
20568 </pre>
20569
20570 <h2><a name="17.7">17.7 MySQL Stored Procedures</a></h2>
20571
20572 <p>ODB native views (<a href="#10.6">Section 10.6, "Native Views"</a>)
20573 can be used to call MySQL stored procedures. For example, assuming
20574 we are using the <code>person</code> class from <a href="#2">Chapter
20575 2, "Hello World Example"</a> (and the corresponding <code>person</code>
20576 table), we can create a stored procedure that given the min and max
20577 ages returns some information about all the people in that range:</p>
20578
20579 <pre class="sql">
20580 CREATE PROCEDURE person_range (
20581 IN min_age SMALLINT,
20582 IN max_age SMALLINT)
20583 BEGIN
20584 SELECT age, first, last FROM person
20585 WHERE age >= min_age AND age &lt;= max_age;
20586 END
20587 </pre>
20588
20589 <p>Given the above stored procedure we can then define an ODB view
20590 that can be used to call it and retrieve its result:</p>
20591
20592 <pre class="cxx">
20593 #pragma db view query("CALL person_range((?))")
20594 struct person_range
20595 {
20596 unsigned short age;
20597 std::string first;
20598 std::string last;
20599 };
20600 </pre>
20601
20602 <p>The following example shows how we can use the above view to
20603 print the list of people in a specific age range:</p>
20604
20605 <pre class="cxx">
20606 typedef odb::query&lt;person_range> query;
20607 typedef odb::result&lt;person_range> result;
20608
20609 transaction t (db.begin ());
20610
20611 result r (
20612 db.query&lt;person_range> (
20613 query::_val (1) + "," + query::_val (18)));
20614
20615 for (result::iterator i (r.begin ()); i != r.end (); ++i)
20616 cerr &lt;&lt; i->first &lt;&lt; " " &lt;&lt; i->last &lt;&lt; " " &lt;&lt; i->age &lt;&lt; endl;
20617
20618 t.commit ();
20619 </pre>
20620
20621 <p>Note that as with all native views, the order and types of data members
20622 must match those of columns in the <code>SELECT</code> list inside
20623 the stored procedure.</p>
20624
20625 <p>There are also a number of limitations when it comes to support for
20626 MySQL stored procedures in ODB views. First of all, you have to use
20627 MySQL server and client libraries version 5.5.3 or later since this
20628 is the version in which support for calling stored procedures with
20629 prepared statements was first added (the
20630 <code>mysql_stmt_next_result()</code> function).</p>
20631
20632 <p>In MySQL, a stored procedure can produce multiple results.
20633 For example, if a stored procedure executes several
20634 <code>SELECT</code> statements, then the result of calling such
20635 a procedure consists of two row sets, one for each <code>SELECT</code>
20636 statement. Additionally, if the procedure has any <code>OUT</code>
20637 or <code>INOUT</code> parameters, then their values are returned as
20638 an additional special row set containing only a single row.
20639 Because such multiple row sets can contain varying number
20640 and type of columns, they cannot be all extracted into a
20641 single view. As a result, an ODB view will only extract the
20642 data from the first row set and ignore all the subsequent
20643 ones.</p>
20644
20645 <p>In particular, this means that we can use an ODB view to extract
20646 the values of the <code>OUT</code> and <code>INOUT</code>
20647 parameters provided that the stored procedure does not generate
20648 any other row sets. For example:</p>
20649
20650 <pre class="sql">
20651 CREATE PROCEDURE person_min_max_age (
20652 OUT min_age SMALLINT,
20653 OUT max_age SMALLINT)
20654 BEGIN
20655 SELECT MIN(age), MAX(age) INTO min_age, max_age FROM person;
20656 END
20657 </pre>
20658
20659 <pre class="cxx">
20660 #pragma db view query("CALL person_min_max_age((?))")
20661 struct person_min_max_age
20662 {
20663 unsigned short min_age;
20664 unsigned short max_age;
20665 };
20666 </pre>
20667
20668 <pre class="cxx">
20669 typedef odb::query&lt;person_min_max_age> query;
20670
20671 transaction t (db.begin ());
20672
20673 // We know this query always returns a single row, so use query_value().
20674 // We have to pass dummy values for OUT parameters.
20675 //
20676 person_min_max_age mma (
20677 db.query_value&lt;person_min_max_age> (
20678 query::_val (0) + "," + query::_val (0)));
20679
20680 cerr &lt;&lt; mma.min_age &lt;&lt; " " &lt;&lt; mma.max_age &lt;&lt; endl;
20681
20682 t.commit ();
20683 </pre>
20684
20685 <p>Another limitation that stems from having multiple results is the
20686 inability to cache the result of a stored procedure call. In
20687 other words, a MySQL stored procedure call always produces an
20688 uncached query result (<a href="#4.4">Section 4.4, "Query
20689 Result"</a>).</p>
20690
20691 <hr class="page-break"/>
20692 <h1><a name="18">18 SQLite Database</a></h1>
20693
20694 <p>To generate support code for the SQLite database you will need
20695 to pass the "<code>--database&nbsp;sqlite</code>"
20696 (or "<code>-d&nbsp;sqlite</code>") option to the ODB compiler.
20697 Your application will also need to link to the SQLite ODB runtime
20698 library (<code>libodb-sqlite</code>). All SQLite-specific ODB
20699 classes are defined in the <code>odb::sqlite</code> namespace.</p>
20700
20701 <h2><a name="18.1">18.1 SQLite Type Mapping</a></h2>
20702
20703 <p>The following table summarizes the default mapping between basic
20704 C++ value types and SQLite database types. This mapping can be
20705 customized on the per-type and per-member basis using the ODB
20706 Pragma Language (<a href="#14">Chapter 14, "ODB Pragma
20707 Language"</a>).</p>
20708
20709 <!-- border="1" is necessary for html2ps -->
20710 <table id="mapping" border="1">
20711 <tr>
20712 <th>C++ Type</th>
20713 <th>SQLite Type</th>
20714 <th>Default <code>NULL</code> Semantics</th>
20715 </tr>
20716
20717 <tr>
20718 <td><code>bool</code></td>
20719 <td><code>INTEGER</code></td>
20720 <td><code>NOT NULL</code></td>
20721 </tr>
20722
20723 <tr>
20724 <td><code>char</code></td>
20725 <td><code>TEXT</code></td>
20726 <td><code>NOT NULL</code></td>
20727 </tr>
20728
20729 <tr>
20730 <td><code>signed char</code></td>
20731 <td><code>INTEGER</code></td>
20732 <td><code>NOT NULL</code></td>
20733 </tr>
20734
20735 <tr>
20736 <td><code>unsigned char</code></td>
20737 <td><code>INTEGER</code></td>
20738 <td><code>NOT NULL</code></td>
20739 </tr>
20740
20741 <tr>
20742 <td><code>short</code></td>
20743 <td><code>INTEGER</code></td>
20744 <td><code>NOT NULL</code></td>
20745 </tr>
20746
20747 <tr>
20748 <td><code>unsigned short</code></td>
20749 <td><code>INTEGER</code></td>
20750 <td><code>NOT NULL</code></td>
20751 </tr>
20752
20753 <tr>
20754 <td><code>int</code></td>
20755 <td><code>INTEGER</code></td>
20756 <td><code>NOT NULL</code></td>
20757 </tr>
20758
20759 <tr>
20760 <td><code>unsigned int</code></td>
20761 <td><code>INTEGER</code></td>
20762 <td><code>NOT NULL</code></td>
20763 </tr>
20764
20765 <tr>
20766 <td><code>long</code></td>
20767 <td><code>INTEGER</code></td>
20768 <td><code>NOT NULL</code></td>
20769 </tr>
20770
20771 <tr>
20772 <td><code>unsigned long</code></td>
20773 <td><code>INTEGER</code></td>
20774 <td><code>NOT NULL</code></td>
20775 </tr>
20776
20777 <tr>
20778 <td><code>long long</code></td>
20779 <td><code>INTEGER</code></td>
20780 <td><code>NOT NULL</code></td>
20781 </tr>
20782
20783 <tr>
20784 <td><code>unsigned long long</code></td>
20785 <td><code>INTEGER</code></td>
20786 <td><code>NOT NULL</code></td>
20787 </tr>
20788
20789 <tr>
20790 <td><code>float</code></td>
20791 <td><code>REAL</code></td>
20792 <td><code>NULL</code></td>
20793 </tr>
20794
20795 <tr>
20796 <td><code>double</code></td>
20797 <td><code>REAL</code></td>
20798 <td><code>NULL</code></td>
20799 </tr>
20800
20801 <tr>
20802 <td><code>std::string</code></td>
20803 <td><code>TEXT</code></td>
20804 <td><code>NOT NULL</code></td>
20805 </tr>
20806
20807 <tr>
20808 <td><code>char[N]</code></td>
20809 <td><code>TEXT</code></td>
20810 <td><code>NOT NULL</code></td>
20811 </tr>
20812
20813 <tr>
20814 <td><code>std::wstring (Windows only)</code></td>
20815 <td><code>TEXT</code></td>
20816 <td><code>NOT NULL</code></td>
20817 </tr>
20818
20819 <tr>
20820 <td><code>wchar_t[N] (Windows only)</code></td>
20821 <td><code>TEXT</code></td>
20822 <td><code>NOT NULL</code></td>
20823 </tr>
20824 </table>
20825
20826 <p>It is possible to map the <code>char</code> C++ type to the
20827 <code>INTEGER</code> SQLite type using the <code>db&nbsp;type</code>
20828 pragma (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>).</p>
20829
20830 <p>SQLite represents the <code>NaN</code> <code>FLOAT</code> value
20831 as a <code>NULL</code> value. As a result, columns of the
20832 <code>float</code> and <code>double</code> types are by default
20833 declared as <code>NULL</code>. However, you can override this by
20834 explicitly declaring them as <code>NOT NULL</code> with the
20835 <code>db&nbsp;not_null</code> pragma (<a href="#14.4.6">Section
20836 14.4.6, "<code>null/not_null</code>"</a>).</p>
20837
20838 <p>Additionally, by default, C++ enums and C++11 enum classes are
20839 automatically mapped to the SQLite <code>INTEGER</code> type with
20840 the default <code>NULL</code> semantics being <code>NOT NULL</code>.
20841 For example:</p>
20842
20843 <pre class="cxx">
20844 enum color {red, green, blue};
20845 enum class taste: unsigned char
20846 {
20847 bitter = 1,
20848 sweet,
20849 sour = 4,
20850 salty
20851 };
20852
20853 #pragma db object
20854 class object
20855 {
20856 ...
20857
20858 color color_; // Automatically mapped to INTEGER.
20859 taste taste_; // Automatically mapped to INTEGER.
20860 };
20861 </pre>
20862
20863 <p>Note also that SQLite only operates with signed integers and the largest
20864 value that an SQLite database can store is a signed 64-bit integer. As
20865 a result, greater <code>unsigned&nbsp;long</code> and
20866 <code>unsigned&nbsp;long&nbsp;long</code> values will be represented in
20867 the database as negative values.</p>
20868
20869 <p>It is also possible to add support for additional SQLite types,
20870 such as <code>NUMERIC</code>. For more information, refer to
20871 <a href="#14.8">Section 14.8, "Database Type Mapping
20872 Pragmas"</a>.</p>
20873
20874 <h3><a name="18.1.1">18.1.1 String Type Mapping</a></h3>
20875
20876 <p>The SQLite ODB runtime library provides support for mapping the
20877 <code>std::array&lt;char, N></code> and, on Windows,
20878 <code>std::array&lt;wchar_t, N></code> types to the SQLite
20879 <code>TEXT</code> type. However, this mapping is not enabled by
20880 default (in particular, by default, <code>std::array</code> will
20881 be treated as a container). To enable the alternative mapping for
20882 this type we need to specify the database type explicitly using
20883 the <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section
20884 14.4.3, "<code>type</code>"</a>), for example:</p>
20885
20886 <pre class="cxx">
20887 #pragma db object
20888 class object
20889 {
20890 ...
20891
20892 #pragma db type("TEXT")
20893 std::array&lt;char, 128> name_;
20894 };
20895 </pre>
20896
20897 <p>Alternatively, this can be done on the per-type basis, for example:</p>
20898
20899 <pre class="cxx">
20900 typedef std::array&lt;char, 128> name_type;
20901 #pragma db value(name_type) type("TEXT")
20902
20903 #pragma db object
20904 class object
20905 {
20906 ...
20907
20908 name_type name_; // Mapped to TEXT.
20909 };
20910 </pre>
20911
20912 <p>The <code>char[N]</code>, <code>std::array&lt;char, N></code>,
20913 <code>wchar_t[N]</code>, and <code>std::array&lt;wchar_t, N></code>
20914 values may or may not be zero-terminated. When extracting such values
20915 from the database, ODB will append the zero terminator if there is
20916 enough space.</p>
20917
20918 <h3><a name="18.1.2">18.1.2 Binary Type Mapping</a></h3>
20919
20920 <p>The SQLite ODB runtime library provides support for mapping the
20921 <code>std::vector&lt;char></code>,
20922 <code>std::vector&lt;unsigned&nbsp;char></code>,
20923 <code>char[N]</code>, <code>unsigned&nbsp;char[N]</code>,
20924 <code>std::array&lt;char, N></code>, and
20925 <code>std::array&lt;unsigned char, N></code>
20926 types to the SQLite <code>BLOB</code> type. However, these mappings
20927 are not enabled by default (in particular, by default,
20928 <code>std::vector</code> and <code>std::array</code> will be treated
20929 as containers). To enable the alternative mappings for these types
20930 we need to specify the database type explicitly using the
20931 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
20932 "<code>type</code>"</a>), for example:</p>
20933
20934 <pre class="cxx">
20935 #pragma db object
20936 class object
20937 {
20938 ...
20939
20940 #pragma db type("BLOB")
20941 std::vector&lt;char> buf_;
20942
20943 #pragma db type("BLOB")
20944 unsigned char uuid_[16];
20945 };
20946 </pre>
20947
20948 <p>Alternatively, this can be done on the per-type basis, for example:</p>
20949
20950 <pre class="cxx">
20951 typedef std::vector&lt;char> buffer;
20952 #pragma db value(buffer) type("BLOB")
20953
20954 #pragma db object
20955 class object
20956 {
20957 ...
20958
20959 buffer buf_; // Mapped to BLOB.
20960 };
20961 </pre>
20962
20963 <p>Note also that in native queries (<a href="#4">Chapter 4, "Querying
20964 the Database"</a>) <code>char[N]</code> and
20965 <code>std::array&lt;char, N></code> parameters are by default passed
20966 as a string rather than a binary. To pass such parameters as a binary,
20967 we need to specify the database type explicitly in the
20968 <code>_val()</code>/<code>_ref()</code> calls. Note also that we
20969 don't need to do this for the integrated queries, for example:</p>
20970
20971 <pre class="cxx">
20972 char u[16] = {...};
20973
20974 db.query&lt;object> ("uuid = " + query::_val&lt;odb::sqlite::id_blob> (u));
20975 db.query&lt;object> (query::uuid == query::_ref (u));
20976 </pre>
20977
20978 <h2><a name="18.2">18.2 SQLite Database Class</a></h2>
20979
20980 <p>The SQLite <code>database</code> class has the following
20981 interface:</p>
20982
20983 <pre class="cxx">
20984 namespace odb
20985 {
20986 namespace sqlite
20987 {
20988 class database: public odb::database
20989 {
20990 public:
20991 database (const std::string&amp; name,
20992 int flags = SQLITE_OPEN_READWRITE,
20993 bool foreign_keys = true,
20994 const std::string&amp; vfs = "",
20995 std::[auto|unique]_ptr&lt;connection_factory> = 0);
20996
20997 #ifdef _WIN32
20998 database (const std::wstring&amp; name,
20999 int flags = SQLITE_OPEN_READWRITE,
21000 bool foreign_keys = true,
21001 const std::string&amp; vfs = "",
21002 std::[auto|unique]_ptr&lt;connection_factory> = 0);
21003 #endif
21004
21005 database (int&amp; argc,
21006 char* argv[],
21007 bool erase = false,
21008 int flags = SQLITE_OPEN_READWRITE,
21009 bool foreign_keys = true,
21010 const std::string&amp; vfs = "",
21011 std::[auto|unique]_ptr&lt;connection_factory> = 0);
21012
21013 static void
21014 print_usage (std::ostream&amp;);
21015
21016 public:
21017 const std::string&amp;
21018 name () const;
21019
21020 int
21021 flags () const;
21022
21023 public:
21024 transaction
21025 begin_immediate ();
21026
21027 transaction
21028 begin_exclusive ();
21029
21030 public:
21031 connection_ptr
21032 connection ();
21033 };
21034 }
21035 }
21036 </pre>
21037
21038 <p>You will need to include the <code>&lt;odb/sqlite/database.hxx></code>
21039 header file to make this class available in your application.</p>
21040
21041 <p>The first constructor opens the specified SQLite database. The
21042 <code>name</code> argument is the database file name to open in
21043 the UTF-8 encoding. If this argument is empty, then a temporary,
21044 on-disk database is created. If this argument is the
21045 <code>:memory:</code> special value, then a temporary, in-memory
21046 database is created. The <code>flags</code> argument allows us to
21047 specify SQLite opening flags. For more information on the possible
21048 values, refer to the <code>sqlite3_open_v2()</code> function description
21049 in the SQLite C API documentation. The <code>foreign_keys</code>
21050 argument specifies whether foreign key constraints checking
21051 should be enabled. See <a href="#18.5.3">Section 18.5.3,
21052 "Foreign Key Constraints"</a> for more information on foreign
21053 keys. The <code>vfs</code> argument specifies the SQLite
21054 virtual file system module that should be used to access the
21055 database. If this argument is empty, then the default vfs module
21056 is used. Again, refer to the <code>sqlite3_open_v2()</code> function
21057 documentation for detail.</p>
21058
21059 <p>The following example shows how we can open the <code>test.db</code>
21060 database in the read-write mode and create it if it does not exist:</p>
21061
21062 <pre class="cxx">
21063 auto_ptr&lt;odb::database> db (
21064 new odb::sqlite::database (
21065 "test.db",
21066 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE));
21067 </pre>
21068
21069 <p>The second constructor is the same as the first except that the database
21070 name is passes as <code>std::wstring</code> in the UTF-16 encoding. This
21071 constructor is only available when compiling for Windows.</p>
21072
21073 <p>The third constructor extracts the database parameters from the
21074 command line. The following options are recognized:</p>
21075
21076 <pre class="terminal">
21077 --database &lt;name>
21078 --create
21079 --read-only
21080 --options-file &lt;file>
21081 </pre>
21082
21083 <p>By default, this constructor opens the database in the read-write mode
21084 (<code>SQLITE_OPEN_READWRITE</code> flag). If the <code>--create</code>
21085 flag is specified, then the database file is created if it does
21086 not already exist (<code>SQLITE_OPEN_CREATE</code> flag). If the
21087 <code>--read-only</code> flag is specified, then the database is
21088 opened in the read-only mode (<code>SQLITE_OPEN_READONLY</code>
21089 flag instead of <code>SQLITE_OPEN_READWRITE</code>). The
21090 <code>--options-file</code> option allows us to specify some
21091 or all of the database options in a file with each option appearing
21092 on a separate line followed by a space and an option value.</p>
21093
21094 <p>If the <code>erase</code> argument to this constructor is true,
21095 then the above options are removed from the <code>argv</code>
21096 array and the <code>argc</code> count is updated accordingly.
21097 This is primarily useful if your application accepts other
21098 options or arguments and you would like to get the SQLite
21099 options out of the <code>argv</code> array.</p>
21100
21101 <p>The <code>flags</code> argument has the same semantics as in
21102 the first constructor. Flags from the command line always override
21103 the corresponding values specified with this argument.</p>
21104
21105 <p>The third constructor throws the <code>odb::sqlite::cli_exception</code>
21106 exception if the SQLite option values are missing or invalid.
21107 See <a href="#18.4">Section 18.4, "SQLite Exceptions"</a>
21108 for more information on this exception.</p>
21109
21110 <p>The static <code>print_usage()</code> function prints the list of options
21111 with short descriptions that are recognized by the third constructor.</p>
21112
21113 <p>The last argument to all of the constructors is a pointer to the
21114 connection factory. In C++98/03, it is <code>std::auto_ptr</code> while
21115 in C++11 <code>std::unique_ptr</code> is used instead. If we pass a
21116 non-<code>NULL</code> value, the database instance assumes ownership
21117 of the factory instance. The connection factory interface as well as
21118 the available implementations are described in the next section.</p>
21119
21120 <p>The set of accessor functions following the constructors allows us
21121 to query the parameters of the <code>database</code> instance.</p>
21122
21123 <p>The <code>begin_immediate()</code> and <code>begin_exclusive()</code>
21124 functions are the SQLite-specific extensions to the standard
21125 <code>odb::database::begin()</code> function (see
21126 <a href="#3.5">Section 3.5, "Transactions"</a>). They allow us
21127 to start an immediate (<code>BEGIN IMMEDIATE</code>) and an exclusive
21128 (<code>BEGIN EXCLUSIVE</code>) SQLite transaction, respectively.
21129 For more information on the semantics of the immediate and exclusive
21130 transactions, refer to the <code>BEGIN</code> statement description
21131 in the SQLite documentation.</p>
21132
21133 <p>The <code>connection()</code> function returns a pointer to the
21134 SQLite database connection encapsulated by the
21135 <code>odb::sqlite::connection</code> class. For more information
21136 on <code>sqlite::connection</code>, refer to <a href="#18.3">Section
21137 18.3, "SQLite Connection and Connection Factory"</a>.</p>
21138
21139 <h2><a name="18.3">18.3 SQLite Connection and Connection Factory</a></h2>
21140
21141 <p>The <code>sqlite::connection</code> class has the following interface:</p>
21142
21143 <pre class="cxx">
21144 namespace odb
21145 {
21146 namespace sqlite
21147 {
21148 class connection: public odb::connection
21149 {
21150 public:
21151 connection (database&amp;, int extra_flags = 0);
21152 connection (database&amp;, sqlite3*);
21153
21154 transaction
21155 begin_immediate ();
21156
21157 transaction
21158 begin_exclusive ();
21159
21160 sqlite3*
21161 handle ();
21162 };
21163
21164 typedef details::shared_ptr&lt;connection> connection_ptr;
21165 }
21166 }
21167 </pre>
21168
21169 <p>For more information on the <code>odb::connection</code> interface,
21170 refer to <a href="#3.6">Section 3.6, "Connections"</a>. The first
21171 overloaded <code>sqlite::connection</code> constructor opens
21172 a new SQLite connection. The <code>extra_flags</code> argument can
21173 be used to specify extra <code>sqlite3_open_v2()</code> flags
21174 that are combined with the flags specified in the
21175 <code>sqlite::database</code> constructor. The second constructor
21176 allows us to create a <code>connection</code> instance by providing
21177 an already open native SQLite handle. Note that the
21178 <code>connection</code> instance assumes ownership of this handle.</p>
21179
21180 <p>The <code>begin_immediate()</code> and <code>begin_exclusive()</code>
21181 functions allow us to start an immediate and an exclusive SQLite
21182 transaction on the connection, respectively. Their semantics are
21183 equivalent to the corresponding functions defined in the
21184 <code>sqlite::database</code> class (<a href="#18.2">Section 18.2,
21185 "SQLite Database Class"</a>). The <code>handle()</code> accessor
21186 returns the SQLite handle corresponding to the connection.</p>
21187
21188 <p>The <code>sqlite::connection_factory</code> abstract class has the
21189 following interface:</p>
21190
21191 <pre class="cxx">
21192 namespace odb
21193 {
21194 namespace sqlite
21195 {
21196 class connection_factory
21197 {
21198 public:
21199 virtual void
21200 database (database&amp;) = 0;
21201
21202 virtual connection_ptr
21203 connect () = 0;
21204 };
21205 }
21206 }
21207 </pre>
21208
21209 <p>The <code>database()</code> function is called when a connection
21210 factory is associated with a database instance. This happens in
21211 the <code>odb::sqlite::database</code> class constructors. The
21212 <code>connect()</code> function is called whenever a database
21213 connection is requested.</p>
21214
21215 <p>The three implementations of the <code>connection_factory</code>
21216 interface provided by the SQLite ODB runtime library are
21217 <code>single_connection_factory</code>,
21218 <code>new_connection_factory</code>, and
21219 <code>connection_pool_factory</code>. You will need to include
21220 the <code>&lt;odb/sqlite/connection-factory.hxx></code>
21221 header file to make the <code>connection_factory</code> interface
21222 and these implementation classes available in your application.</p>
21223
21224 <p>The <code>single_connection_factory</code> class creates a
21225 single connection that is shared between all the threads in
21226 an application. If the connection is currently not in use,
21227 then it is returned to the caller. Otherwise, the caller is
21228 blocked until the connection becomes available. The
21229 <code>single_connection_factory</code> class has the following
21230 interface:</p>
21231
21232 <pre class="cxx">
21233 namespace odb
21234 {
21235 namespace sqlite
21236 {
21237 class single_connection_factory: public connection_factory
21238 {
21239 public:
21240 single_connection_factory ();
21241
21242 protected:
21243 class single_connection: public connection
21244 {
21245 public:
21246 single_connection (database_type&amp;);
21247 single_connection (database_type&amp;, MYSQL*);
21248 };
21249
21250 typedef details::shared_ptr&lt;single_connection> single_connection_ptr;
21251
21252 virtual single_connection_ptr
21253 create ();
21254 };
21255 };
21256 </pre>
21257
21258 <p>The <code>create()</code> virtual function is called when the
21259 factory needs to create the connection. By deriving from the
21260 <code>single_connection_factory</code> class and overriding this
21261 function we can implement custom connection establishment
21262 and configuration.</p>
21263
21264 <p>The <code>new_connection_factory</code> class creates a new
21265 connection whenever one is requested. When a connection is no
21266 longer needed, it is released and closed. The
21267 <code>new_connection_factory</code> class has the following
21268 interface:</p>
21269
21270 <pre class="cxx">
21271 namespace odb
21272 {
21273 namespace sqlite
21274 {
21275 class new_connection_factory: public connection_factory
21276 {
21277 public:
21278 new_connection_factory ();
21279 };
21280 };
21281 </pre>
21282
21283 <p>The <code>connection_pool_factory</code> class implements a
21284 connection pool. It has the following interface:</p>
21285
21286 <pre class="cxx">
21287 namespace odb
21288 {
21289 namespace sqlite
21290 {
21291 class connection_pool_factory: public connection_factory
21292 {
21293 public:
21294 connection_pool_factory (std::size_t max_connections = 0,
21295 std::size_t min_connections = 0);
21296
21297 protected:
21298 class pooled_connection: public connection
21299 {
21300 public:
21301 pooled_connection (database_type&amp;, int extra_flags = 0);
21302 pooled_connection (database_type&amp;, sqlite3*);
21303 };
21304
21305 typedef details::shared_ptr&lt;pooled_connection> pooled_connection_ptr;
21306
21307 virtual pooled_connection_ptr
21308 create ();
21309 };
21310 };
21311 </pre>
21312
21313 <p>The <code>max_connections</code> argument in the
21314 <code>connection_pool_factory</code> constructor specifies the maximum
21315 number of concurrent connections that this pool factory will
21316 maintain. Similarly, the <code>min_connections</code> argument
21317 specifies the minimum number of available connections that
21318 should be kept open.</p>
21319
21320 <p>Whenever a connection is requested, the pool factory first
21321 checks if there is an unused connection that can be returned.
21322 If there is none, the pool factory checks the
21323 <code>max_connections</code> value to see if a new connection
21324 can be created. If the total number of connections maintained
21325 by the pool is less than this value, then a new connection is
21326 created and returned. Otherwise, the caller is blocked until
21327 a connection becomes available.</p>
21328
21329 <p>When a connection is released, the pool factory first checks
21330 if there are blocked callers waiting for a connection. If so, then
21331 one of them is unblocked and is given the connection. Otherwise,
21332 the pool factory checks whether the total number of connections
21333 maintained by the pool is greater than the <code>min_connections</code>
21334 value. If that's the case, the connection is closed. Otherwise, the
21335 connection is added to the pool of available connections to be
21336 returned on the next request. In other words, if the number of
21337 connections maintained by the pool exceeds <code>min_connections</code>
21338 and there are no callers waiting for a new connection,
21339 then the pool will close the excess connections.</p>
21340
21341 <p>If the <code>max_connections</code> value is 0, then the pool will
21342 create a new connection whenever all of the existing connections
21343 are in use. If the <code>min_connections</code> value is 0, then
21344 the pool will never close a connection and instead maintain all
21345 the connections that were ever created.</p>
21346
21347 <p>The <code>create()</code> virtual function is called whenever the
21348 pool needs to create a new connection. By deriving from the
21349 <code>connection_pool_factory</code> class and overriding this
21350 function we can implement custom connection establishment
21351 and configuration.</p>
21352
21353 <p>By default, connections created by <code>new_connection_factory</code>
21354 and <code>connection_pool_factory</code> enable the SQLite shared cache
21355 mode and use the unlock notify functionality to aid concurrency. To
21356 disable the shared cache mode you can pass the
21357 <code>SQLITE_OPEN_PRIVATECACHE</code> flag when creating the database
21358 instance. For more information on the shared cache mode refer to the
21359 SQLite documentation.</p>
21360
21361 <p>If you pass <code>NULL</code> as the connection factory to one of the
21362 <code>database</code> constructors, then the <code>connection_pool_factory</code>
21363 instance will be created by default with the min and max connections
21364 values set to <code>0</code>. The following code fragment shows how we
21365 can pass our own connection factory instance:</p>
21366
21367 <pre class="cxx">
21368 #include &lt;odb/database.hxx>
21369
21370 #include &lt;odb/sqlite/database.hxx>
21371 #include &lt;odb/sqlite/connection-factory.hxx>
21372
21373 int
21374 main (int argc, char* argv[])
21375 {
21376 auto_ptr&lt;odb::sqlite::connection_factory> f (
21377 new odb::sqlite::connection_pool_factory (20));
21378
21379 auto_ptr&lt;odb::database> db (
21380 new sqlite::database (argc, argv, false, SQLITE_OPEN_READWRITE, f));
21381 }
21382 </pre>
21383
21384 <h2><a name="18.4">18.4 SQLite Exceptions</a></h2>
21385
21386 <p>The SQLite ODB runtime library defines the following SQLite-specific
21387 exceptions:</p>
21388
21389 <pre class="cxx">
21390 namespace odb
21391 {
21392 namespace sqlite
21393 {
21394 class forced_rollback: odb::recoverable
21395 {
21396 public:
21397 virtual const char*
21398 what () const throw ();
21399 };
21400
21401 class database_exception: odb::database_exception
21402 {
21403 public:
21404 int
21405 error () const
21406
21407 int
21408 extended_error () const;
21409
21410 const std::string&amp;
21411 message () const;
21412
21413 virtual const char*
21414 what () const throw ();
21415 };
21416
21417 class cli_exception: odb::exception
21418 {
21419 public:
21420 virtual const char*
21421 what () const throw ();
21422 };
21423 }
21424 }
21425 </pre>
21426
21427 <p>You will need to include the <code>&lt;odb/sqlite/exceptions.hxx></code>
21428 header file to make these exceptions available in your application.</p>
21429
21430 <p>The <code>odb::sqlite::forced_rollback</code> exception is thrown if
21431 SQLite is forcing the current transaction to roll back. For more
21432 information on this behavior refer to <a href="#18.5.6">Section 18.5.6,
21433 "Forced Rollback"</a>.</p>
21434
21435 <p>The <code>odb::sqlite::database_exception</code> is thrown if
21436 an SQLite database operation fails. The SQLite-specific error
21437 information is accessible via the <code>error()</code>,
21438 <code>extended_error()</code>, and <code>message()</code> functions.
21439 All this information is also combined and returned in a
21440 human-readable form by the <code>what()</code> function.</p>
21441
21442 <p>The <code>odb::sqlite::cli_exception</code> is thrown by the
21443 command line parsing constructor of the <code>odb::sqlite::database</code>
21444 class if the SQLite option values are missing or invalid. The
21445 <code>what()</code> function returns a human-readable description
21446 of an error.</p>
21447
21448
21449 <h2><a name="18.5">18.5 SQLite Limitations</a></h2>
21450
21451 <p>The following sections describe SQLite-specific limitations imposed by
21452 the current SQLite and ODB runtime versions.</p>
21453
21454 <h3><a name="18.5.1">18.5.1 Query Result Caching</a></h3>
21455
21456 <p>SQLite ODB runtime implementation does not perform query result caching
21457 (<a href="#4.4">Section 4.4, "Query Result"</a>) even when explicitly
21458 requested. The SQLite API supports interleaving execution of multiple
21459 prepared statements on a single connection. As a result, with SQLite, it
21460 is possible to have multiple uncached results and calls to other database
21461 functions do not invalidate them. The only limitation of the uncached
21462 SQLite results is the unavailability of the <code>result::size()</code>
21463 function. If you call this function on an SQLite query result, then
21464 the <code>odb::result_not_cached</code> exception
21465 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>) is always
21466 thrown. Future versions of the SQLite ODB runtime library may add support
21467 for result caching.</p>
21468
21469 <h3><a name="18.5.2">18.5.2 Automatic Assignment of Object Ids</a></h3>
21470
21471 <p>Due to SQLite API limitations, every automatically assigned object id
21472 (<a href="#14.4.2">Section 14.4.2, "<code>auto</code>"</a>) should have
21473 the <code>INTEGER</code> SQLite type. While SQLite will treat other
21474 integer type names (such as <code>INT</code>, <code>BIGINT</code>, etc.)
21475 as <code>INTEGER</code>, automatic id assignment will not work. By default,
21476 ODB maps all C++ integral types to <code>INTEGER</code>. This means that
21477 the only situation that requires consideration is the assignment of a
21478 custom database type using the <code>db&nbsp;type</code> pragma
21479 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>). For
21480 example:</p>
21481
21482 <pre class="cxx">
21483 #pragma db object
21484 class person
21485 {
21486 ...
21487
21488 //#pragma db id auto type("INT") // Will not work.
21489 //#pragma db id auto type("INTEGER") // Ok.
21490 #pragma db id auto // Ok, Mapped to INTEGER.
21491 unsigned int id_;
21492 };
21493 </pre>
21494
21495 <h3><a name="18.5.3">18.5.3 Foreign Key Constraints</a></h3>
21496
21497 <p>By default the SQLite ODB runtime enables foreign key constraints
21498 checking (<code>PRAGMA foreign_keys=ON</code>). You can disable foreign
21499 keys by passing <code>false</code> as the <code>foreign_keys</code>
21500 argument to one of the <code>odb::sqlite::database</code> constructors.
21501 Foreign keys will also be disabled if the SQLite library is built without
21502 support for foreign keys (<code>SQLITE_OMIT_FOREIGN_KEY</code> and
21503 <code>SQLITE_OMIT_TRIGGER</code> macros) or if you are using
21504 an SQLite version prior to 3.6.19, which does not support foreign
21505 key constraints checking.</p>
21506
21507 <p>If foreign key constraints checking is disabled or not available,
21508 then inconsistencies in object relationships will not be detected.
21509 Furthermore, using the <code>erase_query()</code> function
21510 (<a href="#3.11">Section 3.11, "Deleting Persistent Objects"</a>)
21511 to delete persistent objects that contain containers will not work
21512 correctly. Container data for such objects will not be deleted.</p>
21513
21514 <p>When foreign key constraints checking is enabled, then you may
21515 get the "foreign key constraint failed" error while re-creating the
21516 database schema. This error is due to bugs in the SQLite DDL foreign
21517 keys support. The recommended work-around for this problem is to
21518 temporarily disable foreign key constraints checking while
21519 re-creating the schema. The following code fragment shows how
21520 this can be done:</p>
21521
21522 <pre class="cxx">
21523 #include &lt;odb/connection.hxx>
21524 #include &lt;odb/transaction.hxx>
21525 #include &lt;odb/schema-catalog.hxx>
21526
21527 odb::database&amp; db = ...
21528
21529 {
21530 odb::connection_ptr c (db.connection ());
21531
21532 c->execute ("PRAGMA foreign_keys=OFF");
21533
21534 odb::transaction t (c->begin ());
21535 odb::schema_catalog::create_schema (db);
21536 t.commit ();
21537
21538 c->execute ("PRAGMA foreign_keys=ON");
21539 }
21540 </pre>
21541
21542 <p>Finally, ODB assumes the standard SQL behavior which requires
21543 that foreign key constraints checking is deferred until the
21544 transaction is committed. Default SQLite behavior is to check such
21545 constraints immediately. As a result, when used with ODB, a custom
21546 database schema that defines foreign key constraints may need to
21547 declare such constraints as <code>DEFERRABLE INITIALLY DEFERRED</code>,
21548 as shown in the following example. By default, schemas generated by
21549 the ODB compiler meet this requirement automatically.</p>
21550
21551 <pre class="sql">
21552 CREATE TABLE Employee (
21553 ...
21554 employer INTEGER REFERENCES Employer(id)
21555 DEFERRABLE INITIALLY DEFERRED);
21556 </pre>
21557
21558 <p>You can override the default behavior and instruct the ODB
21559 compiler to generate non-deferrable foreign keys by specifying
21560 the <code>--fkeys-deferrable-mode not_deferrable</code> ODB
21561 compiler option. Note, however, that in this case the order in
21562 which you persist, update, and erase objects within a transaction
21563 becomes important.</p>
21564
21565 <h3><a name="18.5.4">18.5.4 Constraint Violations</a></h3>
21566
21567 <p>Due to the granularity of the SQLite error codes, it is impossible
21568 to distinguish between the duplicate primary key and other constraint
21569 violations. As a result, when making an object persistent, the SQLite
21570 ODB runtime will translate all constraint violation errors to the
21571 <code>object_already_persistent</code> exception (<a href="#3.14">Section
21572 3.14, "ODB Exceptions"</a>).</p>
21573
21574 <h3><a name="18.5.5">18.5.5 Sharing of Queries</a></h3>
21575
21576 <p>As discussed in <a href="#4.3">Section 4.3, "Executing a Query"</a>, a
21577 query instance that does not have any by-reference parameters is
21578 immutable and can be shared between multiple threads without
21579 synchronization. Currently, the SQLite ODB runtime does not support this
21580 functionality. Future versions of the library will remove this
21581 limitation.</p>
21582
21583 <h3><a name="18.5.6">18.5.6 Forced Rollback</a></h3>
21584
21585 <p>In SQLite 3.7.11 or later, if one of the connections participating in
21586 the shared cache rolls back a transaction, then ongoing transactions
21587 on other connections in the shared cache may also be forced to roll back.
21588 An example of such behavior would be a read-only transaction that is
21589 forced to roll back while iterating over the query result because another
21590 transaction on another connection was rolled back.</p>
21591
21592 <p>If a transaction is being forced to roll back by SQLite, then ODB
21593 throws <code>odb::sqlite::forced_rollback</code>
21594 (<a href="#18.4">Section 18.4, "SQLite Exceptions"</a>) which is
21595 a recoverable exception (<a href="#3.7">3.7 Error Handling and
21596 Recovery</a>). As a result, the recommended way to handle this
21597 exception is to re-execute the affected transaction.</p>
21598
21599 <h3><a name="18.5.7">18.5.7 Database Schema Evolution</a></h3>
21600
21601 <p>From the list of schema migration changes supported by ODB
21602 (<a href="#13.2">Section 13.2, "Schema Migration"</a>), the
21603 following are not supported by SQLite:</p>
21604
21605 <ul class="list">
21606 <li>drop column</li>
21607 <li>alter column, set <code>NULL</code>/<code>NOT NULL</code></li>
21608 <li>add foreign key</li>
21609 <li>drop foreign key</li>
21610 </ul>
21611
21612 <p>The biggest problem is the lack of support for dropping columns.
21613 This means that it would be impossible to delete a data member
21614 in a persistent class. To work around this limitation ODB
21615 implements <em>logical delete</em> for columns that allow
21616 <code>NULL</code> values. In this case, instead of dropping
21617 the column (in the post-migration stage), the schema migration
21618 statements will automatically reset this column in all the
21619 existing rows to <code>NULL</code>. Any new rows that are
21620 inserted later will also automatically have this column set
21621 to <code>NULL</code> (unless the column specifies a default
21622 value).</p>
21623
21624 <p>Since it is also impossible to change the column's
21625 <code>NULL</code>/<code>NOT NULL</code> attribute after it
21626 has been added, to make schema evolution support usable in
21627 SQLite, all the columns should be added as <code>NULL</code>
21628 even if semantically they should not allow <code>NULL</code>
21629 values. We should also normally refrain from assigning
21630 default values to columns (<a href="#14.4.7">Section 14.4.7,
21631 <code>default</code></a>), unless the space overhead of
21632 a default value is not a concern. Explicitly making all
21633 the data members <code>NULL</code> would be burdensome
21634 and ODB provides the <code>--sqlite-override-null</code>
21635 command line option that forces all the columns, even those
21636 that were explicitly marked <code>NOT NULL</code>, to be
21637 <code>NULL</code> in SQLite.</p>
21638
21639 <p>SQLite only supports adding foreign keys as part of the
21640 column addition. As a result, we can only add a new
21641 data member of an object pointer type if it points
21642 to an object with a simple (single-column) object id.</p>
21643
21644 <p>SQLite also doesn't support dropping foreign keys.
21645 Leaving a foreign key around works well with logical
21646 delete unless we also want to delete the pointed-to
21647 object. In this case we will have to leave an
21648 empty table corresponding to the pointed-to object
21649 around. An alternative would be to make a copy of the
21650 pointing object without the object pointer, migrate the
21651 data, and then delete both the old pointing and the
21652 pointed-to objects. Since this will result in dropping
21653 the pointing table, the foreign key will be dropped
21654 as well. Yet another, more radical, solution to this
21655 problem is to disable foreign keys checking altogether
21656 (see the <code>foreign_keys</code> SQLite pragma).</p>
21657
21658 <p>To summarize, to make schema evolution support usable
21659 in SQLite we should pass the <code>--sqlite-override-null</code>
21660 option when compiling our persistent classes and also refrain
21661 from assigning default values to data members. Note also that
21662 this has to be done from the start so that every column is added
21663 as <code>NULL</code> and therefore can be logically deleted later.
21664 In particular, you cannot add the <code>--sqlite-override-null</code>
21665 option when you realize you need to delete a data member. At this
21666 point it is too late since the column has already been added
21667 as <code>NOT NULL</code> in existing databases. We should also
21668 avoid composite object ids if we are planning to use object
21669 relationships.</p>
21670
21671 <h2><a name="18.6">18.6 SQLite Index Definitions</a></h2>
21672
21673 <p>When the <code>index</code> pragma (<a href="#14.7">Section 14.7,
21674 "Index Definition Pragmas"</a>) is used to define an SQLite index,
21675 the <code>type</code> clause specifies the index type (for example,
21676 <code>UNIQUE</code>) while the <code>method</code> and
21677 <code>options</code> clauses are not used. The column options
21678 can be used to specify collations and the sort order. For example:</p>
21679
21680 <pre class="cxx">
21681 #pragma db object
21682 class object
21683 {
21684 ...
21685
21686 std::string name_;
21687
21688 #pragma db index member(name_, "COLLATE binary DESC")
21689 };
21690 </pre>
21691
21692 <p>Index names in SQLite are database-global. To avoid name clashes,
21693 ODB automatically prefixes each index name with the table name on
21694 which it is defined.</p>
21695
21696 <!-- CHAPTER -->
21697
21698
21699 <hr class="page-break"/>
21700 <h1><a name="19">19 PostgreSQL Database</a></h1>
21701
21702 <p>To generate support code for the PostgreSQL database you will need
21703 to pass the "<code>--database&nbsp;pgsql</code>"
21704 (or "<code>-d&nbsp;pgsql</code>") option to the ODB compiler.
21705 Your application will also need to link to the PostgreSQL ODB runtime
21706 library (<code>libodb-pgsql</code>). All PostgreSQL-specific ODB
21707 classes are defined in the <code>odb::pgsql</code> namespace.</p>
21708
21709 <p>ODB utilizes prepared statements extensively. Support for prepared
21710 statements was added in PostgreSQL version 7.4 with the introduction
21711 of the messaging protocol version 3.0. For this reason, ODB supports
21712 only PostgreSQL version 7.4 and later.</p>
21713
21714 <h2><a name="19.1">19.1 PostgreSQL Type Mapping</a></h2>
21715
21716 <p>The following table summarizes the default mapping between basic
21717 C++ value types and PostgreSQL database types. This mapping can be
21718 customized on the per-type and per-member basis using the ODB
21719 Pragma Language (<a href="#14">Chapter 14, "ODB Pragma
21720 Language"</a>).</p>
21721
21722 <!-- border="1" is necessary for html2ps -->
21723 <table id="mapping" border="1">
21724 <tr>
21725 <th>C++ Type</th>
21726 <th>PostgreSQL Type</th>
21727 <th>Default <code>NULL</code> Semantics</th>
21728 </tr>
21729
21730 <tr>
21731 <td><code>bool</code></td>
21732 <td><code>BOOLEAN</code></td>
21733 <td><code>NOT NULL</code></td>
21734 </tr>
21735
21736 <tr>
21737 <td><code>char</code></td>
21738 <td><code>CHAR(1)</code></td>
21739 <td><code>NOT NULL</code></td>
21740 </tr>
21741
21742 <tr>
21743 <td><code>signed char</code></td>
21744 <td><code>SMALLINT</code></td>
21745 <td><code>NOT NULL</code></td>
21746 </tr>
21747
21748 <tr>
21749 <td><code>unsigned char</code></td>
21750 <td><code>SMALLINT</code></td>
21751 <td><code>NOT NULL</code></td>
21752 </tr>
21753
21754 <tr>
21755 <td><code>short</code></td>
21756 <td><code>SMALLINT NULL</code></td>
21757 <td><code>NOT NULL</code></td>
21758 </tr>
21759
21760 <tr>
21761 <td><code>unsigned short</code></td>
21762 <td><code>SMALLINT</code></td>
21763 <td><code>NOT NULL</code></td>
21764 </tr>
21765
21766 <tr>
21767 <td><code>int</code></td>
21768 <td><code>INTEGER</code></td>
21769 <td><code>NOT NULL</code></td>
21770 </tr>
21771
21772 <tr>
21773 <td><code>unsigned int</code></td>
21774 <td><code>INTEGER</code></td>
21775 <td><code>NOT NULL</code></td>
21776 </tr>
21777
21778 <tr>
21779 <td><code>long</code></td>
21780 <td><code>BIGINT</code></td>
21781 <td><code>NOT NULL</code></td>
21782 </tr>
21783
21784 <tr>
21785 <td><code>unsigned long</code></td>
21786 <td><code>BIGINT</code></td>
21787 <td><code>NOT NULL</code></td>
21788 </tr>
21789
21790 <tr>
21791 <td><code>long long</code></td>
21792 <td><code>BIGINT</code></td>
21793 <td><code>NOT NULL</code></td>
21794 </tr>
21795
21796 <tr>
21797 <td><code>unsigned long long</code></td>
21798 <td><code>BIGINT</code></td>
21799 <td><code>NOT NULL</code></td>
21800 </tr>
21801
21802 <tr>
21803 <td><code>float</code></td>
21804 <td><code>REAL</code></td>
21805 <td><code>NOT NULL</code></td>
21806 </tr>
21807
21808 <tr>
21809 <td><code>double</code></td>
21810 <td><code>DOUBLE PRECISION</code></td>
21811 <td><code>NOT NULL</code></td>
21812 </tr>
21813
21814 <tr>
21815 <td><code>std::string</code></td>
21816 <td><code>TEXT</code></td>
21817 <td><code>NOT NULL</code></td>
21818 </tr>
21819
21820 <tr>
21821 <td><code>char[N]</code></td>
21822 <td><code>VARCHAR(N-1)</code></td>
21823 <td><code>NOT NULL</code></td>
21824 </tr>
21825 </table>
21826
21827 <p>It is possible to map the <code>char</code> C++ type to an integer
21828 database type (for example, <code>SMALLINT</code>) using the
21829 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
21830 "<code>type</code>"</a>).</p>
21831
21832 <p>Additionally, by default, C++ enums and C++11 enum classes are
21833 automatically mapped to the PostgreSQL types corresponding to their
21834 underlying integral types (see table above). The default
21835 <code>NULL</code> semantics is <code>NOT NULL</code>. For
21836 example:</p>
21837
21838 <pre class="cxx">
21839 enum color {red, green, blue};
21840 enum class taste: unsigned char
21841 {
21842 bitter = 1,
21843 sweet,
21844 sour = 4,
21845 salty
21846 };
21847
21848 #pragma db object
21849 class object
21850 {
21851 ...
21852
21853 color color_; // Automatically mapped to INTEGER.
21854 taste taste_; // Automatically mapped to SMALLINT.
21855 };
21856 </pre>
21857
21858 <p>Note also that because PostgreSQL does not support unsigned integers,
21859 the <code>unsigned&nbsp;short</code>, <code>unsigned&nbsp;int</code>, and
21860 <code>unsigned&nbsp;long</code>/<code>unsigned&nbsp;long&nbsp;long</code> C++ types
21861 are by default mapped to the <code>SMALLINT</code>, <code>INTEGER</code>,
21862 and <code>BIGINT</code> PostgreSQL types, respectively. The sign bit
21863 of the value stored by the database for these types will contain
21864 the most significant bit of the actual unsigned value being
21865 persisted.</p>
21866
21867 <p>It is also possible to add support for additional PostgreSQL types,
21868 such as <code>NUMERIC</code>, geometry types, <code>XML</code>,
21869 <code>JSON</code>, enumeration types, composite types, arrays,
21870 geospatial types, and the key-value store (<code>HSTORE</code>).
21871 For more information, refer to <a href="#14.8">Section 14.8,
21872 "Database Type Mapping Pragmas"</a>.</p>
21873
21874 <h3><a name="19.1.1">19.1.1 String Type Mapping</a></h3>
21875
21876 <p>The PostgreSQL ODB runtime library provides support for mapping the
21877 <code>std::string</code>, <code>char[N]</code>, and
21878 <code>std::array&lt;char, N></code> types to the PostgreSQL
21879 <code>CHAR</code>, <code>VARCHAR</code>, and <code>TEXT</code>
21880 types. However, these mappings are not enabled by default (in
21881 particular, by default, <code>std::array</code> will be treated
21882 as a container). To enable the alternative mappings for these
21883 types we need to specify the database type explicitly using the
21884 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
21885 "<code>type</code>"</a>), for example:</p>
21886
21887 <pre class="cxx">
21888 #pragma db object
21889 class object
21890 {
21891 ...
21892
21893 #pragma db type("CHAR(2)")
21894 char state_[2];
21895
21896 #pragma db type("VARCHAR(128)")
21897 std::string name_;
21898 };
21899 </pre>
21900
21901 <p>Alternatively, this can be done on the per-type basis, for example:</p>
21902
21903 <pre class="cxx">
21904 #pragma db value(std::string) type("VARCHAR(128)")
21905
21906 #pragma db object
21907 class object
21908 {
21909 ...
21910
21911 std::string name_; // Mapped to VARCHAR(128).
21912 };
21913 </pre>
21914
21915 <p>The <code>char[N]</code> and <code>std::array&lt;char, N></code> values
21916 may or may not be zero-terminated. When extracting such values from the
21917 database, ODB will append the zero terminator if there is enough
21918 space.</p>
21919
21920 <h3><a name="19.1.2">19.1.2 Binary Type and <code>UUID</code> Mapping</a></h3>
21921
21922 <p>The PostgreSQL ODB runtime library provides support for mapping the
21923 <code>std::vector&lt;char></code>,
21924 <code>std::vector&lt;unsigned&nbsp;char></code>,
21925 <code>char[N]</code>, <code>unsigned&nbsp;char[N]</code>,
21926 <code>std::array&lt;char, N></code>, and
21927 <code>std::array&lt;unsigned char, N></code> types to the PostgreSQL
21928 <code>BYTEA</code> type. There is also support for mapping the
21929 <code>char[16]</code> array to the PostgreSQL <code>UUID</code> type.
21930 However, these mappings are not enabled by default (in particular, by
21931 default, <code>std::vector</code> and <code>std::array</code> will be
21932 treated as containers). To enable the alternative mappings for these
21933 types we need to specify the database type explicitly using the
21934 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
21935 "<code>type</code>"</a>), for example:</p>
21936
21937 <pre class="cxx">
21938 #pragma db object
21939 class object
21940 {
21941 ...
21942
21943 #pragma db type("UUID")
21944 char uuid_[16];
21945
21946 #pragma db type("BYTEA")
21947 std::vector&lt;char> buf_;
21948
21949 #pragma db type("BYTEA")
21950 unsigned char data_[256];
21951 };
21952 </pre>
21953
21954 <p>Alternatively, this can be done on the per-type basis, for example:</p>
21955
21956 <pre class="cxx">
21957 typedef std::vector&lt;char> buffer;
21958 #pragma db value(buffer) type("BYTEA")
21959
21960 #pragma db object
21961 class object
21962 {
21963 ...
21964
21965 buffer buf_; // Mapped to BYTEA.
21966 };
21967 </pre>
21968
21969 <p>Note also that in native queries (<a href="#4">Chapter 4, "Querying
21970 the Database"</a>) <code>char[N]</code> and
21971 <code>std::array&lt;char, N></code> parameters are by default passed
21972 as a string rather than a binary. To pass such parameters as a binary,
21973 we need to specify the database type explicitly in the
21974 <code>_val()</code>/<code>_ref()</code> calls. Note also that we
21975 don't need to do this for the integrated queries, for example:</p>
21976
21977 <pre class="cxx">
21978 char u[16] = {...};
21979
21980 db.query&lt;object> ("uuid = " + query::_val&lt;odb::pgsql::id_uuid> (u));
21981 db.query&lt;object> ("buf = " + query::_val&lt;odb::pgsql::id_bytea> (u));
21982 db.query&lt;object> (query::uuid == query::_ref (u));
21983 </pre>
21984
21985 <h2><a name="19.2">19.2 PostgreSQL Database Class</a></h2>
21986
21987 <p>The PostgreSQL <code>database</code> class has the following
21988 interface:</p>
21989
21990 <pre class="cxx">
21991 namespace odb
21992 {
21993 namespace pgsql
21994 {
21995 class database: public odb::database
21996 {
21997 public:
21998 database (const std::string&amp; user,
21999 const std::string&amp; password,
22000 const std::string&amp; db,
22001 const std::string&amp; host = "",
22002 unsigned int port = 0,
22003 const std::string&amp; extra_conninfo = "",
22004 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22005
22006 database (const std::string&amp; user,
22007 const std::string&amp; password,
22008 const std::string&amp; db,
22009 const std::string&amp; host,
22010 const std::string&amp; socket_ext,
22011 const std::string&amp; extra_conninfo = "",
22012 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22013
22014 database (const std::string&amp; conninfo,
22015 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22016
22017 database (int&amp; argc,
22018 char* argv[],
22019 bool erase = false,
22020 const std::string&amp; extra_conninfo = "",
22021 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22022
22023 static void
22024 print_usage (std::ostream&amp;);
22025
22026 public:
22027 const std::string&amp;
22028 user () const;
22029
22030 const std::string&amp;
22031 password () const;
22032
22033 const std::string&amp;
22034 db () const;
22035
22036 const std::string&amp;
22037 host () const;
22038
22039 unsigned int
22040 port () const;
22041
22042 const std::string&amp;
22043 socket_ext () const;
22044
22045 const std::string&amp;
22046 extra_conninfo () const;
22047
22048 const std::string&amp;
22049 conninfo () const;
22050
22051 public:
22052 connection_ptr
22053 connection ();
22054 };
22055 }
22056 }
22057 </pre>
22058
22059 <p>You will need to include the <code>&lt;odb/pgsql/database.hxx></code>
22060 header file to make this class available in your application.</p>
22061
22062 <p>The overloaded <code>database</code> constructors allow us to specify
22063 the PostgreSQL database parameters that should be used when connecting
22064 to the database. The <code>port</code> argument in the first constructor
22065 is an integer value specifying the TCP/IP port number to connect to. A
22066 zero port number indicates that the default port should be used.
22067 The <code>socket_ext</code> argument in the second constructor is a
22068 string value specifying the UNIX-domain socket file name extension.</p>
22069
22070 <p>The third constructor allows us to specify all the database parameters
22071 as a single <code>conninfo</code> string. All other constructors
22072 accept additional database connection parameters as the
22073 <code>extra_conninfo</code> argument. For more information
22074 about the format of the <code>conninfo</code> string, refer to
22075 the <code>PQconnectdb()</code> function description in the PostgreSQL
22076 documentation. In the case of <code>extra_conninfo</code>, all the
22077 database parameters provided in this string will take precedence
22078 over those explicitly specified with other constructor arguments.</p>
22079
22080 <p>The last constructor extracts the database parameters
22081 from the command line. The following options are recognized:</p>
22082
22083 <pre class="terminal">
22084 --user &lt;login> | --username &lt;login>
22085 --password &lt;password>
22086 --database &lt;name> | --dbname &lt;name>
22087 --host &lt;host>
22088 --port &lt;integer>
22089 --options-file &lt;file>
22090 </pre>
22091
22092 <p>The <code>--options-file</code> option allows us to specify some
22093 or all of the database options in a file with each option appearing
22094 on a separate line followed by a space and an option value.</p>
22095
22096 <p>If the <code>erase</code> argument to this constructor is true,
22097 then the above options are removed from the <code>argv</code>
22098 array and the <code>argc</code> count is updated accordingly.
22099 This is primarily useful if your application accepts other
22100 options or arguments and you would like to get the PostgreSQL
22101 options out of the <code>argv</code> array.</p>
22102
22103 <p>This constructor throws the <code>odb::pgsql::cli_exception</code>
22104 exception if the PostgreSQL option values are missing or invalid.
22105 See section <a href="#19.4">Section 19.4, "PostgreSQL Exceptions"</a>
22106 for more information on this exception.</p>
22107
22108 <p>The static <code>print_usage()</code> function prints the list of options
22109 with short descriptions that are recognized by this constructor.</p>
22110
22111 <p>The last argument to all of the constructors is a pointer to the
22112 connection factory. In C++98/03, it is <code>std::auto_ptr</code> while
22113 in C++11 <code>std::unique_ptr</code> is used instead. If we pass a
22114 non-<code>NULL</code> value, the database instance assumes ownership
22115 of the factory instance. The connection factory interface as well as
22116 the available implementations are described in the next section.</p>
22117
22118 <p>The set of accessor functions following the constructors allows us
22119 to query the parameters of the <code>database</code> instance. Note that
22120 the <code>conninfo()</code> accessor returns a complete
22121 <code>conninfo</code> string which includes parameters that were
22122 explicitly specified with the various constructor arguments, as well as
22123 the extra parameters passed in the <code>extra_conninfo</code> argument.
22124 The <code>extra_conninfo()</code> accessor will return the
22125 <code>conninfo</code> string as passed in the <code>extra_conninfo</code>
22126 argument.</p>
22127
22128 <p>The <code>connection()</code> function returns a pointer to the
22129 PostgreSQL database connection encapsulated by the
22130 <code>odb::pgsql::connection</code> class. For more information
22131 on <code>pgsql::connection</code>, refer to <a href="#19.3">Section
22132 19.3, "PostgreSQL Connection and Connection Factory"</a>.</p>
22133
22134 <h2><a name="19.3">19.3 PostgreSQL Connection and Connection Factory</a></h2>
22135
22136 <p>The <code>pgsql::connection</code> class has the following interface:</p>
22137
22138 <pre class="cxx">
22139 namespace odb
22140 {
22141 namespace pgsql
22142 {
22143 class connection: public odb::connection
22144 {
22145 public:
22146 connection (database&amp;);
22147 connection (database&amp;, PGconn*);
22148
22149 PGconn*
22150 handle ();
22151 };
22152
22153 typedef details::shared_ptr&lt;connection> connection_ptr;
22154 }
22155 }
22156 </pre>
22157
22158 <p>For more information on the <code>odb::connection</code> interface,
22159 refer to <a href="#3.6">Section 3.6, "Connections"</a>. The first
22160 overloaded <code>pgsql::connection</code> constructor establishes a
22161 new PostgreSQL connection. The second constructor allows us to create
22162 a <code>connection</code> instance by providing an already connected
22163 native PostgreSQL handle. Note that the <code>connection</code>
22164 instance assumes ownership of this handle. The <code>handle()</code>
22165 accessor returns the PostgreSQL handle corresponding to the connection.</p>
22166
22167 <p>The <code>pgsql::connection_factory</code> abstract class has the
22168 following interface:</p>
22169
22170 <pre class="cxx">
22171 namespace odb
22172 {
22173 namespace pgsql
22174 {
22175 class connection_factory
22176 {
22177 public:
22178 virtual void
22179 database (database&amp;) = 0;
22180
22181 virtual connection_ptr
22182 connect () = 0;
22183 };
22184 }
22185 }
22186 </pre>
22187
22188 <p>The <code>database()</code> function is called when a connection
22189 factory is associated with a database instance. This happens in
22190 the <code>odb::pgsql::database</code> class constructors. The
22191 <code>connect()</code> function is called whenever a database
22192 connection is requested.</p>
22193
22194 <p>The two implementations of the <code>connection_factory</code>
22195 interface provided by the PostgreSQL ODB runtime are
22196 <code>new_connection_factory</code> and
22197 <code>connection_pool_factory</code>. You will need to include
22198 the <code>&lt;odb/pgsql/connection-factory.hxx></code>
22199 header file to make the <code>connection_factory</code> interface
22200 and these implementation classes available in your application.</p>
22201
22202 <p>The <code>new_connection_factory</code> class creates a new
22203 connection whenever one is requested. When a connection is no
22204 longer needed, it is released and closed. The
22205 <code>new_connection_factory</code> class has the following
22206 interface:</p>
22207
22208 <pre class="cxx">
22209 namespace odb
22210 {
22211 namespace pgsql
22212 {
22213 class new_connection_factory: public connection_factory
22214 {
22215 public:
22216 new_connection_factory ();
22217 };
22218 };
22219 </pre>
22220
22221 <p>The <code>connection_pool_factory</code> class implements a
22222 connection pool. It has the following interface:</p>
22223
22224 <pre class="cxx">
22225 namespace odb
22226 {
22227 namespace pgsql
22228 {
22229 class connection_pool_factory: public connection_factory
22230 {
22231 public:
22232 connection_pool_factory (std::size_t max_connections = 0,
22233 std::size_t min_connections = 0);
22234
22235 protected:
22236 class pooled_connection: public connection
22237 {
22238 public:
22239 pooled_connection (database_type&amp;);
22240 pooled_connection (database_type&amp;, PGconn*);
22241 };
22242
22243 typedef details::shared_ptr&lt;pooled_connection> pooled_connection_ptr;
22244
22245 virtual pooled_connection_ptr
22246 create ();
22247 };
22248 };
22249 </pre>
22250
22251 <p>The <code>max_connections</code> argument in the
22252 <code>connection_pool_factory</code> constructor specifies the maximum
22253 number of concurrent connections that this pool factory will
22254 maintain. Similarly, the <code>min_connections</code> argument
22255 specifies the minimum number of available connections that
22256 should be kept open.</p>
22257
22258 <p>Whenever a connection is requested, the pool factory first
22259 checks if there is an unused connection that can be returned.
22260 If there is none, the pool factory checks the
22261 <code>max_connections</code> value to see if a new connection
22262 can be created. If the total number of connections maintained
22263 by the pool is less than this value, then a new connection is
22264 created and returned. Otherwise, the caller is blocked until
22265 a connection becomes available.</p>
22266
22267 <p>When a connection is released, the pool factory first checks
22268 if there are blocked callers waiting for a connection. If so, then
22269 one of them is unblocked and is given the connection. Otherwise,
22270 the pool factory checks whether the total number of connections
22271 maintained by the pool is greater than the <code>min_connections</code>
22272 value. If that's the case, the connection is closed. Otherwise, the
22273 connection is added to the pool of available connections to be
22274 returned on the next request. In other words, if the number of
22275 connections maintained by the pool exceeds <code>min_connections</code>
22276 and there are no callers waiting for a new connection,
22277 the pool will close the excess connections.</p>
22278
22279 <p>If the <code>max_connections</code> value is 0, then the pool will
22280 create a new connection whenever all of the existing connections
22281 are in use. If the <code>min_connections</code> value is 0, then
22282 the pool will never close a connection and instead maintain all
22283 the connections that were ever created.</p>
22284
22285 <p>The <code>create()</code> virtual function is called whenever the
22286 pool needs to create a new connection. By deriving from the
22287 <code>connection_pool_factory</code> class and overriding this
22288 function we can implement custom connection establishment
22289 and configuration.</p>
22290
22291 <p>If you pass <code>NULL</code> as the connection factory to one of the
22292 <code>database</code> constructors, then the
22293 <code>connection_pool_factory</code> instance will be created by default
22294 with the min and max connections values set to <code>0</code>. The
22295 following code fragment shows how we can pass our own connection factory
22296 instance:</p>
22297
22298 <pre class="cxx">
22299 #include &lt;odb/database.hxx>
22300
22301 #include &lt;odb/pgsql/database.hxx>
22302 #include &lt;odb/pgsql/connection-factory.hxx>
22303
22304 int
22305 main (int argc, char* argv[])
22306 {
22307 auto_ptr&lt;odb::pgsql::connection_factory> f (
22308 new odb::pgsql::connection_pool_factory (20));
22309
22310 auto_ptr&lt;odb::database> db (
22311 new pgsql::database (argc, argv, false, "", f));
22312 }
22313 </pre>
22314
22315 <h2><a name="19.4">19.4 PostgreSQL Exceptions</a></h2>
22316
22317 <p>The PostgreSQL ODB runtime library defines the following
22318 PostgreSQL-specific exceptions:</p>
22319
22320 <pre class="cxx">
22321 namespace odb
22322 {
22323 namespace pgsql
22324 {
22325 class database_exception: odb::database_exception
22326 {
22327 public:
22328 const std::string&amp;
22329 message () const;
22330
22331 const std::string&amp;
22332 sqlstate () const;
22333
22334 virtual const char*
22335 what () const throw ();
22336 };
22337
22338 class cli_exception: odb::exception
22339 {
22340 public:
22341 virtual const char*
22342 what () const throw ();
22343 };
22344 }
22345 }
22346 </pre>
22347
22348 <p>You will need to include the <code>&lt;odb/pgsql/exceptions.hxx></code>
22349 header file to make these exceptions available in your application.</p>
22350
22351 <p>The <code>odb::pgsql::database_exception</code> is thrown if
22352 a PostgreSQL database operation fails. The PostgreSQL-specific error
22353 information is accessible via the <code>message()</code> and
22354 <code>sqlstate()</code> functions. All this information is also
22355 combined and returned in a human-readable form by the <code>what()</code>
22356 function.</p>
22357
22358 <p>The <code>odb::pgsql::cli_exception</code> is thrown by the
22359 command line parsing constructor of the <code>odb::pgsql::database</code>
22360 class if the PostgreSQL option values are missing or invalid. The
22361 <code>what()</code> function returns a human-readable description
22362 of an error.</p>
22363
22364 <h2><a name="19.5">19.5 PostgreSQL Limitations</a></h2>
22365
22366 <p>The following sections describe PostgreSQL-specific limitations imposed
22367 by the current PostgreSQL and ODB runtime versions.</p>
22368
22369 <h3><a name="19.5.1">19.5.1 Query Result Caching</a></h3>
22370
22371 <p>The PostgreSQL ODB runtime implementation will always return a
22372 cached query result (<a href="#4.4">Section 4.4, "Query Result"</a>)
22373 even when explicitly requested not to. This is a limitation of the
22374 PostgreSQL client library (<code>libpq</code>) which does not
22375 support uncached (streaming) query results.</p>
22376
22377 <h3><a name="19.5.2">19.5.2 Foreign Key Constraints</a></h3>
22378
22379 <p>ODB assumes the standard SQL behavior which requires that
22380 foreign key constraints checking is deferred until the
22381 transaction is committed. Default PostgreSQL behavior is
22382 to check such constraints immediately. As a result, when
22383 used with ODB, a custom database schema that defines foreign
22384 key constraints may need to declare such constraints as
22385 <code>INITIALLY DEFERRED</code>, as shown in the following example.
22386 By default, schemas generated by the ODB compiler meet this requirement
22387 automatically.</p>
22388
22389 <pre class="sql">
22390 CREATE TABLE Employee (
22391 ...
22392 employer BIGINT REFERENCES Employer(id) INITIALLY DEFERRED);
22393 </pre>
22394
22395 <p>You can override the default behavior and instruct the ODB
22396 compiler to generate non-deferrable foreign keys by specifying
22397 the <code>--fkeys-deferrable-mode not_deferrable</code> ODB
22398 compiler option. Note, however, that in this case the order in
22399 which you persist, update, and erase objects within a transaction
22400 becomes important.</p>
22401
22402 <h3><a name="19.5.3">19.5.3 Unique Constraint Violations</a></h3>
22403
22404 <p>Due to the granularity of the PostgreSQL error codes, it is impossible
22405 to distinguish between the duplicate primary key and other unique
22406 constraint violations. As a result, when making an object persistent,
22407 the PostgreSQL ODB runtime will translate all unique constraint violation
22408 errors to the <code>object_already_persistent</code> exception
22409 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>).</p>
22410
22411 <h3><a name="19.5.4">19.5.4 Date-Time Format</a></h3>
22412
22413 <p>ODB expects the PostgreSQL server to use integers as a binary
22414 format for the date-time types, which is the default for most
22415 PostgreSQL configurations. When creating a connection, ODB
22416 examines the <code>integer_datetimes</code> PostgreSQL server
22417 parameter and if it is <code>false</code>,
22418 <code>odb::pgsql::database_exception</code> is thrown. You may
22419 check the value of this parameter for your server by executing
22420 the following SQL query:</p>
22421
22422 <pre class="sql">
22423 SHOW integer_datetimes
22424 </pre>
22425
22426 <h3><a name="19.5.5">19.5.5 Timezones</a></h3>
22427
22428 <p>ODB does not currently natively support the PostgreSQL date-time types
22429 with timezone information. However, these types can be accessed by
22430 mapping them to one of the natively supported types, as discussed
22431 in <a href="#14.8">Section 14.8, "Database Type Mapping Pragmas"</a>.</p>
22432
22433 <h3><a name="19.5.6">19.5.6 <code>NUMERIC</code> Type Support</a></h3>
22434
22435 <p>Support for the PostgreSQL <code>NUMERIC</code> type is limited
22436 to providing a binary buffer containing the binary representation
22437 of the value. For more information on the binary format used to
22438 store <code>NUMERIC</code> values refer to the PostgreSQL
22439 documentation. An alternative approach to accessing <code>NUMERIC</code>
22440 values is to map this type to one of the natively supported
22441 ones, as discussed in <a href="#14.8">Section 14.8, "Database
22442 Type Mapping Pragmas"</a>.</p>
22443
22444
22445 <h2><a name="19.6">19.6 PostgreSQL Index Definitions</a></h2>
22446
22447 <p>When the <code>index</code> pragma (<a href="#14.7">Section 14.7,
22448 "Index Definition Pragmas"</a>) is used to define a PostgreSQL index,
22449 the <code>type</code> clause specifies the index type (for example,
22450 <code>UNIQUE</code>), the <code>method</code> clause specifies the
22451 index method (for example, <code>BTREE</code>, <code>HASH</code>,
22452 <code>GIN</code>, etc.), and the <code>options</code> clause
22453 specifies additional index options, such as storage parameters,
22454 table spaces, and the <code>WHERE</code> predicate. To support
22455 the definition of concurrent indexes, the <code>type</code>
22456 clause can end with the word <code>CONCURRENTLY</code> (upper and
22457 lower cases are recognized). The column options can be used to
22458 specify collations, operator classes, and the sort order. For example:</p>
22459
22460 <pre class="cxx">
22461 #pragma db object
22462 class object
22463 {
22464 ...
22465
22466 std::string name_;
22467
22468 #pragma db index \
22469 type("UNIQUE CONCURRENTLY") \
22470 method("HASH") \
22471 member(name_, "DESC") \
22472 options("WITH(FILLFACTOR = 80)")
22473 };
22474 </pre>
22475
22476 <p>Index names in PostgreSQL are schema-global. To avoid name clashes,
22477 ODB automatically prefixes each index name with the table name on
22478 which it is defined.</p>
22479
22480 <!-- CHAPTER -->
22481
22482
22483 <hr class="page-break"/>
22484 <h1><a name="20">20 Oracle Database</a></h1>
22485
22486 <p>To generate support code for the Oracle database you will need
22487 to pass the "<code>--database&nbsp;oracle</code>"
22488 (or "<code>-d&nbsp;oracle</code>") option to the ODB compiler.
22489 Your application will also need to link to the Oracle ODB runtime
22490 library (<code>libodb-oracle</code>). All Oracle-specific ODB
22491 classes are defined in the <code>odb::oracle</code> namespace.</p>
22492
22493 <h2><a name="20.1">20.1 Oracle Type Mapping</a></h2>
22494
22495 <p>The following table summarizes the default mapping between basic
22496 C++ value types and Oracle database types. This mapping can be
22497 customized on the per-type and per-member basis using the ODB
22498 Pragma Language (<a href="#14">Chapter 14, "ODB Pragma
22499 Language"</a>).</p>
22500
22501 <!-- border="1" is necessary for html2ps -->
22502 <table id="mapping" border="1">
22503 <tr>
22504 <th>C++ Type</th>
22505 <th>Oracle Type</th>
22506 <th>Default <code>NULL</code> Semantics</th>
22507 </tr>
22508
22509 <tr>
22510 <td><code>bool</code></td>
22511 <td><code>NUMBER(1)</code></td>
22512 <td><code>NOT NULL</code></td>
22513 </tr>
22514
22515 <tr>
22516 <td><code>char</code></td>
22517 <td><code>CHAR(1)</code></td>
22518 <td><code>NOT NULL</code></td>
22519 </tr>
22520
22521 <tr>
22522 <td><code>signed char</code></td>
22523 <td><code>NUMBER(3)</code></td>
22524 <td><code>NOT NULL</code></td>
22525 </tr>
22526
22527 <tr>
22528 <td><code>unsigned char</code></td>
22529 <td><code>NUMBER(3)</code></td>
22530 <td><code>NOT NULL</code></td>
22531 </tr>
22532
22533 <tr>
22534 <td><code>short</code></td>
22535 <td><code>NUMBER(5)</code></td>
22536 <td><code>NOT NULL</code></td>
22537 </tr>
22538
22539 <tr>
22540 <td><code>unsigned short</code></td>
22541 <td><code>NUMBER(5)</code></td>
22542 <td><code>NOT NULL</code></td>
22543 </tr>
22544
22545 <tr>
22546 <td><code>int</code></td>
22547 <td><code>NUMBER(10)</code></td>
22548 <td><code>NOT NULL</code></td>
22549 </tr>
22550
22551 <tr>
22552 <td><code>unsigned int</code></td>
22553 <td><code>NUMBER(10)</code></td>
22554 <td><code>NOT NULL</code></td>
22555 </tr>
22556
22557 <tr>
22558 <td><code>long</code></td>
22559 <td><code>NUMBER(19)</code></td>
22560 <td><code>NOT NULL</code></td>
22561 </tr>
22562
22563 <tr>
22564 <td><code>unsigned long</code></td>
22565 <td><code>NUMBER(20)</code></td>
22566 <td><code>NOT NULL</code></td>
22567 </tr>
22568
22569 <tr>
22570 <td><code>long long</code></td>
22571 <td><code>NUMBER(19)</code></td>
22572 <td><code>NOT NULL</code></td>
22573 </tr>
22574
22575 <tr>
22576 <td><code>unsigned long long</code></td>
22577 <td><code>NUMBER(20)</code></td>
22578 <td><code>NOT NULL</code></td>
22579 </tr>
22580
22581 <tr>
22582 <td><code>float</code></td>
22583 <td><code>BINARY_FLOAT</code></td>
22584 <td><code>NOT NULL</code></td>
22585 </tr>
22586
22587 <tr>
22588 <td><code>double</code></td>
22589 <td><code>BINARY_DOUBLE</code></td>
22590 <td><code>NOT NULL</code></td>
22591 </tr>
22592
22593 <tr>
22594 <td><code>std::string</code></td>
22595 <td><code>VARCHAR2(512)</code></td>
22596 <td><code>NULL</code></td>
22597 </tr>
22598
22599 <tr>
22600 <td><code>char[N]</code></td>
22601 <td><code>VARCHAR2(N-1)</code></td>
22602 <td><code>NULL</code></td>
22603 </tr>
22604 </table>
22605
22606 <p>It is possible to map the <code>char</code> C++ type to an integer
22607 database type (for example, <code>NUMBER(3)</code>) using the
22608 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
22609 "<code>type</code>"</a>).</p>
22610
22611 <p>In Oracle empty <code>VARCHAR2</code> and <code>NVARCHAR2</code>
22612 strings are represented as a <code>NULL</code> value. As a result,
22613 columns of the <code>std::string</code> and <code>char[N]</code>
22614 types are by default declared as <code>NULL</code> except for
22615 primary key columns. However, you can override this by explicitly
22616 declaring such columns as <code>NOT NULL</code> with the
22617 <code>db&nbsp;not_null</code> pragma (<a href="#14.4.6">Section
22618 14.4.6, "<code>null/not_null</code>"</a>). This also means that for
22619 object ids that are mapped to these Oracle types, an empty string is
22620 an invalid value.</p>
22621
22622 <p>Additionally, by default, C++ enums and C++11 enum classes are
22623 automatically mapped to the Oracle types corresponding to their
22624 underlying integral types (see table above). The default
22625 <code>NULL</code> semantics is <code>NOT NULL</code>. For
22626 example:</p>
22627
22628 <pre class="cxx">
22629 enum color {red, green, blue};
22630 enum class taste: unsigned char
22631 {
22632 bitter = 1,
22633 sweet,
22634 sour = 4,
22635 salty
22636 };
22637
22638 #pragma db object
22639 class object
22640 {
22641 ...
22642
22643 color color_; // Automatically mapped to NUMBER(10).
22644 taste taste_; // Automatically mapped to NUMBER(3).
22645 };
22646 </pre>
22647
22648 <p>It is also possible to add support for additional Oracle types,
22649 such as <code>XML</code>, geospatial types, user-defined types,
22650 and collections (arrays, table types). For more information, refer to
22651 <a href="#14.8">Section 14.8, "Database Type Mapping
22652 Pragmas"</a>.</p>
22653
22654 <h3><a name="20.1.1">20.1.1 String Type Mapping</a></h3>
22655
22656 <p>The Oracle ODB runtime library provides support for mapping the
22657 <code>std::string</code>, <code>char[N]</code>, and
22658 <code>std::array&lt;char, N></code> types to the Oracle <code>CHAR</code>,
22659 <code>VARCHAR2</code>, <code>CLOB</code>, <code>NCHAR</code>,
22660 <code>NVARCHAR2</code>, and <code>NCLOB</code> types. However,
22661 these mappings are not enabled by default (in particular, by
22662 default, <code>std::array</code> will be treated as a container).
22663 To enable the alternative mappings for these types we need to
22664 specify the database type explicitly using the <code>db&nbsp;type</code>
22665 pragma (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>),
22666 for example:</p>
22667
22668 <pre class="cxx">
22669 #pragma db object
22670 class object
22671 {
22672 ...
22673
22674 #pragma db type ("CHAR(2)")
22675 char state_[2];
22676
22677 #pragma db type ("VARCHAR(128)") null
22678 std::string name_;
22679
22680 #pragma db type ("CLOB")
22681 std::string text_;
22682 };
22683 </pre>
22684
22685 <p>Alternatively, this can be done on the per-type basis, for example:</p>
22686
22687 <pre class="cxx">
22688 #pragma db value(std::string) type("VARCHAR(128)") null
22689
22690 #pragma db object
22691 class object
22692 {
22693 ...
22694
22695 std::string name_; // Mapped to VARCHAR(128).
22696
22697 #pragma db type ("CLOB")
22698 std::string text_; // Mapped to CLOB.
22699 };
22700 </pre>
22701
22702 <p>The <code>char[N]</code> and <code>std::array&lt;char, N></code> values
22703 may or may not be zero-terminated. When extracting such values from the
22704 database, ODB will append the zero terminator if there is enough
22705 space.</p>
22706
22707 <h3><a name="20.1.2">20.1.2 Binary Type Mapping</a></h3>
22708
22709 <p>The Oracle ODB runtime library provides support for mapping the
22710 <code>std::vector&lt;char></code>,
22711 <code>std::vector&lt;unsigned&nbsp;char></code>,
22712 <code>char[N]</code>, <code>unsigned&nbsp;char[N]</code>,
22713 <code>std::array&lt;char, N></code>, and
22714 <code>std::array&lt;unsigned char, N></code>
22715 types to the Oracle <code>BLOB</code> and <code>RAW</code> types.
22716 However, these mappings are not enabled by default (in particular, by
22717 default, <code>std::vector</code> and <code>std::array</code> will be
22718 treated as containers). To enable the alternative mappings for these
22719 types we need to specify the database type explicitly using the
22720 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
22721 "<code>type</code>"</a>), for example:</p>
22722
22723 <pre class="cxx">
22724 #pragma db object
22725 class object
22726 {
22727 ...
22728
22729 #pragma db type("BLOB")
22730 std::vector&lt;char> buf_;
22731
22732 #pragma db type("RAW(16)")
22733 unsigned char uuid_[16];
22734 };
22735 </pre>
22736
22737 <p>Alternatively, this can be done on the per-type basis, for example:</p>
22738
22739 <pre class="cxx">
22740 typedef std::vector&lt;char> buffer;
22741 #pragma db value(buffer) type("BLOB")
22742
22743 #pragma db object
22744 class object
22745 {
22746 ...
22747
22748 buffer buf_; // Mapped to BLOB.
22749 };
22750 </pre>
22751
22752 <p>Note also that in native queries (<a href="#4">Chapter 4, "Querying
22753 the Database"</a>) <code>char[N]</code> and
22754 <code>std::array&lt;char, N></code> parameters are by default passed
22755 as a string rather than a binary. To pass such parameters as a binary,
22756 we need to specify the database type explicitly in the
22757 <code>_val()</code>/<code>_ref()</code> calls. Note also that we
22758 don't need to do this for the integrated queries, for example:</p>
22759
22760 <pre class="cxx">
22761 char u[16] = {...};
22762
22763 db.query&lt;object> ("uuid = " + query::_val&lt;odb::oracle::id_raw> (u));
22764 db.query&lt;object> (query::uuid == query::_ref (u));
22765 </pre>
22766
22767 <h2><a name="20.2">20.2 Oracle Database Class</a></h2>
22768
22769 <p>The Oracle <code>database</code> class encapsulates the OCI environment
22770 handle as well as the database connection string and user credentials
22771 that are used to establish connections to the database. It has the
22772 following interface:</p>
22773
22774 <pre class="cxx">
22775 namespace odb
22776 {
22777 namespace oracle
22778 {
22779 class database: public odb::database
22780 {
22781 public:
22782 database (const std::string&amp; user,
22783 const std::string&amp; password,
22784 const std::string&amp; db,
22785 ub2 charset = 0,
22786 ub2 ncharset = 0,
22787 OCIEnv* environment = 0,
22788 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22789
22790 database (const std::string&amp; user,
22791 const std::string&amp; password,
22792 const std::string&amp; service,
22793 const std::string&amp; host,
22794 unsigned int port = 0,
22795 ub2 charset = 0,
22796 ub2 ncharset = 0,
22797 OCIEnv* environment = 0,
22798 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22799
22800 database (int&amp; argc,
22801 char* argv[],
22802 bool erase = false,
22803 ub2 charset = 0,
22804 ub2 ncharset = 0,
22805 OCIEnv* environment = 0,
22806 std::[auto|unique]_ptr&lt;connection_factory> = 0);
22807
22808 static void
22809 print_usage (std::ostream&amp;);
22810
22811 public:
22812 const std::string&amp;
22813 user () const;
22814
22815 const std::string&amp;
22816 password () const;
22817
22818 const std::string&amp;
22819 db () const;
22820
22821 const std::string&amp;
22822 service () const;
22823
22824 const std::string&amp;
22825 host () const;
22826
22827 unsigned int
22828 port () const;
22829
22830 ub2
22831 charset () const;
22832
22833 ub2
22834 ncharset () const;
22835
22836 OCIEnv*
22837 environment ();
22838
22839 public:
22840 connection_ptr
22841 connection ();
22842 };
22843 }
22844 }
22845 </pre>
22846
22847 <p>You will need to include the <code>&lt;odb/oracle/database.hxx></code>
22848 header file to make this class available in your application.</p>
22849
22850 <p>The overloaded <code>database</code> constructors allow us to specify the
22851 Oracle database parameters that should be used when connecting to the
22852 database. The <code>db</code> argument in the first constructor is a
22853 connection identifier that specifies the database to connect to. For more
22854 information on the format of the connection identifier, refer to the
22855 Oracle documentation.</p>
22856
22857 <p>The second constructor allows us to specify the individual components
22858 of a connection identifier as the <code>service</code>, <code>host</code>,
22859 and <code>port</code> arguments. If the <code>host</code> argument is
22860 empty, then localhost is used by default. Similarly, if the
22861 <code>port</code> argument is zero, then the default port is used.</p>
22862
22863 <p>The last constructor extracts the database parameters
22864 from the command line. The following options are recognized:</p>
22865
22866 <pre class="terminal">
22867 --user &lt;login>
22868 --password &lt;password>
22869 --database &lt;connect-id>
22870 --service &lt;name>
22871 --host &lt;host>
22872 --port &lt;integer>
22873 --options-file &lt;file>
22874 </pre>
22875
22876 <p>The <code>--options-file</code> option allows us to specify some
22877 or all of the database options in a file with each option appearing
22878 on a separate line followed by a space and an option value. Note that it
22879 is invalid to specify the <code>--database</code> option
22880 together with <code>--service</code>, <code>--host</code>, or
22881 <code>--port</code> options.</p>
22882
22883 <p>If the <code>erase</code> argument to this constructor is true,
22884 then the above options are removed from the <code>argv</code>
22885 array and the <code>argc</code> count is updated accordingly.
22886 This is primarily useful if your application accepts other
22887 options or arguments and you would like to get the Oracle
22888 options out of the <code>argv</code> array.</p>
22889
22890 <p>This constructor throws the <code>odb::oracle::cli_exception</code>
22891 exception if the Oracle option values are missing or invalid. See section
22892 <a href="#20.4">Section 20.4, "Oracle Exceptions"</a> for more
22893 information on this exception.</p>
22894
22895 <p>The static <code>print_usage()</code> function prints the list of options
22896 with short descriptions that are recognized by this constructor.</p>
22897
22898 <p>Additionally, all the constructors have the <code>charset</code>,
22899 <code>ncharset</code>, and <code>environment</code> arguments.
22900 The <code>charset</code> argument specifies the client-side database
22901 character encoding. Character data corresponding to the <code>CHAR</code>,
22902 <code>VARCHAR2</code>, and <code>CLOB</code> types will be delivered
22903 to and received from the application in this encoding. Similarly,
22904 the <code>ncharset</code> argument specifies the client-side national
22905 character encoding. Character data corresponding to the <code>NCHAR</code>,
22906 <code>NVARCHAR2</code>, and <code>NCLOB</code> types will be delivered
22907 to and received from the application in this encoding. For the complete
22908 list of available character encoding values, refer to the Oracle
22909 documentation. Commonly used encoding values are <code>873</code>
22910 (UTF-8), <code>31</code> (ISO-8859-1), and <code>1000</code> (UTF-16).
22911 If the database character encoding is not specified, then the
22912 <code>NLS_LANG</code> environment/registry variable is used. Similarly,
22913 if the national character encoding is not specified, then the
22914 <code>NLS_NCHAR</code> environment/registry variable is used. For more
22915 information on character encodings, refer to the
22916 <code>OCIEnvNlsCreate()</code> function in the Oracle Call Interface
22917 (OCI) documentation.</p>
22918
22919 <p>The <code>environment</code> argument allows us to provide a custom
22920 OCI environment handle. If this argument is not <code>NULL</code>,
22921 then the passed handle is used in all the OCI function calls made
22922 by this <code>database</code> class instance. Note also that the
22923 <code>database</code> instance does not assume ownership of the
22924 passed environment handle and this handle should be valid for
22925 the lifetime of the <code>database</code> instance. If a custom
22926 environment handle is used, then the <code>charset</code> and
22927 <code>ncharset</code> arguments have no effect.</p>
22928
22929 <p>The last argument to all of the constructors is a pointer to the
22930 connection factory. In C++98/03, it is <code>std::auto_ptr</code> while
22931 in C++11 <code>std::unique_ptr</code> is used instead. If we pass a
22932 non-<code>NULL</code> value, the database instance assumes ownership
22933 of the factory instance. The connection factory interface as well as
22934 the available implementations are described in the next section.</p>
22935
22936 <p>The set of accessor functions following the constructors allows us
22937 to query the parameters of the <code>database</code> instance.</p>
22938
22939 <p>The <code>connection()</code> function returns a pointer to the
22940 Oracle database connection encapsulated by the
22941 <code>odb::oracle::connection</code> class. For more information
22942 on <code>oracle::connection</code>, refer to <a href="#20.3">Section
22943 20.3, "Oracle Connection and Connection Factory"</a>.</p>
22944
22945 <h2><a name="20.3">20.3 Oracle Connection and Connection Factory</a></h2>
22946
22947 <p>The <code>oracle::connection</code> class has the following interface:</p>
22948
22949 <pre class="cxx">
22950 namespace odb
22951 {
22952 namespace oracle
22953 {
22954 class connection: public odb::connection
22955 {
22956 public:
22957 connection (database&amp;);
22958 connection (database&amp;, OCISvcCtx*);
22959
22960 OCISvcCtx*
22961 handle ();
22962
22963 OCIError*
22964 error_handle ();
22965
22966 details::buffer&amp;
22967 lob_buffer ();
22968 };
22969
22970 typedef details::shared_ptr&lt;connection> connection_ptr;
22971 }
22972 }
22973 </pre>
22974
22975 <p>For more information on the <code>odb::connection</code> interface, refer
22976 to <a href="#3.6">Section 3.6, "Connections"</a>. The first overloaded
22977 <code>oracle::connection</code> constructor creates a new OCI service
22978 context. The OCI statement caching is enabled for the underlying session
22979 while the OCI connection pooling and session pooling are not used. The
22980 second constructor allows us to create a <code>connection</code> instance by
22981 providing an already connected Oracle service context. Note that the
22982 <code>connection</code> instance assumes ownership of this handle. The
22983 <code>handle()</code> accessor returns the OCI service context handle
22984 associated with the <code>connection</code> instance.</p>
22985
22986 <p>An OCI error handle is allocated for each <code>connection</code>
22987 instance and is available via the <code>error_handle()</code> accessor
22988 function.</p>
22989
22990 <p>Additionally, each <code>connection</code> instance maintains a large
22991 object (LOB) buffer. This buffer is used by the Oracle ODB runtime
22992 as an intermediate storage for piecewise handling of LOB data.
22993 By default, the LOB buffer has zero initial capacity and is
22994 expanded to 4096 bytes when the first LOB operation is performed.
22995 If your application requires a bigger or smaller LOB buffer, you can
22996 specify a custom capacity using the <code>lob_buffer()</code>
22997 accessor.</p>
22998
22999 <p>The <code>oracle::connection_factory</code> abstract class has the
23000 following interface:</p>
23001
23002 <pre class="cxx">
23003 namespace odb
23004 {
23005 namespace oracle
23006 {
23007 class connection_factory
23008 {
23009 public:
23010 virtual void
23011 database (database&amp;) = 0;
23012
23013 virtual connection_ptr
23014 connect () = 0;
23015 };
23016 }
23017 }
23018 </pre>
23019
23020 <p>The <code>database()</code> function is called when a connection
23021 factory is associated with a database instance. This happens in
23022 the <code>odb::oracle::database</code> class constructors. The
23023 <code>connect()</code> function is called whenever a database
23024 connection is requested.</p>
23025
23026 <p>The two implementations of the <code>connection_factory</code>
23027 interface provided by the Oracle ODB runtime are
23028 <code>new_connection_factory</code> and
23029 <code>connection_pool_factory</code>. You will need to include
23030 the <code>&lt;odb/oracle/connection-factory.hxx></code>
23031 header file to make the <code>connection_factory</code> interface
23032 and these implementation classes available in your application.</p>
23033
23034 <p>The <code>new_connection_factory</code> class creates a new
23035 connection whenever one is requested. When a connection is no
23036 longer needed, it is released and closed. The
23037 <code>new_connection_factory</code> class has the following
23038 interface:</p>
23039
23040 <pre class="cxx">
23041 namespace odb
23042 {
23043 namespace oracle
23044 {
23045 class new_connection_factory: public connection_factory
23046 {
23047 public:
23048 new_connection_factory ();
23049 };
23050 };
23051 </pre>
23052
23053 <p>The <code>connection_pool_factory</code> class implements a
23054 connection pool. It has the following interface:</p>
23055
23056 <pre class="cxx">
23057 namespace odb
23058 {
23059 namespace oracle
23060 {
23061 class connection_pool_factory: public connection_factory
23062 {
23063 public:
23064 connection_pool_factory (std::size_t max_connections = 0,
23065 std::size_t min_connections = 0);
23066
23067 protected:
23068 class pooled_connection: public connection
23069 {
23070 public:
23071 pooled_connection (database_type&amp;);
23072 pooled_connection (database_type&amp;, OCISvcCtx*);
23073 };
23074
23075 typedef details::shared_ptr&lt;pooled_connection> pooled_connection_ptr;
23076
23077 virtual pooled_connection_ptr
23078 create ();
23079 };
23080 };
23081 </pre>
23082
23083 <p>The <code>max_connections</code> argument in the
23084 <code>connection_pool_factory</code> constructor specifies the maximum
23085 number of concurrent connections that this pool factory will
23086 maintain. Similarly, the <code>min_connections</code> argument
23087 specifies the minimum number of available connections that
23088 should be kept open.</p>
23089
23090 <p>Whenever a connection is requested, the pool factory first
23091 checks if there is an unused connection that can be returned.
23092 If there is none, the pool factory checks the
23093 <code>max_connections</code> value to see if a new connection
23094 can be created. If the total number of connections maintained
23095 by the pool is less than this value, then a new connection is
23096 created and returned. Otherwise, the caller is blocked until
23097 a connection becomes available.</p>
23098
23099 <p>When a connection is released, the pool factory first checks
23100 if there are blocked callers waiting for a connection. If so, then
23101 one of them is unblocked and is given the connection. Otherwise,
23102 the pool factory checks whether the total number of connections
23103 maintained by the pool is greater than the <code>min_connections</code>
23104 value. If that's the case, the connection is closed. Otherwise, the
23105 connection is added to the pool of available connections to be
23106 returned on the next request. In other words, if the number of
23107 connections maintained by the pool exceeds <code>min_connections</code>
23108 and there are no callers waiting for a new connection,
23109 the pool will close the excess connections.</p>
23110
23111 <p>If the <code>max_connections</code> value is 0, then the pool will
23112 create a new connection whenever all of the existing connections
23113 are in use. If the <code>min_connections</code> value is 0, then
23114 the pool will never close a connection and instead maintain all
23115 the connections that were ever created.</p>
23116
23117 <p>The <code>create()</code> virtual function is called whenever the
23118 pool needs to create a new connection. By deriving from the
23119 <code>connection_pool_factory</code> class and overriding this
23120 function we can implement custom connection establishment
23121 and configuration.</p>
23122
23123 <p>If you pass <code>NULL</code> as the connection factory to one of the
23124 <code>database</code> constructors, then the
23125 <code>connection_pool_factory</code> instance will be created by default
23126 with the min and max connections values set to <code>0</code>. The
23127 following code fragment shows how we can pass our own connection factory
23128 instance:</p>
23129
23130 <pre class="cxx">
23131 #include &lt;odb/database.hxx>
23132
23133 #include &lt;odb/oracle/database.hxx>
23134 #include &lt;odb/oracle/connection-factory.hxx>
23135
23136 int
23137 main (int argc, char* argv[])
23138 {
23139 auto_ptr&lt;odb::oracle::connection_factory> f (
23140 new odb::oracle::connection_pool_factory (20));
23141
23142 auto_ptr&lt;odb::database> db (
23143 new oracle::database (argc, argv, false, 0, 0, 0, f));
23144 }
23145 </pre>
23146
23147 <h2><a name="20.4">20.4 Oracle Exceptions</a></h2>
23148
23149 <p>The Oracle ODB runtime library defines the following
23150 Oracle-specific exceptions:</p>
23151
23152 <pre class="cxx">
23153 namespace odb
23154 {
23155 namespace oracle
23156 {
23157 class database_exception: odb::database_exception
23158 {
23159 public:
23160 class record
23161 {
23162 public:
23163 sb4
23164 error () const;
23165
23166 const std::string&amp;
23167 message () const;
23168 };
23169
23170 typedef std::vector&lt;record> records;
23171
23172 typedef records::size_type size_type;
23173 typedef records::const_iterator iterator;
23174
23175 iterator
23176 begin () const;
23177
23178 iterator
23179 end () const;
23180
23181 size_type
23182 size () const;
23183
23184 virtual const char*
23185 what () const throw ();
23186 };
23187
23188 class cli_exception: odb::exception
23189 {
23190 public:
23191 virtual const char*
23192 what () const throw ();
23193 };
23194
23195 class invalid_oci_handle: odb::exception
23196 {
23197 public:
23198 virtual const char*
23199 what () const throw ();
23200 };
23201 }
23202 }
23203 </pre>
23204
23205 <p>You will need to include the <code>&lt;odb/oracle/exceptions.hxx></code>
23206 header file to make these exceptions available in your application.</p>
23207
23208 <p>The <code>odb::oracle::database_exception</code> is thrown if
23209 an Oracle database operation fails. The Oracle-specific error
23210 information is stored as a series of records, each containing
23211 the error code as a signed 4-byte integer and the message string.
23212 All this information is also combined and returned in a
23213 human-readable form by the <code>what()</code> function.</p>
23214
23215 <p>The <code>odb::oracle::cli_exception</code> is thrown by the
23216 command line parsing constructor of the <code>odb::oracle::database</code>
23217 class if the Oracle option values are missing or invalid. The
23218 <code>what()</code> function returns a human-readable description
23219 of an error.</p>
23220
23221 <p>The <code>odb::oracle::invalid_oci_handle</code> is thrown if an
23222 invalid handle is passed to an OCI function or if an OCI function
23223 was unable to allocate a handle. The former normally indicates
23224 a programming error while the latter indicates an out of memory
23225 condition. The <code>what()</code> function returns a human-readable
23226 description of an error.</p>
23227
23228 <h2><a name="20.5">20.5 Oracle Limitations</a></h2>
23229
23230 <p>The following sections describe Oracle-specific limitations imposed
23231 by the current Oracle and ODB runtime versions.</p>
23232
23233 <h3><a name="20.5.1">20.5.1 Identifier Truncation</a></h3>
23234
23235 <p>Oracle limits the length of database identifiers (table, column, etc.,
23236 names) to 30 characters. The ODB compiler automatically truncates
23237 any identifier that is longer than 30 characters. This, however,
23238 can lead to duplicate names. A common symptom of this problem
23239 are errors during the database schema creation indicating
23240 that a database object with the same name already exists. To
23241 resolve this problem we can assign custom, shorter identifiers
23242 using the <code>db&nbsp;table</code> and <code>db&nbsp;column</code>
23243 pragmas (<a href="#14">Chapter 14, "ODB Pragma Language")</a>. For
23244 example:</p>
23245
23246 <pre class="cxx">
23247 #pragma db object
23248 class long_class_name
23249 {
23250 ...
23251
23252 std::vector&lt;int> long_container_x_;
23253 std::vector&lt;int> long_container_y_;
23254 };
23255 </pre>
23256
23257 <p>In the above example, the names of the two container tables will be
23258 <code>long_class_name_long_container_x_</code> and
23259 <code>long_class_name_long_container_y_</code>. However, when
23260 truncated to 30 characters, they both become
23261 <code>long_class_name_long_container</code>. To resolve this
23262 collision we can assign a custom table name for each container:</p>
23263
23264 <pre class="cxx">
23265 #pragma db object
23266 class long_class_name
23267 {
23268 ...
23269
23270 #pragma db table("long_class_name_cont_x")
23271 std::vector&lt;int> long_container_x_;
23272
23273 #pragma db table("long_class_name_cont_y")
23274 std::vector&lt;int> long_container_y_;
23275 };
23276 </pre>
23277
23278 <h3><a name="20.5.2">20.5.2 Query Result Caching</a></h3>
23279
23280 <p>Oracle ODB runtime implementation does not perform query result caching
23281 (<a href="#4.4">Section 4.4, "Query Result"</a>) even when explicitly
23282 requested. The OCI API supports interleaving execution of multiple
23283 prepared statements on a single connection. As a result, with OCI,
23284 it is possible to have multiple uncached results and calls to other
23285 database functions do not invalidate them. The only limitation of
23286 the uncached Oracle results is the unavailability of the
23287 <code>result::size()</code> function. If you call this function on
23288 an Oracle query result, then the <code>odb::result_not_cached</code>
23289 exception (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>) is
23290 always thrown. Future versions of the Oracle ODB runtime library
23291 may add support for result caching.</p>
23292
23293 <h3><a name="20.5.3">20.5.3 Foreign Key Constraints</a></h3>
23294
23295 <p>ODB assumes the standard SQL behavior which requires that
23296 foreign key constraints checking is deferred until the
23297 transaction is committed. Default Oracle behavior is
23298 to check such constraints immediately. As a result, when
23299 used with ODB, a custom database schema that defines foreign
23300 key constraints may need to declare such constraints as
23301 <code>INITIALLY DEFERRED</code>, as shown in the following example.
23302 By default, schemas generated by the ODB compiler meet this requirement
23303 automatically.</p>
23304
23305 <pre class="sql">
23306 CREATE TABLE Employee (
23307 ...
23308 employer NUMBER(20) REFERENCES Employer(id)
23309 DEFERRABLE INITIALLY DEFERRED);
23310 </pre>
23311
23312 <p>You can override the default behavior and instruct the ODB
23313 compiler to generate non-deferrable foreign keys by specifying
23314 the <code>--fkeys-deferrable-mode not_deferrable</code> ODB
23315 compiler option. Note, however, that in this case the order in
23316 which you persist, update, and erase objects within a transaction
23317 becomes important.</p>
23318
23319 <h3><a name="20.5.4">20.5.4 Unique Constraint Violations</a></h3>
23320
23321 <p>Due to the granularity of the Oracle error codes, it is impossible
23322 to distinguish between the duplicate primary key and other unique
23323 constraint violations. As a result, when making an object persistent,
23324 the Oracle ODB runtime will translate all unique constraint violation
23325 errors to the <code>object_already_persistent</code> exception
23326 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>).</p>
23327
23328 <h3><a name="20.5.5">20.5.5 Large <code>FLOAT</code> and
23329 <code>NUMBER</code> Types</a></h3>
23330
23331 <p>The Oracle <code>FLOAT</code> type with a binary precision greater
23332 than 53 and fixed-point <code>NUMBER</code> type with a decimal
23333 precision greater than 15 cannot be automatically extracted
23334 into the C++ <code>float</code> and <code>double</code> types.
23335 Instead, the Oracle ODB runtime uses a 21-byte buffer containing
23336 the binary representation of a value as an image type for such
23337 <code>FLOAT</code> and <code>NUMBER</code> types. In order to
23338 convert them into an application-specific large number representation,
23339 you will need to provide a suitable <code>value_traits</code>
23340 template specialization. For more information on the binary format
23341 used to store the <code>FLOAT</code> and <code>NUMBER</code> values,
23342 refer to the Oracle Call Interface (OCI) documentation.</p>
23343
23344 <p>An alternative approach to accessing large <code>FLOAT</code> and
23345 <code>NUMBER</code> values is to map these type to one of the
23346 natively supported ones, as discussed in <a href="#14.8">Section
23347 14.8, "Database Type Mapping Pragmas"</a>.</p>
23348
23349 <p>Note that a <code>NUMBER</code> type that is used to represent a
23350 floating point number (declared by specifying <code>NUMBER</code>
23351 without any range and scale) can be extracted into the C++
23352 <code>float</code> and <code>double</code> types.</p>
23353
23354 <h3><a name="20.5.6">20.5.6 Timezones</a></h3>
23355
23356 <p>ODB does not currently support the Oracle date-time types with timezone
23357 information. However, these types can be accessed by mapping them to
23358 one of the natively supported types, as discussed in
23359 <a href="#14.8">Section 14.8, "Database Type Mapping Pragmas"</a>.</p>
23360
23361 <h3><a name="20.5.7">20.5.7 <code>LONG</code> Types</a></h3>
23362
23363 <p>ODB does not support the deprecated Oracle <code>LONG</code> and
23364 <code>LONG RAW</code> data types. However, these types can be accessed
23365 by mapping them to one of the natively supported types, as discussed
23366 in <a href="#14.8">Section 14.8, "Database Type Mapping Pragmas"</a>.</p>
23367
23368 <h3><a name="20.5.8">20.5.8 LOB Types and By-Value Accessors/Modifiers</a></h3>
23369
23370 <p>As discussed in <a href="#14.4.5">Section 14.4.5,
23371 "<code>get</code>/<code>set</code>/<code>access</code>"</a>, by-value
23372 accessor and modifier expressions cannot be used with data members
23373 of Oracle large object (LOB) data types: <code>BLOB</code>,
23374 <code>CLOB</code>, and <code>NCLOB</code>. The Oracle ODB runtime
23375 uses streaming for reading/writing LOB data directly from/to
23376 data members. As a result, by-reference accessors and modifiers
23377 should be used for these data types.</p>
23378
23379 <h3><a name="20.5.9">20.5.9 Database Schema Evolution</a></h3>
23380
23381 <p>In Oracle, the type of the <code>name</code> column in the
23382 <code>schema_version</code> table is <code>VARCHAR2(512)</code>.
23383 Because this column is a primary key and <code>VARCHAR2</code>
23384 represents empty strings as <code>NULL</code> values, it is
23385 impossible to store an empty string in this column, which
23386 is what is used to represent the default schema name. As a
23387 result, in Oracle, the empty schema name is stored as a
23388 string containing a single space character. ODB performs
23389 all the necessary translations automatically and normally
23390 you do not need to worry about this implementation detail
23391 unless you are querying or modifying the <code>schema_version</code>
23392 table directly.</p>
23393
23394 <h2><a name="20.6">20.6 Oracle Index Definitions</a></h2>
23395
23396 <p>When the <code>index</code> pragma (<a href="#14.7">Section 14.7,
23397 "Index Definition Pragmas"</a>) is used to define an Oracle index,
23398 the <code>type</code> clause specifies the index type (for example,
23399 <code>UNIQUE</code>, <code>BITMAP</code>), the <code>method</code>
23400 clause is not used, and the <code>options</code> clause specifies
23401 additional index properties, such as partitioning, table spaces, etc.
23402 The column options can be used to specify the sort order. For example:</p>
23403
23404 <pre class="cxx">
23405 #pragma db object
23406 class object
23407 {
23408 ...
23409
23410 std::string name_;
23411
23412 #pragma db index \
23413 type("BITMAP") \
23414 member(name_, "DESC") \
23415 options("TABLESPACE TBS1")
23416 };
23417 </pre>
23418
23419 <p>Index names in Oracle are schema-global. To avoid name clashes,
23420 ODB automatically prefixes each index name with the table name on
23421 which it is defined.</p>
23422
23423
23424 <!-- CHAPTER -->
23425
23426
23427 <hr class="page-break"/>
23428 <h1><a name="21">21 Microsoft SQL Server Database</a></h1>
23429
23430 <p>To generate support code for the SQL Server database you will need
23431 to pass the "<code>--database&nbsp;mssql</code>"
23432 (or "<code>-d&nbsp;mssql</code>") option to the ODB compiler.
23433 Your application will also need to link to the SQL Server ODB runtime
23434 library (<code>libodb-mssql</code>). All SQL Server-specific ODB
23435 classes are defined in the <code>odb::mssql</code> namespace.</p>
23436
23437 <h2><a name="21.1">21.1 SQL Server Type Mapping</a></h2>
23438
23439 <p>The following table summarizes the default mapping between basic
23440 C++ value types and SQL Server database types. This mapping can be
23441 customized on the per-type and per-member basis using the ODB
23442 Pragma Language (<a href="#14">Chapter 14, "ODB Pragma Language"</a>).</p>
23443
23444 <!-- border="1" is necessary for html2ps -->
23445 <table id="mapping" border="1">
23446 <tr>
23447 <th>C++ Type</th>
23448 <th>SQL Server Type</th>
23449 <th>Default <code>NULL</code> Semantics</th>
23450 </tr>
23451
23452 <tr>
23453 <td><code>bool</code></td>
23454 <td><code>BIT</code></td>
23455 <td><code>NOT NULL</code></td>
23456 </tr>
23457
23458 <tr>
23459 <td><code>char</code></td>
23460 <td><code>CHAR(1)</code></td>
23461 <td><code>NOT NULL</code></td>
23462 </tr>
23463
23464 <tr>
23465 <td><code>signed char</code></td>
23466 <td><code>TINYINT</code></td>
23467 <td><code>NOT NULL</code></td>
23468 </tr>
23469
23470 <tr>
23471 <td><code>unsigned char</code></td>
23472 <td><code>TINYINT</code></td>
23473 <td><code>NOT NULL</code></td>
23474 </tr>
23475
23476 <tr>
23477 <td><code>short</code></td>
23478 <td><code>SMALLINT</code></td>
23479 <td><code>NOT NULL</code></td>
23480 </tr>
23481
23482 <tr>
23483 <td><code>unsigned short</code></td>
23484 <td><code>SMALLINT</code></td>
23485 <td><code>NOT NULL</code></td>
23486 </tr>
23487
23488 <tr>
23489 <td><code>int</code></td>
23490 <td><code>INT</code></td>
23491 <td><code>NOT NULL</code></td>
23492 </tr>
23493
23494 <tr>
23495 <td><code>unsigned int</code></td>
23496 <td><code>INT</code></td>
23497 <td><code>NOT NULL</code></td>
23498 </tr>
23499
23500 <tr>
23501 <td><code>long</code></td>
23502 <td><code>BIGINT</code></td>
23503 <td><code>NOT NULL</code></td>
23504 </tr>
23505
23506 <tr>
23507 <td><code>unsigned long</code></td>
23508 <td><code>BIGINT</code></td>
23509 <td><code>NOT NULL</code></td>
23510 </tr>
23511
23512 <tr>
23513 <td><code>long long</code></td>
23514 <td><code>BIGINT</code></td>
23515 <td><code>NOT NULL</code></td>
23516 </tr>
23517
23518 <tr>
23519 <td><code>unsigned long long</code></td>
23520 <td><code>BIGINT</code></td>
23521 <td><code>NOT NULL</code></td>
23522 </tr>
23523
23524 <tr>
23525 <td><code>float</code></td>
23526 <td><code>REAL</code></td>
23527 <td><code>NOT NULL</code></td>
23528 </tr>
23529
23530 <tr>
23531 <td><code>double</code></td>
23532 <td><code>FLOAT</code></td>
23533 <td><code>NOT NULL</code></td>
23534 </tr>
23535
23536 <tr>
23537 <td><code>std::string</code></td>
23538 <td><code>VARCHAR(512)/VARCHAR(256)</code></td>
23539 <td><code>NOT NULL</code></td>
23540 </tr>
23541
23542 <tr>
23543 <td><code>char[N]</code></td>
23544 <td><code>VARCHAR(N-1)</code></td>
23545 <td><code>NOT NULL</code></td>
23546 </tr>
23547
23548 <tr>
23549 <td><code>std::wstring</code></td>
23550 <td><code>NVARCHAR(512)/NVARCHAR(256)</code></td>
23551 <td><code>NOT NULL</code></td>
23552 </tr>
23553
23554 <tr>
23555 <td><code>wchar_t[N]</code></td>
23556 <td><code>NVARCHAR(N-1)</code></td>
23557 <td><code>NOT NULL</code></td>
23558 </tr>
23559
23560 <tr>
23561 <td><code>GUID</code></td>
23562 <td><code>UNIQUEIDENTIFIER</code></td>
23563 <td><code>NOT NULL</code></td>
23564 </tr>
23565
23566 </table>
23567
23568 <p>It is possible to map the <code>char</code> C++ type to an integer
23569 database type (for example, <code>TINYINT</code>) using the
23570 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
23571 "<code>type</code>"</a>).</p>
23572
23573 <p>Note that the <code>std::string</code> and <code>std::wstring</code>
23574 types are mapped differently depending on whether a member of one of
23575 these types is an object id or not. If the member is an object id,
23576 then for this member <code>std::string</code> is mapped
23577 to <code>VARCHAR(256)</code> and <code>std::wstring</code> &mdash;
23578 to <code>NVARCHAR(256)</code>. Otherwise, <code>std::string</code>
23579 is mapped to <code>VARCHAR(512)</code> and <code>std::wstring</code>
23580 &mdash; to <code>NVARCHAR(512)</code>. Note also that you can
23581 always change this mapping using the <code>db&nbsp;type</code> pragma
23582 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>).</p>
23583
23584 <p>Additionally, by default, C++ enums and C++11 enum classes are
23585 automatically mapped to the SQL Server types corresponding to their
23586 underlying integral types (see table above). The default
23587 <code>NULL</code> semantics is <code>NOT NULL</code>. For
23588 example:</p>
23589
23590 <pre class="cxx">
23591 enum color {red, green, blue};
23592 enum class taste: unsigned char
23593 {
23594 bitter = 1,
23595 sweet,
23596 sour = 4,
23597 salty
23598 };
23599
23600 #pragma db object
23601 class object
23602 {
23603 ...
23604
23605 color color_; // Automatically mapped to INT.
23606 taste taste_; // Automatically mapped to TINYINT.
23607 };
23608 </pre>
23609
23610 <p>Note also that because SQL Server does not support unsigned integers,
23611 the <code>unsigned&nbsp;short</code>, <code>unsigned&nbsp;int</code>, and
23612 <code>unsigned&nbsp;long</code>/<code>unsigned&nbsp;long&nbsp;long</code> C++ types
23613 are by default mapped to the <code>SMALLINT</code>, <code>INT</code>,
23614 and <code>BIGINT</code> SQL Server types, respectively. The sign bit
23615 of the value stored by the database for these types will contain
23616 the most significant bit of the actual unsigned value being
23617 persisted. Similarly, because there is no signed version of the
23618 <code>TINYINT</code> SQL Server type, by default, the
23619 <code>signed char</code> C++ type is mapped to <code>TINYINT</code>.
23620 As a result, the most significant bit of the value stored by the
23621 database for this type will contain the sign bit of the actual
23622 signed value being persisted.</p>
23623
23624 <p>It is also possible to add support for additional SQL Server types,
23625 such as geospatial types, <code>XML</code>, and user-defined types.
23626 For more information, refer to <a href="#14.8">Section 14.8, "Database
23627 Type Mapping Pragmas"</a>.</p>
23628
23629 <h3><a name="21.1.1">21.1.1 String Type Mapping</a></h3>
23630
23631 <p>The SQL Server ODB runtime library provides support for mapping the
23632 <code>std::string</code>, <code>char[N]</code>, and
23633 <code>std::array&lt;char, N></code> types to the SQL Server
23634 <code>CHAR</code>, <code>VARCHAR</code>, and <code>TEXT</code>
23635 types as well as the <code>std::wstring</code>, <code>wchar_t[N]</code>,
23636 and <code>std::array&lt;wchar_t, N></code> types to <code>NCHAR</code>,
23637 <code>NVARCHAR</code>, and <code>NTEXT</code>. However, these mappings
23638 are not enabled by default (in particular, by default,
23639 <code>std::array</code> will be treated as a container). To enable the
23640 alternative mappings for these types we need to specify the database
23641 type explicitly using the <code>db&nbsp;type</code> pragma
23642 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), for
23643 example:</p>
23644
23645 <pre class="cxx">
23646 #pragma db object
23647 class object
23648 {
23649 ...
23650
23651 #pragma db type ("CHAR(2)")
23652 char state_[2];
23653
23654 #pragma db type ("NVARCHAR(max)")
23655 std::wstring text_;
23656 };
23657 </pre>
23658
23659 <p>Alternatively, this can be done on the per-type basis, for example:</p>
23660
23661 <pre class="cxx">
23662 #pragma db value(std::wstring) type("NVARCHAR(max)")
23663
23664 #pragma db object
23665 class object
23666 {
23667 ...
23668
23669 std::wstring text_; // Mapped to NVARCHAR(max).
23670 };
23671 </pre>
23672
23673 <p>The <code>char[N]</code>, <code>std::array&lt;char, N></code>,
23674 <code>wchar_t[N]</code>, and <code>std::array&lt;wchar_t, N></code>
23675 values may or may not be zero-terminated. When extracting such values
23676 from the database, ODB will append the zero terminator if there is
23677 enough space.</p>
23678
23679 <p>See also <a href="#21.1.4">Section 21.1.4, "Long String and Binary
23680 Types"</a> for certain limitations of long string types.</p>
23681
23682 <h3><a name="21.1.2">21.1.2 Binary Type and <code>UNIQUEIDENTIFIER</code> Mapping</a></h3>
23683
23684 <p>The SQL Server ODB runtime library also provides support for mapping the
23685 <code>std::vector&lt;char></code>,
23686 <code>std::vector&lt;unsigned&nbsp;char></code>,
23687 <code>char[N]</code>, <code>unsigned&nbsp;char[N]</code>,
23688 <code>std::array&lt;char, N></code>, and <code>std::array&lt;unsigned char, N></code>
23689 types to the SQL Server <code>BINARY</code>, <code>VARBINARY</code>, and
23690 <code>IMAGE</code> types. There is also support for mapping the
23691 <code>char[16]</code> array to the SQL Server <code>UNIQUEIDENTIFIER</code>
23692 type. However, these mappings are not enabled by default (in particular,
23693 by default, <code>std::vector</code> and <code>std::array</code> will
23694 be treated as containers). To enable the alternative mappings for these
23695 types we need to specify the database type explicitly using the
23696 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
23697 "<code>type</code>"</a>), for example:</p>
23698
23699 <pre class="cxx">
23700 #pragma db object
23701 class object
23702 {
23703 ...
23704
23705 #pragma db type("UNIQUEIDENTIFIER")
23706 char uuid_[16];
23707
23708 #pragma db type("VARBINARY(max)")
23709 std::vector&lt;char> buf_;
23710
23711 #pragma db type("BINARY(256)")
23712 unsigned char data_[256];
23713 };
23714 </pre>
23715
23716 <p>Alternatively, this can be done on the per-type basis, for example:</p>
23717
23718 <pre class="cxx">
23719 typedef std::vector&lt;char> buffer;
23720 #pragma db value(buffer) type("VARBINARY(max)")
23721
23722 #pragma db object
23723 class object
23724 {
23725 ...
23726
23727 buffer buf_; // Mapped to VARBINARY(max).
23728 };
23729 </pre>
23730
23731 <p>Note also that in native queries (<a href="#4">Chapter 4, "Querying
23732 the Database"</a>) <code>char[N]</code> and
23733 <code>std::array&lt;char, N></code> parameters are by default passed
23734 as a string rather than a binary. To pass such parameters as a binary,
23735 we need to specify the database type explicitly in the
23736 <code>_val()</code>/<code>_ref()</code> calls. Note also that we
23737 don't need to do this for the integrated queries, for example:</p>
23738
23739 <pre class="cxx">
23740 char u[16] = {...};
23741
23742 db.query&lt;object> ("uuid = " + query::_val&lt;odb::mssql::id_binary> (u));
23743 db.query&lt;object> (
23744 "uuid = " + query::_val&lt;odb::mssql::id_uniqueidentifier> (u));
23745 db.query&lt;object> (query::uuid == query::_ref (u));
23746 </pre>
23747
23748 <p>See also <a href="#21.1.4">Section 21.1.4, "Long String and Binary
23749 Types"</a> for certain limitations of long binary types.</p>
23750
23751 <h3><a name="21.1.3">21.1.3 <code>ROWVERSION</code> Mapping</a></h3>
23752
23753 <p><code>ROWVERSION</code> is a special SQL Server data type that is
23754 automatically incremented by the database server whenever a row
23755 is inserted or updated. As such, it is normally used to implement
23756 optimistic concurrency and ODB provides support for using
23757 <code>ROWVERSION</code> instead of the more portable approach
23758 for optimistic concurrency (<a href="#12">Chapter 12, "Optimistic
23759 Concurrency"</a>).</p>
23760
23761 <p><code>ROWVERSION</code> is a 64-bit value which is mapped by ODB
23762 to <code>unsigned long long</code>. As a result, to use
23763 <code>ROWVERSION</code> for optimistic concurrency we need to
23764 make sure that the version column is of the <code>unsigned long
23765 long</code> type. We also need to explicitly specify that it
23766 should be mapped to the <code>ROWVERSION</code> data type. For
23767 example:</p>
23768
23769 <pre class="cxx">
23770 #pragma db object optimistic
23771 class person
23772 {
23773 ...
23774
23775 #pragma db version type("ROWVERSION")
23776 unsigned long long version_;
23777 };
23778 </pre>
23779
23780 <h3><a name="21.1.4">21.1.4 Long String and Binary Types</a></h3>
23781
23782 <p>For SQL Server, ODB handles character, national character, and
23783 binary data in two different ways depending on its maximum length.
23784 If the maximum length (in bytes) is less than or equal to the limit
23785 specified with the <code>--mssql-short-limit</code> ODB compiler
23786 option (1024 by default), then it is treated as <i>short data</i>,
23787 otherwise &mdash; <i>long data</i>. For short data ODB pre-allocates
23788 an intermediate buffer of the maximum size and binds it directly
23789 to a parameter or result column. This way the underlying database
23790 API (ODBC) can read/write directly from/to this buffer. In the case
23791 of long data, the data is read/written in chunks using the
23792 <code>SQLGetData()</code>/<code>SQLPutData()</code> ODBC functions.
23793 While the long data approach reduces the amount of memory used by
23794 the application, it may require greater CPU resources.</p>
23795
23796 <p>Long data has a number of limitations. In particular, when setting
23797 a custom short data limit, make sure that it is sufficiently large
23798 so that no object id in the application is treated as long data.
23799 It is also impossible to load an object or view with long data more
23800 than once as part of a query result iteration (<a href="#4.4">Section
23801 4.4, "Query Result"</a>). Any such attempt will result in the
23802 <code>odb::mssql::long_data_reload</code> exception
23803 (<a href="#21.4">Section 21.4, "SQL Server Exceptions"</a>). For
23804 example:</p>
23805
23806 <pre class="cxx">
23807 #pragma db object
23808 class object
23809 {
23810 ...
23811
23812 int num_;
23813
23814 #pragma db type("VARCHAR(max)") // Long data.
23815 std::string str_;
23816 };
23817
23818 typedef odb::query&lt;object> query;
23819 typedef odb::result&lt;object> result;
23820
23821 transaction t (db.begin ());
23822
23823 result r (db.query&lt;object> (query::num &lt; 100));
23824
23825 for (result::iterator i (r.begin ()); i != r.end (); ++i)
23826 {
23827 if (!i->str_.empty ()) // First load.
23828 {
23829 object o;
23830 i.load (o); // Error: second load, long_data_reload is thrown.
23831 }
23832 }
23833
23834 t.commit ();
23835 </pre>
23836
23837 <p>Finally, if a native view (<a href="#10.6">Section 10.6, "Native
23838 Views"</a>) contains one or more long data members, then such
23839 members should come last both in the select-list of the native
23840 SQL query and the list of data members in the C++ class.</p>
23841
23842 <h2><a name="21.2">21.2 SQL Server Database Class</a></h2>
23843
23844 <p>The SQL Server <code>database</code> class encapsulates the ODBC
23845 environment handle as well as the server instance address and
23846 user credentials that are used to establish connections to the
23847 database. It has the following interface:</p>
23848
23849 <pre class="cxx">
23850 namespace odb
23851 {
23852 namespace mssql
23853 {
23854 enum protocol
23855 {
23856 protocol_auto,
23857 protocol_tcp, // TCP/IP.
23858 protocol_lpc, // Shared memory (local procedure call).
23859 protocol_np // Named pipes.
23860 };
23861
23862 enum transaction_isolation
23863 {
23864 isolation_read_uncommitted,
23865 isolation_read_committed, // SQL Server default.
23866 isolation_repeatable_read,
23867 isolation_snapshot,
23868 isolation_serializable
23869 };
23870
23871 class database: public odb::database
23872 {
23873 public:
23874 typedef protocol protocol_type;
23875 typedef transaction_isolation transaction_isolation_type;
23876
23877 database (const std::string&amp; user,
23878 const std::string&amp; password,
23879 const std::string&amp; db,
23880 const std::string&amp; server,
23881 const std::string&amp; driver = "",
23882 const std::string&amp; extra_connect_string = "",
23883 transaction_isolation_type = isolation_read_committed,
23884 SQLHENV environment = 0,
23885 std::[auto|unique]_ptr&lt;connection_factory> = 0);
23886
23887 database (const std::string&amp; user,
23888 const std::string&amp; password,
23889 const std::string&amp; db,
23890 protocol_type protocol = protocol_auto,
23891 const std::string&amp; host = "",
23892 const std::string&amp; instance = "",
23893 const std::string&amp; driver = "",
23894 const std::string&amp; extra_connect_string = "",
23895 transaction_isolation_type = isolation_read_committed,
23896 SQLHENV environment = 0,
23897 std::[auto|unique]_ptr&lt;connection_factory> = 0);
23898
23899 database (const std::string&amp; user,
23900 const std::string&amp; password,
23901 const std::string&amp; db,
23902 const std::string&amp; host,
23903 unsigned int port,
23904 const std::string&amp; driver = "",
23905 const std::string&amp; extra_connect_string = "",
23906 transaction_isolation_type = isolation_read_committed,
23907 SQLHENV environment = 0,
23908 std::[auto|unique]_ptr&lt;connection_factory> = 0);
23909
23910 database (const std::string&amp; connect_string,
23911 transaction_isolation_type = isolation_read_committed,
23912 SQLHENV environment = 0,
23913 std::[auto|unique]_ptr&lt;connection_factory> = 0);
23914
23915 database (int&amp; argc,
23916 char* argv[],
23917 bool erase = false,
23918 const std::string&amp; extra_connect_string = "",
23919 transaction_isolation_type = isolation_read_committed,
23920 SQLHENV environment = 0,
23921 std::[auto|unique]_ptr&lt;connection_factory> = 0);
23922
23923 static void
23924 print_usage (std::ostream&amp;);
23925
23926 public:
23927 const std::string&amp;
23928 user () const;
23929
23930 const std::string&amp;
23931 password () const;
23932
23933 const std::string&amp;
23934 db () const;
23935
23936 protocol_type
23937 protocol () const;
23938
23939 const std::string&amp;
23940 host () const;
23941
23942 const std::string&amp;
23943 instance () const;
23944
23945 unsigned int
23946 port () const;
23947
23948 const std::string&amp;
23949 server () const;
23950
23951 const std::string&amp;
23952 driver () const;
23953
23954 const std::string&amp;
23955 extra_connect_string () const;
23956
23957 transaction_isolation_type
23958 transaction_isolation () const;
23959
23960 const std::string&amp;
23961 connect_string () const;
23962
23963 SQLHENV
23964 environment ();
23965
23966 public:
23967 connection_ptr
23968 connection ();
23969 };
23970 }
23971 }
23972 </pre>
23973
23974 <p>You will need to include the <code>&lt;odb/mssql/database.hxx></code>
23975 header file to make this class available in your application.</p>
23976
23977 <p>The overloaded <code>database</code> constructors allow us to specify the
23978 SQL Server database parameters that should be used when connecting to the
23979 database. The <code>user</code> and <code>password</code> arguments
23980 specify the login name and password. If <code>user</code> is empty,
23981 then Windows authentication is used and the <code>password</code>
23982 argument is ignored. The <code>db</code> argument specifies the
23983 database name to open. If it is empty, then the default database for
23984 the user is used.</p>
23985
23986 <p>The <code>server</code> argument in the first constructor specifies
23987 the SQL Server instance address in the standard SQL Server address
23988 format:</p>
23989
23990 <p>
23991 <code>[<i>protocol</i><b>:</b>]<i>host</i>[<b>\</b><i>instance</i>][<b>,</b><i>port</i>]</code>
23992 </p>
23993
23994 <p>Where <code><i>protocol</i></code> can be <code>tcp</code>
23995 (TCP/IP), <code>lpc</code> (shared memory), or
23996 <code>np</code> (named pipe). If protocol is not specified, then a
23997 suitable protocol is automatically selected based on the SQL Server
23998 Native Client configuration. The <code><i>host</i></code> component
23999 can be a host name or an IP address. If <code><i>instance</i></code>
24000 is not specified, then the default SQL Server instance is assumed.
24001 If port is not specified, then the default SQL Server port is
24002 used (1433). Note that you would normally specify either the
24003 instance name or the port, but not both. If both are specified,
24004 then the instance name is ignored by the SQL Server Native Client
24005 ODBC driver. For more information on the format of the SQL
24006 Server address, refer to the SQL Server Native Client ODBC
24007 driver documentation.</p>
24008
24009 <p>The second and third constructors allow us to specify all these address
24010 components (protocol, host, instance, and port) as separate
24011 arguments. The third constructor always connects using TCP/IP
24012 to the specified host and port.</p>
24013
24014 <p>The <code>driver</code> argument specifies the SQL Server Native
24015 Client ODBC driver that should be used to connect to the database.
24016 If not specified, then the latest available version is used. The
24017 following examples show common ways of connecting to the database
24018 using the first three constructors:</p>
24019
24020 <pre class="cxx">
24021 // Connect to the default SQL Server instance on the local machine
24022 // using the default protocol. Login as 'test' with password 'secret'
24023 // and open the 'example_db' database.
24024 //
24025 odb::mssql::database db1 ("test",
24026 "secret",
24027 "example_db");
24028
24029 // As above except use Windows authentication and open the default
24030 // database for this user.
24031 //
24032 odb::mssql::database db2 ("",
24033 "",
24034 "");
24035
24036 // Connect to the default SQL Server instance on 'onega' using the
24037 // default protocol. Login as 'test' with password 'secret' and open
24038 // the 'example_db' database.
24039 //
24040 odb::mssql::database db3 ("test",
24041 "secret",
24042 "example_db"
24043 "onega");
24044
24045 // As above but connect to the 'production' SQL Server instance.
24046 //
24047 odb::mssql::database db4 ("test",
24048 "secret",
24049 "example_db"
24050 "onega\\production");
24051
24052 // Same as above but specify protocol, host, and instance as separate
24053 // arguments.
24054 //
24055 odb::mssql::database db5 ("test",
24056 "secret",
24057 "example_db",
24058 odb::mssql::protocol_auto,
24059 "onega",
24060 "production");
24061
24062 // As above, but use TCP/IP as the protocol.
24063 //
24064 odb::mssql::database db6 ("test",
24065 "secret",
24066 "example_db"
24067 "tcp:onega\\production");
24068
24069 // Same as above but using separate arguments.
24070 //
24071 odb::mssql::database db7 ("test",
24072 "secret",
24073 "example_db",
24074 odb::mssql::protocol_tcp,
24075 "onega",
24076 "production");
24077
24078 // As above, but use TCP/IP port instead of the instance name.
24079 //
24080 odb::mssql::database db8 ("test",
24081 "secret",
24082 "example_db"
24083 "tcp:onega,1435");
24084
24085 // Same as above but using separate arguments. Note that here we
24086 // don't need to specify protocol explicitly since it can only
24087 // be TCP/IP.
24088 //
24089 odb::mssql::database db9 ("test",
24090 "secret",
24091 "example_db",
24092 "onega",
24093 1435);
24094
24095 // As above but use the specific SQL Server Native Client ODBC
24096 // driver version.
24097 //
24098 odb::mssql::database dbA ("test",
24099 "secret",
24100 "example_db"
24101 "tcp:onega,1435",
24102 "SQL Server Native Client 10.0");
24103 </pre>
24104
24105
24106 <p>The fourth constructor allows us to pass a custom ODBC connection
24107 string that provides all the information necessary to connect to
24108 the database. Note also that all the other constructors have the
24109 <code>extra_connect_string</code> argument which can be used to
24110 specify additional ODBC connection attributes. For more information
24111 on the format of the ODBC connection string, refer to the SQL
24112 Server Native Client ODBC driver documentation.</p>
24113
24114 <p>The last constructor extracts the database parameters
24115 from the command line. The following options are recognized:</p>
24116
24117 <pre class="terminal">
24118 --user | -U &lt;login>
24119 --password | -P &lt;password>
24120 --database | -d &lt;name>
24121 --server | -S &lt;address>
24122 --driver &lt;name>
24123 --options-file &lt;file>
24124 </pre>
24125
24126 <p>The <code>--options-file</code> option allows us to specify some
24127 or all of the database options in a file with each option appearing
24128 on a separate line followed by a space and an option value.</p>
24129
24130 <p>If the <code>erase</code> argument to this constructor is true,
24131 then the above options are removed from the <code>argv</code>
24132 array and the <code>argc</code> count is updated accordingly.
24133 This is primarily useful if your application accepts other
24134 options or arguments and you would like to get the SQL Server
24135 options out of the <code>argv</code> array.</p>
24136
24137 <p>This constructor throws the <code>odb::mssql::cli_exception</code>
24138 exception if the SQL Server option values are missing or invalid. See
24139 section <a href="#21.4">Section 21.4, "SQL Server Exceptions"</a> for
24140 more information on this exception.</p>
24141
24142 <p>The static <code>print_usage()</code> function prints the list of options
24143 with short descriptions that are recognized by this constructor.</p>
24144
24145 <p>Additionally, all the constructors have the <code>transaction_isolation</code>
24146 and <code>environment</code> arguments. The <code>transaction_isolation</code>
24147 argument allows us to specify an alternative transaction isolation level
24148 that should be used by all the connections created by this database instance.
24149 The <code>environment</code> argument allows us to provide a custom ODBC
24150 environment handle. If this argument is not <code>NULL</code>, then the
24151 passed handle is used in all the ODBC function calls made by this
24152 <code>database</code> instance. Note also that the <code>database</code>
24153 instance does not assume ownership of the passed environment handle and
24154 this handle should be valid for the lifetime of the <code>database</code>
24155 instance.</p>
24156
24157 <p>The last argument to all of the constructors is a pointer to the
24158 connection factory. In C++98/03, it is <code>std::auto_ptr</code> while
24159 in C++11 <code>std::unique_ptr</code> is used instead. If we pass a
24160 non-<code>NULL</code> value, the database instance assumes ownership
24161 of the factory instance. The connection factory interface as well as
24162 the available implementations are described in the next section.</p>
24163
24164 <p>The set of accessor functions following the constructors allows us
24165 to query the parameters of the <code>database</code> instance.</p>
24166
24167 <p>The <code>connection()</code> function returns a pointer to the
24168 SQL Server database connection encapsulated by the
24169 <code>odb::mssql::connection</code> class. For more information
24170 on <code>mssql::connection</code>, refer to <a href="#21.3">Section
24171 21.3, "SQL Server Connection and Connection Factory"</a>.</p>
24172
24173 <h2><a name="21.3">21.3 SQL Server Connection and Connection Factory</a></h2>
24174
24175 <p>The <code>mssql::connection</code> class has the following interface:</p>
24176
24177 <pre class="cxx">
24178 namespace odb
24179 {
24180 namespace mssql
24181 {
24182 class connection: public odb::connection
24183 {
24184 public:
24185 connection (database&amp;);
24186 connection (database&amp;, SQLHDBC handle);
24187
24188 SQLHDBC
24189 handle ();
24190
24191 details::buffer&amp;
24192 long_data_buffer ();
24193 };
24194
24195 typedef details::shared_ptr&lt;connection> connection_ptr;
24196 }
24197 }
24198 </pre>
24199
24200 <p>For more information on the <code>odb::connection</code> interface, refer
24201 to <a href="#3.6">Section 3.6, "Connections"</a>. The first overloaded
24202 <code>mssql::connection</code> constructor creates a new ODBC connection.
24203 The created connection is configured to use the manual commit mode with
24204 multiple active result sets (MARS) enabled. The second constructor allows
24205 us to create a <code>connection</code> instance by providing an already
24206 established ODBC connection. Note that the <code>connection</code>
24207 instance assumes ownership of this handle. The <code>handle()</code>
24208 accessor returns the underlying ODBC connection handle associated with
24209 the <code>connection</code> instance.</p>
24210
24211 <p>Additionally, each <code>connection</code> instance maintains a long
24212 data buffer. This buffer is used by the SQL Server ODB runtime
24213 as an intermediate storage for piecewise handling of long data.
24214 By default, the long data buffer has zero initial capacity and is
24215 expanded to 4096 bytes when the first long data operation is performed.
24216 If your application requires a bigger or smaller long data buffer,
24217 you can specify a custom capacity using the <code>long_data_buffer()</code>
24218 accessor.</p>
24219
24220 <p>The <code>mssql::connection_factory</code> abstract class has the
24221 following interface:</p>
24222
24223 <pre class="cxx">
24224 namespace odb
24225 {
24226 namespace mssql
24227 {
24228 class connection_factory
24229 {
24230 public:
24231 virtual void
24232 database (database&amp;) = 0;
24233
24234 virtual connection_ptr
24235 connect () = 0;
24236 };
24237 }
24238 }
24239 </pre>
24240
24241 <p>The <code>database()</code> function is called when a connection
24242 factory is associated with a database instance. This happens in
24243 the <code>odb::mssql::database</code> class constructors. The
24244 <code>connect()</code> function is called whenever a database
24245 connection is requested.</p>
24246
24247 <p>The two implementations of the <code>connection_factory</code>
24248 interface provided by the SQL Server ODB runtime are
24249 <code>new_connection_factory</code> and
24250 <code>connection_pool_factory</code>. You will need to include
24251 the <code>&lt;odb/mssql/connection-factory.hxx></code>
24252 header file to make the <code>connection_factory</code> interface
24253 and these implementation classes available in your application.</p>
24254
24255 <p>The <code>new_connection_factory</code> class creates a new
24256 connection whenever one is requested. When a connection is no
24257 longer needed, it is released and closed. The
24258 <code>new_connection_factory</code> class has the following
24259 interface:</p>
24260
24261 <pre class="cxx">
24262 namespace odb
24263 {
24264 namespace mssql
24265 {
24266 class new_connection_factory: public connection_factory
24267 {
24268 public:
24269 new_connection_factory ();
24270 };
24271 };
24272 </pre>
24273
24274 <p>The <code>connection_pool_factory</code> class implements a
24275 connection pool. It has the following interface:</p>
24276
24277 <pre class="cxx">
24278 namespace odb
24279 {
24280 namespace mssql
24281 {
24282 class connection_pool_factory: public connection_factory
24283 {
24284 public:
24285 connection_pool_factory (std::size_t max_connections = 0,
24286 std::size_t min_connections = 0);
24287
24288 protected:
24289 class pooled_connection: public connection
24290 {
24291 public:
24292 pooled_connection (database_type&amp;);
24293 pooled_connection (database_type&amp;, SQLHDBC handle);
24294 };
24295
24296 typedef details::shared_ptr&lt;pooled_connection> pooled_connection_ptr;
24297
24298 virtual pooled_connection_ptr
24299 create ();
24300 };
24301 };
24302 </pre>
24303
24304 <p>The <code>max_connections</code> argument in the
24305 <code>connection_pool_factory</code> constructor specifies the maximum
24306 number of concurrent connections that this pool factory will
24307 maintain. Similarly, the <code>min_connections</code> argument
24308 specifies the minimum number of available connections that
24309 should be kept open.</p>
24310
24311 <p>Whenever a connection is requested, the pool factory first
24312 checks if there is an unused connection that can be returned.
24313 If there is none, the pool factory checks the
24314 <code>max_connections</code> value to see if a new connection
24315 can be created. If the total number of connections maintained
24316 by the pool is less than this value, then a new connection is
24317 created and returned. Otherwise, the caller is blocked until
24318 a connection becomes available.</p>
24319
24320 <p>When a connection is released, the pool factory first checks
24321 if there are blocked callers waiting for a connection. If so, then
24322 one of them is unblocked and is given the connection. Otherwise,
24323 the pool factory checks whether the total number of connections
24324 maintained by the pool is greater than the <code>min_connections</code>
24325 value. If that's the case, the connection is closed. Otherwise, the
24326 connection is added to the pool of available connections to be
24327 returned on the next request. In other words, if the number of
24328 connections maintained by the pool exceeds <code>min_connections</code>
24329 and there are no callers waiting for a new connection,
24330 the pool will close the excess connections.</p>
24331
24332 <p>If the <code>max_connections</code> value is 0, then the pool will
24333 create a new connection whenever all of the existing connections
24334 are in use. If the <code>min_connections</code> value is 0, then
24335 the pool will never close a connection and instead maintain all
24336 the connections that were ever created.</p>
24337
24338 <p>The <code>create()</code> virtual function is called whenever the
24339 pool needs to create a new connection. By deriving from the
24340 <code>connection_pool_factory</code> class and overriding this
24341 function we can implement custom connection establishment
24342 and configuration.</p>
24343
24344 <p>If you pass <code>NULL</code> as the connection factory to one of the
24345 <code>database</code> constructors, then the
24346 <code>connection_pool_factory</code> instance will be created by default
24347 with the min and max connections values set to <code>0</code>. The
24348 following code fragment shows how we can pass our own connection factory
24349 instance:</p>
24350
24351 <pre class="cxx">
24352 #include &lt;odb/database.hxx>
24353
24354 #include &lt;odb/mssql/database.hxx>
24355 #include &lt;odb/mssql/connection-factory.hxx>
24356
24357 int
24358 main (int argc, char* argv[])
24359 {
24360 auto_ptr&lt;odb::mssql::connection_factory> f (
24361 new odb::mssql::connection_pool_factory (20));
24362
24363 auto_ptr&lt;odb::database> db (
24364 new mssql::database (argc, argv, false, "", 0, f));
24365 }
24366 </pre>
24367
24368 <h2><a name="21.4">21.4 SQL Server Exceptions</a></h2>
24369
24370 <p>The SQL Server ODB runtime library defines the following
24371 SQL Server-specific exceptions:</p>
24372
24373 <pre class="cxx">
24374 namespace odb
24375 {
24376 namespace mssql
24377 {
24378 class database_exception: odb::database_exception
24379 {
24380 public:
24381 class record
24382 {
24383 public:
24384 SQLINTEGER
24385 error () const;
24386
24387 const std::string&amp;
24388 sqlstate () const;
24389
24390 const std::string&amp;
24391 message () const;
24392 };
24393
24394 typedef std::vector&lt;record> records;
24395
24396 typedef records::size_type size_type;
24397 typedef records::const_iterator iterator;
24398
24399 iterator
24400 begin () const;
24401
24402 iterator
24403 end () const;
24404
24405 size_type
24406 size () const;
24407
24408 virtual const char*
24409 what () const throw ();
24410 };
24411
24412 class cli_exception: odb::exception
24413 {
24414 public:
24415 virtual const char*
24416 what () const throw ();
24417 };
24418
24419 class long_data_reload: odb::exception
24420 {
24421 public:
24422 virtual const char*
24423 what () const throw ();
24424 };
24425 }
24426 }
24427 </pre>
24428
24429 <p>You will need to include the <code>&lt;odb/mssql/exceptions.hxx></code>
24430 header file to make these exceptions available in your application.</p>
24431
24432 <p>The <code>odb::mssql::database_exception</code> is thrown if
24433 an SQL Server database operation fails. The SQL Server-specific error
24434 information is stored as a series of records, each containing
24435 the error code as a signed 4-byte integer, the SQLSTATE code,
24436 and the message string. All this information is also combined
24437 and returned in a human-readable form by the <code>what()</code>
24438 function.</p>
24439
24440 <p>The <code>odb::mssql::cli_exception</code> is thrown by the
24441 command line parsing constructor of the <code>odb::mssql::database</code>
24442 class if the SQL Server option values are missing or invalid. The
24443 <code>what()</code> function returns a human-readable description
24444 of an error.</p>
24445
24446 <p>The <code>odb::mssql::long_data_reload</code> is thrown if an
24447 attempt is made to re-load an object or view with long data as
24448 part of a query result iteration. For more information, refer
24449 to <a href="#21.1">Section 21.1, "SQL Server Type Mapping"</a>.</p>
24450
24451 <h2><a name="21.5">21.5 SQL Server Limitations</a></h2>
24452
24453 <p>The following sections describe SQL Server-specific limitations imposed
24454 by the current SQL Server and ODB runtime versions.</p>
24455
24456 <h3><a name="21.5.1">21.5.1 Query Result Caching</a></h3>
24457
24458 <p>SQL Server ODB runtime implementation does not perform query result
24459 caching (<a href="#4.4">Section 4.4, "Query Result"</a>) even when
24460 explicitly requested. The ODBC API and the SQL Server Native Client ODBC
24461 driver support interleaving execution of multiple prepared statements
24462 on a single connection. As a result, it is possible to have multiple
24463 uncached results and calls to other database functions do not invalidate
24464 them. The only limitation of the uncached SQL Server results is the
24465 unavailability of the <code>result::size()</code> function. If you
24466 call this function on an SQL Server query result, then the
24467 <code>odb::result_not_cached</code> exception (<a href="#3.14">Section
24468 3.14, "ODB Exceptions"</a>) is always thrown. Future versions of the
24469 SQL Server ODB runtime library may add support for result caching.</p>
24470
24471 <h3><a name="21.5.2">21.5.2 Foreign Key Constraints</a></h3>
24472
24473 <p>ODB assumes the standard SQL behavior which requires that foreign
24474 key constraints checking is deferred until the transaction is
24475 committed. The only behavior supported by SQL Server is to check
24476 such constraints immediately. As a result, by default, schemas
24477 generated by the ODB compiler for SQL Server have foreign key
24478 definitions commented out. They are retained only for documentation.</p>
24479
24480 <p>You can override the default behavior and instruct the ODB
24481 compiler to generate non-deferrable foreign keys by specifying
24482 the <code>--fkeys-deferrable-mode not_deferrable</code> ODB
24483 compiler option. Note, however, that in this case the order in
24484 which you persist, update, and erase objects within a transaction
24485 becomes important.</p>
24486
24487 <h3><a name="21.5.3">21.5.3 Unique Constraint Violations</a></h3>
24488
24489 <p>Due to the granularity of the ODBC error codes, it is impossible
24490 to distinguish between the duplicate primary key and other unique
24491 constraint violations. As a result, when making an object persistent,
24492 the SQL Server ODB runtime will translate all unique constraint violation
24493 errors to the <code>object_already_persistent</code> exception
24494 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>).</p>
24495
24496 <h3><a name="21.5.4">21.5.4 Multi-threaded Windows Applications</a></h3>
24497
24498 <p>Multi-threaded Windows applications must use the
24499 <code>_beginthread()</code>/<code>_beginthreadex()</code> and
24500 <code>_endthread()</code>/<code>_endthreadex()</code> CRT functions
24501 instead of the <code>CreateThread()</code> and <code>EndThread()</code>
24502 Win32 functions to start and terminate threads. This is a limitation of
24503 the ODBC implementation on Windows.</p>
24504
24505 <h3><a name="21.5.5">21.5.5 Affected Row Count and DDL Statements</a></h3>
24506
24507 <p>SQL Server always returns zero as the number of affected rows
24508 for DDL statements. In particular, this means that the
24509 <code>database::execute()</code> (<a href="#3.12">Section 3.12,
24510 "Executing Native SQL Statements"</a>) function will always
24511 return zero for such statements.</p>
24512
24513 <h3><a name="21.5.6">21.5.6 Long Data and Auto Object Ids, <code>ROWVERSION</code></a></h3>
24514
24515 <p>SQL Server 2005 has a bug that causes it to fail on an <code>INSERT</code>
24516 or <code>UPDATE</code> statement with the <code>OUTPUT</code> clause
24517 (used to return automatically assigned object ids as well as
24518 <code>ROWVERSION</code> values) if one of the inserted columns
24519 is long data. The symptom of this bug in ODB is an exception thrown
24520 by the <code>database::persist()</code> or <code>database::update()</code>
24521 function when used on an object that contains long data and has an
24522 automatically assigned object id or uses <code>ROWVERSION</code>-based
24523 optimistic concurrency (<a href="#21.1.1">Section 21.1.1,
24524 "<code>ROWVERSION</code> Support"</a>). The error message reads "This
24525 operation conflicts with another pending operation on this transaction.
24526 The operation failed."</p>
24527
24528 <p>For automatically assigned object ids ODB includes a workaround for
24529 this bug which uses a less efficient method to obtain id values for
24530 objects that contain long data. To enable this workaround you need
24531 to specify that the generated code will be used with SQL Server 2005
24532 or later by passing the <code>--mssql-server-version&nbsp;9.0</code>
24533 ODB compiler option.</p>
24534
24535 <p>For <code>ROWVERSION</code>-based optimistic concurrency no workaround
24536 is currently provided. The ODB compiler will issue an error for
24537 objects that use <code>ROWVERSION</code> for optimistic concurrency
24538 and containing long data.</p>
24539
24540 <h3><a name="21.5.7">21.5.7 Long Data and By-Value Accessors/Modifiers</a></h3>
24541
24542 <p>As discussed in <a href="#14.4.5">Section 14.4.5,
24543 "<code>get</code>/<code>set</code>/<code>access</code>"</a>, by-value
24544 accessor and modifier expressions cannot be used with data members
24545 of long data types. The SQL Server ODB runtime uses streaming for
24546 reading/writing long data directly from/to data members. As a result,
24547 by-reference accessors and modifiers should be used for these data
24548 types.</p>
24549
24550 <h3><a name="21.5.8">21.5.8 Bulk Update and <code>ROWVERSION</code></a></h3>
24551
24552 <p>The bulk update operation (<a href="#15.3">Section 15.3, "Bulk Database
24553 Operations"</a>) is not yet supported for persistent classes that use
24554 <code>ROWVERSION</code>-based optimistic concurrency. For such classes
24555 the bulk <code>update()</code> function is not available. The bulk
24556 persist and erase support is still provided.</p>
24557
24558 <h2><a name="21.6">21.6 SQL Server Index Definitions</a></h2>
24559
24560 <p>When the <code>index</code> pragma (<a href="#14.7">Section 14.7,
24561 "Index Definition Pragmas"</a>) is used to define an SQL Server index,
24562 the <code>type</code> clause specifies the index type (for example,
24563 <code>UNIQUE</code>, <code>CLUSTERED</code>), the <code>method</code>
24564 clause is not used, and the <code>options</code> clause specifies
24565 additional index properties. The column options can be used to specify
24566 the sort order. For example:</p>
24567
24568 <pre class="cxx">
24569 #pragma db object
24570 class object
24571 {
24572 ...
24573
24574 std::string name_;
24575
24576 #pragma db index \
24577 type("UNIQUE CLUSTERED") \
24578 member(name_, "DESC") \
24579 options("WITH(FILLFACTOR = 80)")
24580 };
24581 </pre>
24582
24583 <h2><a name="21.7">21.7 SQL Server Stored Procedures</a></h2>
24584
24585 <p>ODB native views (<a href="#10.6">Section 10.6, "Native Views"</a>)
24586 can be used to call SQL Server stored procedures. For example, assuming
24587 we are using the <code>person</code> class from <a href="#2">Chapter
24588 2, "Hello World Example"</a> (and the corresponding <code>person</code>
24589 table), we can create a stored procedure that given the min and max
24590 ages returns some information about all the people in that range:</p>
24591
24592 <pre class="sql">
24593 CREATE PROCEDURE dbo.person_range (
24594 @min_age SMALLINT,
24595 @max_age SMALLINT)
24596 AS
24597 SELECT age, first, last FROM person
24598 WHERE age >= @min_age AND age &lt;= @max_age;
24599 </pre>
24600
24601 <p>Given the above stored procedure we can then define an ODB view
24602 that can be used to call it and retrieve its result:</p>
24603
24604 <pre class="cxx">
24605 #pragma db view query("EXEC person_range (?)")
24606 struct person_range
24607 {
24608 unsigned short age;
24609 std::string first;
24610 std::string last;
24611 };
24612 </pre>
24613
24614 <p>The following example shows how we can use the above view to
24615 print the list of people in a specific age range:</p>
24616
24617 <pre class="cxx">
24618 typedef odb::query&lt;person_range> query;
24619 typedef odb::result&lt;person_range> result;
24620
24621 transaction t (db.begin ());
24622
24623 result r (
24624 db.query&lt;person_range> (
24625 query::_val (1) + "," + query::_val (18)));
24626
24627 for (result::iterator i (r.begin ()); i != r.end (); ++i)
24628 cerr &lt;&lt; i->first &lt;&lt; " " &lt;&lt; i->last &lt;&lt; " " &lt;&lt; i->age &lt;&lt; endl;
24629
24630 t.commit ();
24631 </pre>
24632
24633 <p>Note that as with all native views, the order and types of data members
24634 must match those of columns in the <code>SELECT</code> list inside
24635 the stored procedure.</p>
24636
24637 <p>There are also a number of limitations when it comes to calling
24638 SQL Server stored procedures with ODB views. There is currently
24639 no support for output parameters, however, this is planned for
24640 a future version. In the meantime, to call a stored procedure
24641 that has output parameters we have to use a wrapper procedure
24642 that converts such parameters to a <code>SELECT</code>
24643 result. For example, given the following procedure that
24644 calculates the age range of the people in our database:</p>
24645
24646 <pre class="sql">
24647 CREATE PROCEDURE dbo.person_age_range (
24648 @min_age SMALLINT = NULL OUTPUT,
24649 @max_age SMALLINT = NULL OUTPUT)
24650 AS
24651 SELECT @min_age = MIN(age), @max_age = MAX(max) FROM person;
24652 </pre>
24653
24654 <p>We can create a wrapper procedure like this:</p>
24655
24656 <pre class="sql">
24657 CREATE PROCEDURE dbo.person_age_range_odb
24658 AS
24659 DECLARE @min_age SMALLINT, @max_age SMALLINT;
24660 EXEC person_age_range @min_age OUTPUT, @max_age OUTPUT;
24661 SELECT @min_age, @max_age;
24662 </pre>
24663
24664 <p>And a view like this:</p>
24665
24666 <pre class="cxx">
24667 #pragma db view query("EXEC person_age_range_odb")
24668 struct person_age_range
24669 {
24670 unsigned short min_age;
24671 unsigned short max_age;
24672 };
24673 </pre>
24674
24675 <p>Which we can then use to call the stored procedure:</p>
24676
24677 <pre class="cxx">
24678 transaction t (db.begin ());
24679
24680 person_age_range ar (db.query_value&lt;person_age_range> ());
24681 cerr &lt;&lt; ar.min_age &lt;&lt; " " &lt;&lt; ar.max_age &lt;&lt; endl;
24682
24683 t.commit ();
24684 </pre>
24685
24686 <p>In SQL Server, a stored procedure can produce multiple results.
24687 For example, if a stored procedure executes several
24688 <code>SELECT</code> statements, then the result of calling such
24689 a procedure consists of two row sets, one for each <code>SELECT</code>
24690 statement. Because such multiple row sets can contain varying number
24691 and type of columns, they cannot be all extracted into a
24692 single view. Consequently, these kind of stored procedures are
24693 currently not supported.</p>
24694
24695 <p>A stored procedure may also produce no row sets at all. For
24696 example, a stored procedure that only executes DML statements
24697 would exhibit this behavior. To call such a procedure we use
24698 an empty view, for example:</p>
24699
24700 <pre class="sql">
24701 CREATE PROCEDURE dbo.insert_person (
24702 @first VARCHAR(512),
24703 @last VARCHAR(512),
24704 @age SMALLINT)
24705 AS
24706 INSERT INTO person(first, last, age)
24707 VALUES(@first, @last, @age);
24708 </pre>
24709
24710 <pre class="cxx">
24711 #pragma db view
24712 struct no_result {};
24713
24714 transaction t (db.begin ());
24715
24716 db.query_one&lt;no_result> (
24717 "EXEC insert_person" +
24718 query::_val ("John") + "," +
24719 query::_val ("Doe") + "," +
24720 query::_val (21));
24721
24722 t.commit ();
24723 </pre>
24724
24725 <p>Finally, an SQL Server stored procedure can also return an
24726 integer status code. Similar to output parameters, this code
24727 can only be observed by an ODB view if it is converted to a
24728 <code>SELECT</code> result. For more information on how to
24729 do this and for other examples of stored procedure calls,
24730 refer to the <code>mssql/stored-proc</code> test in the
24731 <code>odb-tests</code> package.</p>
24732
24733 <!-- PART -->
24734
24735
24736 <hr class="page-break"/>
24737 <h1><a name="III">PART III&nbsp;&nbsp;
24738 <span style="font-weight: normal;">PROFILES</span></a></h1>
24739
24740 <p>Part III covers the integration of ODB with popular C++ frameworks
24741 and libraries. It consists of the following chapters.</p>
24742
24743 <table class="toc">
24744 <tr><th>22</th><td><a href="#22">Profiles Introduction</a></td></tr>
24745 <tr><th>23</th><td><a href="#23">Boost Profile</a></td></tr>
24746 <tr><th>24</th><td><a href="#24">Qt Profile</a></td></tr>
24747 </table>
24748
24749
24750 <!-- CHAPTER -->
24751
24752
24753 <hr class="page-break"/>
24754 <h1><a name="22">22 Profiles Introduction</a></h1>
24755
24756 <p>ODB profiles are a generic mechanism for integrating ODB with
24757 widely-used C++ frameworks and libraries. A profile provides glue
24758 code which allows you to seamlessly persist various components, such
24759 as smart pointers, containers, and value types found in these
24760 frameworks or libraries. The code necessary to implement a profile
24761 is packaged into the so called profile library. For example, the
24762 Boost profile implementation is provided by the <code>libodb-boost</code>
24763 profile library.</p>
24764
24765 <p>Besides linking the profile library to our application, it is also
24766 necessary to let the ODB compiler know which profiles we
24767 are using. This is accomplished with the <code>--profile</code>
24768 (or <code>-p</code> alias) option. For example:</p>
24769
24770 <pre class="terminal">
24771 odb --profile boost ...
24772 </pre>
24773
24774 <p>Some profiles, especially those covering frameworks or libraries that
24775 consist of multiple sub-libraries, provide sub-profiles that allow you
24776 to pick and choose which components you would like to use in your
24777 application. For example, the <code>boost</code> profile contains
24778 the <code>boost/data-time</code> sub-profile. If we are only
24779 interested in the <code>date_time</code> types, then we can
24780 pass <code>boost/data-time</code> instead of <code>boost</code>
24781 to the <code>--profile</code> option, for example:</p>
24782
24783 <pre class="terminal">
24784 odb --profile boost/date-time ...
24785 </pre>
24786
24787 <p>To summarize, you will need to perform the following steps in order
24788 to make use of a profile in your application:</p>
24789
24790 <ol>
24791 <li>ODB compiler: if necessary, specify the path to the profile library
24792 headers (<code>-I</code> option).</li>
24793 <li>ODB compiler: specify the profile you would like to use with
24794 the <code>--profile</code> option.</li>
24795 <li>C++ compiler: if necessary, specify the path to the profile library
24796 headers (normally <code>-I</code> option).</li>
24797 <li>Linker: link the profile library to the application.</li>
24798 </ol>
24799
24800 <p>The remaining chapters in this part of the manual describe the
24801 standard profiles provided by ODB.</p>
24802
24803
24804 <!-- CHAPTER -->
24805
24806
24807 <hr class="page-break"/>
24808 <h1><a name="23">23 Boost Profile</a></h1>
24809
24810 <p>The ODB profile implementation for Boost is provided by the
24811 <code>libodb-boost</code> library and consists of multiple sub-profiles
24812 corresponding to the individual Boost libraries. To enable all the
24813 available Boost sub-profiles, pass <code>boost</code> as the profile
24814 name to the <code>--profile</code> ODB compiler option. Alternatively,
24815 you can enable only specific sub-profiles by passing individual
24816 sub-profile names to <code>--profile</code>. The following sections in
24817 this chapter discuss each Boost sub-profile in detail. The
24818 <code>boost</code> example in the <code>odb-examples</code>
24819 package shows how to enable and use the Boost profile.</p>
24820
24821 <p>Some sub-profiles may throw exceptions to indicate error conditions,
24822 such as the inability to store a specific value in a particular database
24823 system. All such exceptions derive from the
24824 <code>odb::boost::exception</code> class which in turn derives from
24825 the root of the ODB exception hierarchy, class <code>odb::exception</code>
24826 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>). The
24827 <code>odb::boost::exception</code> class is defined in the
24828 <code>&lt;odb/boost/exception.hxx></code> header file and has the
24829 same interface as <code>odb::exception</code>. Concrete exceptions
24830 that can be thrown by the Boost sub-profiles are described in the
24831 following sections.</p>
24832
24833 <h2><a name="23.1">23.1 Smart Pointers Library</a></h2>
24834
24835 <p>The <code>smart-ptr</code> sub-profile provides persistence
24836 support for a subset of smart pointers from the Boost
24837 <code>smart_ptr</code> library. To enable only this profile,
24838 pass <code>boost/smart-ptr</code> to the <code>--profile</code>
24839 ODB compiler option.</p>
24840
24841 <p>The currently supported smart pointers are
24842 <code>boost::shared_ptr</code> and <code>boost::weak_ptr</code>. For
24843 more information on using smart pointers as pointers to objects and
24844 views, refer to <a href="#3.3">Section 3.3, "Object and View Pointers"</a>
24845 and <a href="#6">Chapter 6, "Relationships"</a>. For more information
24846 on using smart pointers as pointers to values, refer to
24847 <a href="#7.3">Section 7.3, "Pointers and <code>NULL</code> Value
24848 Semantics"</a>. When used as a pointer to a value, only
24849 <code>boost::shared_ptr</code> is supported. For example:</p>
24850
24851 <pre class="cxx">
24852 #pragma db object
24853 class person
24854 {
24855 ...
24856
24857 #pragma db null
24858 boost::shared_ptr&lt;std::string> middle_name_;
24859 };
24860 </pre>
24861
24862 <p>To provide finer grained control over object relationship loading,
24863 the <code>smart-ptr</code> sub-profile also provides the lazy
24864 counterparts for the above pointers: <code>odb::boost::lazy_shared_ptr</code> and
24865 <code>odb::boost::lazy_weak_ptr</code>. You will need to include the
24866 <code>&lt;odb/boost/lazy-ptr.hxx></code> header file to make the lazy
24867 variants available in your application. For a description of the lazy
24868 pointer interface and semantics refer to <a href="#6.4">Section 6.4,
24869 "Lazy Pointers"</a>. The following example shows how we can use these
24870 smart pointers to establish a relationship between persistent objects.</p>
24871
24872 <pre class="cxx">
24873 class employee;
24874
24875 #pragma db object
24876 class position
24877 {
24878 ...
24879
24880 #pragma db inverse(position_)
24881 odb::boost::lazy_weak_ptr&lt;employee> employee_;
24882 };
24883
24884 #pragma db object
24885 class employee
24886 {
24887 ...
24888
24889 #pragma db not_null
24890 boost::shared_ptr&lt;position> position_;
24891 };
24892 </pre>
24893
24894 <p>Besides providing persistence support for the above smart pointers,
24895 the <code>smart-ptr</code> sub-profile also changes the default
24896 pointer (<a href="#3.3">Section 3.3, "Object and View Pointers"</a>)
24897 to <code>boost::shared_ptr</code>. In particular, this means that
24898 database functions that return dynamically allocated objects and views
24899 will return them as <code>boost::shared_ptr</code> pointers. To override
24900 this behavior, add the <code>--default-pointer</code> option specifying
24901 the alternative pointer type after the <code>--profile</code> option.</p>
24902
24903 <h2><a name="23.2">23.2 Unordered Containers Library</a></h2>
24904
24905 <p>The <code>unordered</code> sub-profile provides persistence support for
24906 the containers from the Boost <code>unordered</code> library. To enable
24907 only this profile, pass <code>boost/unordered</code> to
24908 the <code>--profile</code> ODB compiler option.</p>
24909
24910 <p>The supported containers are <code>boost::unordered_set</code>,
24911 <code>boost::unordered_map</code>, <code>boost::unordered_multiset</code>,
24912 and <code>boost::unordered_multimap</code>. For more information on using
24913 the set and multiset containers with ODB, refer to <a href="#5.2">Section
24914 5.2, "Set and Multiset Containers"</a>. For more information on using the
24915 map and multimap containers with ODB, refer to <a href="#5.3"> Section
24916 5.3, "Map and Multimap Containers"</a>. The following example shows how
24917 the <code>unordered_set</code> container may be used within a persistent
24918 object.</p>
24919
24920 <pre class="cxx">
24921 #pragma db object
24922 class person
24923 {
24924 ...
24925 boost::unordered_set&lt;std::string&gt; emails_;
24926 };
24927 </pre>
24928
24929 <h2><a name="23.3">23.3 Multi-Index Container Library</a></h2>
24930
24931 <p>The <code>multi-index</code> sub-profile provides persistence support for
24932 <code>boost::multi_index_container</code> from the Boost Multi-Index
24933 library. To enable only this profile, pass <code>boost/multi-index</code>
24934 to the <code>--profile</code> ODB compiler option. The following example
24935 shows how <code>multi_index_container</code> may be used within a
24936 persistent object.</p>
24937
24938 <pre class="cxx">
24939 namespace mi = boost::multi_index;
24940
24941 #pragma db object
24942 class person
24943 {
24944 ...
24945
24946 typedef
24947 mi::multi_index_container&lt;
24948 std::string,
24949 mi::indexed_by&lt;
24950 mi::sequenced&lt;>,
24951 mi::ordered_unique&lt;mi::identity&lt;std::string> >
24952 >
24953 > emails;
24954
24955 emails emails_;
24956 };
24957 </pre>
24958
24959 <p>Note that a <code>multi_index_container</code> instantiation is
24960 stored differently in the database depending on whether it has
24961 any <code>sequenced</code> or <code>random_access</code> indexes.
24962 If it does, then it is treated as an ordered container
24963 (<a href="#5.1">Section 5.1, "Ordered Containers"</a>) with the
24964 first such index establishing the order. Otherwise, it is treated
24965 as a set container (<a href="#5.2">Section 5.2, "Set and Multiset
24966 Containers"</a>).</p>
24967
24968 <p>Note also that there is a terminology clash between ODB and Boost
24969 Multi-Index. The ODB term <em>ordered container</em> translates
24970 to Multi-Index terms <em>sequenced index</em> and <em>random access
24971 index</em> while the ODB term <em>set container</em> translates
24972 to Multi-Index terms <em>ordered index</em> and <em>hashed
24973 index</em>.</p>
24974
24975 <p>The <code>emails</code> container from the above example is stored
24976 as an ordered container. In contrast, the following <code>aliases</code>
24977 container is stored as a set.</p>
24978
24979 <pre class="cxx">
24980 namespace mi = boost::multi_index;
24981
24982 #pragma db value
24983 struct name
24984 {
24985 std::string first;
24986 std::string last;
24987 };
24988
24989 bool operator&lt; (const name&amp;, const name&amp;);
24990
24991 #pragma db object
24992 class person
24993 {
24994 ...
24995
24996 typedef
24997 mi::multi_index_container&lt;
24998 name,
24999 mi::indexed_by&lt;
25000 mi::ordered_unique&lt;mi::identity&lt;name> >
25001 mi::ordered_non_unique&lt;
25002 mi::member&lt;name, std::string, &amp;name::first>
25003 >,
25004 mi::ordered_non_unique&lt;
25005 mi::member&lt;name, std::string, &amp;name::last>
25006 >
25007 >
25008 > aliases;
25009
25010 aliases aliases_;
25011 };
25012 </pre>
25013
25014 <h2><a name="23.4">23.4 Optional Library</a></h2>
25015
25016 <p>The <code>optional</code> sub-profile provides persistence support for
25017 the <code>boost::optional</code> container from the Boost
25018 <code>optional</code> library. To enable only this profile, pass
25019 <code>boost/optional</code> to the <code>--profile</code> ODB compiler
25020 option.</p>
25021
25022 <p>In a relational database <code>boost::optional</code> is mapped to
25023 a column that can have a <code>NULL</code> value. Similar to
25024 <code>odb::nullable</code> (<a href="#7.3">Section 7.3, "Pointers and
25025 <code>NULL</code> Value Semantics"</a>), it can be used to add the
25026 <code>NULL</code> semantics to existing C++ types. For example:</p>
25027
25028 <pre class="cxx">
25029 #include &lt;boost/optional.hpp>
25030
25031 #pragma db object
25032 class person
25033 {
25034 ...
25035
25036 std::string first_; // TEXT NOT NULL
25037 boost::optional&lt;std::string> middle_; // TEXT NULL
25038 std::string last_; // TEXT NOT NULL
25039 };
25040 </pre>
25041
25042 <p>Note also that similar to <code>odb::nullable</code>, when
25043 this profile is used, the <code>NULL</code> values are automatically
25044 enabled for data members of the <code>boost::optional</code> type.</p>
25045
25046 <h2><a name="23.5">23.5 Date Time Library</a></h2>
25047
25048 <p>The <code>date-time</code> sub-profile provides persistence support for a
25049 subset of types from the Boost <code>date_time</code> library. It is
25050 further subdivided into two sub-profiles, <code>gregorian</code>
25051 and <code>posix_time</code>. The <code>gregorian</code> sub-profile
25052 provides support for types from the <code>boost::gregorian</code>
25053 namespace, while the <code>posix-time</code> sub-profile provides support
25054 for types from the <code>boost::posix_time</code> namespace. To enable
25055 the entire <code>date-time</code> sub-profile, pass
25056 <code>boost/date-time</code> to the <code>--profile</code> ODB compiler
25057 option. To enable only the <code>gregorian</code> sub-profile, pass
25058 <code>boost/date-time/gregorian</code>, and to enable only the
25059 <code>posix-time</code> sub-profile, pass
25060 <code>boost/date-time/posix-time</code>.</p>
25061
25062 <p>The only type that the <code>gregorian</code> sub-profile currently
25063 supports is <code>gregorian::date</code>. The types currently supported
25064 by the <code>posix-time</code> sub-profile are
25065 <code>posix_time::ptime</code> and
25066 <code>posix_time::time_duration</code>. The manner in which these types
25067 are persisted is database system dependent and is discussed in the
25068 sub-sections that follow. The example below shows how
25069 <code>gregorian::date</code> may be used within a persistent object.</p>
25070
25071 <pre class="cxx">
25072 #pragma db object
25073 class person
25074 {
25075 ...
25076 boost::gregorian::date date_of_birth_;
25077 };
25078 </pre>
25079
25080 <p>Concrete exceptions that can be thrown by the <code>date-time</code>
25081 sub-profile implementation are presented below.</p>
25082
25083
25084 <pre class="cxx">
25085 namespace odb
25086 {
25087 namespace boost
25088 {
25089 namespace date_time
25090 {
25091 struct special_value: odb::boost::exception
25092 {
25093 virtual const char*
25094 what () const throw ();
25095 };
25096
25097 struct value_out_of_range: odb::boost::exception
25098 {
25099 virtual const char*
25100 what () const throw ();
25101 };
25102 }
25103 }
25104 }
25105 </pre>
25106
25107 <p>You will need to include the
25108 <code>&lt;odb/boost/date-time/exceptions.hxx&gt;</code> header file to
25109 make these exceptions available in your application.</p>
25110
25111 <p>The <code>special_value</code> exception is thrown if an attempt is made
25112 to store a Boost date-time special value that cannot be represented in
25113 the target database. The <code>value_out_of_range</code> exception is
25114 thrown if an attempt is made to store a date-time value that is out of
25115 the target database range. The specific conditions under which these
25116 exceptions are thrown are database system dependent and are discussed in
25117 more detail in the following sub-sections.</p>
25118
25119 <h3><a name="23.5.1">23.5.1 MySQL Database Type Mapping</a></h3>
25120
25121 <p>The following table summarizes the default mapping between the currently
25122 supported Boost <code>date_time</code> types and the MySQL database
25123 types.</p>
25124
25125 <!-- border="1" is necessary for html2ps -->
25126 <table id="mapping" border="1">
25127 <tr>
25128 <th>Boost <code>date_time</code> Type</th>
25129 <th>MySQL Type</th>
25130 <th>Default <code>NULL</code> Semantics</th>
25131 </tr>
25132
25133 <tr>
25134 <td><code>gregorian::date</code></td>
25135 <td><code>DATE</code></td>
25136 <td><code>NULL</code></td>
25137 </tr>
25138
25139 <tr>
25140 <td><code>posix_time::ptime</code></td>
25141 <td><code>DATETIME</code></td>
25142 <td><code>NULL</code></td>
25143 </tr>
25144
25145 <tr>
25146 <td><code>posix_time::time_duration</code></td>
25147 <td><code>TIME</code></td>
25148 <td><code>NULL</code></td>
25149 </tr>
25150 </table>
25151
25152 <p>The Boost special value <code>date_time::not_a_date_time</code> is stored
25153 as a <code>NULL</code> value in a MySQL database.</p>
25154
25155 <p>The <code>posix-time</code> sub-profile implementation also provides
25156 support for mapping <code>posix_time::ptime</code> to the
25157 <code>TIMESTAMP</code> MySQL type. However, this mapping has to be
25158 explicitly requested using the <code>db&nbsp;type</code> pragma
25159 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), as shown in
25160 the following example:</p>
25161
25162 <pre class="cxx">
25163 #pragma db object
25164 class person
25165 {
25166 ...
25167 #pragma db type("TIMESTAMP") not_null
25168 boost::posix_time::ptime updated_;
25169 };
25170 </pre>
25171
25172 <p>Starting with MySQL version 5.6.4 it is possible to store fractional
25173 seconds up to microsecond precision in <code>TIME</code>,
25174 <code>DATETIME</code>, and <code>TIMESTAMP</code> columns. However,
25175 to enable sub-second precision, the corresponding type with the
25176 desired precision has to be specified explicitly, as shown in the
25177 following example:</p>
25178
25179 <pre class="cxx">
25180 #pragma db object
25181 class person
25182 {
25183 ...
25184 #pragma db type("DATETIME(6)") // Microsecond precision.
25185 boost::posix_time::ptime updated_;
25186 };
25187 </pre>
25188
25189 <p>Alternatively, you can enable sub-second precision on the per-type
25190 basis, for example:</p>
25191
25192 <pre class="cxx">
25193 #pragma db value(boost::posix_time::ptime) type("DATETIME(6)")
25194
25195 #pragma db object
25196 class person
25197 {
25198 ...
25199 boost::posix_time::ptime created_; // Microsecond precision.
25200 boost::posix_time::ptime updated_; // Microsecond precision.
25201 };
25202 </pre>
25203
25204 <p>Some valid Boost date-time values cannot be stored in a MySQL database.
25205 An attempt to persist any Boost date-time special value other than
25206 <code>date_time::not_a_date_time</code> will result in the
25207 <code>special_value</code> exception. An attempt to persist a Boost
25208 date-time value that is out of the MySQL type range will result in
25209 the <code>out_of_range</code> exception. Refer to the MySQL
25210 documentation for more information on the MySQL data type ranges.</p>
25211
25212 <h3><a name="23.5.2">23.5.2 SQLite Database Type Mapping</a></h3>
25213
25214 <p>The following table summarizes the default mapping between the currently
25215 supported Boost <code>date_time</code> types and the SQLite database
25216 types.</p>
25217
25218 <!-- border="1" is necessary for html2ps -->
25219 <table id="mapping" border="1">
25220 <tr>
25221 <th>Boost <code>date_time</code> Type</th>
25222 <th>SQLite Type</th>
25223 <th>Default <code>NULL</code> Semantics</th>
25224 </tr>
25225
25226 <tr>
25227 <td><code>gregorian::date</code></td>
25228 <td><code>TEXT</code></td>
25229 <td><code>NULL</code></td>
25230 </tr>
25231
25232 <tr>
25233 <td><code>posix_time::ptime</code></td>
25234 <td><code>TEXT</code></td>
25235 <td><code>NULL</code></td>
25236 </tr>
25237
25238 <tr>
25239 <td><code>posix_time::time_duration</code></td>
25240 <td><code>TEXT</code></td>
25241 <td><code>NULL</code></td>
25242 </tr>
25243 </table>
25244
25245 <p>The Boost special value <code>date_time::not_a_date_time</code> is stored
25246 as a <code>NULL</code> value in an SQLite database.</p>
25247
25248 <p>The <code>date-time</code> sub-profile implementation also provides
25249 support for mapping <code>gregorian::date</code> and
25250 <code>posix_time::ptime</code> to the <code>INTEGER</code> SQLite type,
25251 with the integer value representing the UNIX time. Similarly, an
25252 alternative mapping for <code>posix_time::time_duration</code> to the
25253 <code>INTEGER</code> type represents the duration as a number of
25254 seconds. These mappings have to be explicitly requested using the
25255 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
25256 "<code>type</code>"</a>), as shown in the following example:</p>
25257
25258 <pre class="cxx">
25259 #pragma db object
25260 class person
25261 {
25262 ...
25263 #pragma db type("INTEGER")
25264 boost::gregorian::date born_;
25265 };
25266 </pre>
25267
25268 <!--
25269
25270 <p>The Boost UNIX time interface does not support 64 bit time arithmetic.
25271 As a result, the UNIX time representations of <code>gregorian::date</code>
25272 and <code>posix_time::ptime</code> are restricted to the 32 bit range.
25273 The minimum and maximum date representable by
25274 <code>gregorian::date</code> is 1901-12-14 and 2038-01-19 respectively,
25275 while the minimum and maximum date-time representable by
25276 <code>posix_time::ptime</code> is 1901-12-13&nbsp;20:45:54 GMT and
25277 2038-01-19&nbsp;03:14:07&nbsp;GMT respectively. Persisting and loading
25278 of values outside of these ranges will result in undefined behavior.</p>
25279
25280 -->
25281
25282 <p>Some valid Boost date-time values cannot be stored in an SQLite database.
25283 An attempt to persist any Boost date-time special value other than
25284 <code>date_time::not_a_date_time</code> will result in the
25285 <code>special_value</code> exception. An attempt to persist a negative
25286 <code>posix_time::time_duration</code> value as SQLite <code>TEXT</code>
25287 will result in the <code>out_of_range</code> exception.</p>
25288
25289
25290 <h3><a name="23.5.3">23.5.3 PostgreSQL Database Type Mapping</a></h3>
25291
25292 <p>The following table summarizes the default mapping between the currently
25293 supported Boost <code>date_time</code> types and the PostgreSQL database
25294 types.</p>
25295
25296 <!-- border="1" is necessary for html2ps -->
25297 <table id="mapping" border="1">
25298 <tr>
25299 <th>Boost <code>date_time</code> Type</th>
25300 <th>PostgreSQL Type</th>
25301 <th>Default <code>NULL</code> Semantics</th>
25302 </tr>
25303
25304 <tr>
25305 <td><code>gregorian::date</code></td>
25306 <td><code>DATE</code></td>
25307 <td><code>NULL</code></td>
25308 </tr>
25309
25310 <tr>
25311 <td><code>posix_time::ptime</code></td>
25312 <td><code>TIMESTAMP</code></td>
25313 <td><code>NULL</code></td>
25314 </tr>
25315
25316 <tr>
25317 <td><code>posix_time::time_duration</code></td>
25318 <td><code>TIME</code></td>
25319 <td><code>NULL</code></td>
25320 </tr>
25321 </table>
25322
25323 <p>The Boost special value <code>date_time::not_a_date_time</code> is stored
25324 as a <code>NULL</code> value in a PostgreSQL database.
25325 <code>posix_time::ptime</code> values representing the special values
25326 <code>date_time::pos_infin</code> and <code>date_time::neg_infin</code>
25327 are stored as the special PostgreSQL TIMESTAMP values
25328 <code>infinity</code> and <code>-infinity</code>, respectively.</p>
25329
25330 <p>Some valid Boost date-time values cannot be stored in a PostgreSQL
25331 database. The PostgreSQL TIME type represents a clock time, and can
25332 therefore only store positive durations with a total length of time less
25333 than 24 hours. An attempt to persist a
25334 <code>posix_time::time_duration</code> value outside of this range will
25335 result in the <code>value_out_of_range</code> exception. An attempt to
25336 persist a <code>posix_time::time_duration</code> value representing any
25337 special value other than <code>date_time::not_a_date_time</code> will
25338 result in the <code>special_value</code> exception.</p>
25339
25340
25341 <h3><a name="23.5.4">23.5.4 Oracle Database Type Mapping</a></h3>
25342
25343 <p>The following table summarizes the default mapping between the currently
25344 supported Boost <code>date_time</code> types and the Oracle database
25345 types.</p>
25346
25347 <!-- border="1" is necessary for html2ps -->
25348 <table id="mapping" border="1">
25349 <tr>
25350 <th>Boost <code>date_time</code> Type</th>
25351 <th>Oracle Type</th>
25352 <th>Default <code>NULL</code> Semantics</th>
25353 </tr>
25354
25355 <tr>
25356 <td><code>gregorian::date</code></td>
25357 <td><code>DATE</code></td>
25358 <td><code>NULL</code></td>
25359 </tr>
25360
25361 <tr>
25362 <td><code>posix_time::ptime</code></td>
25363 <td><code>TIMESTAMP</code></td>
25364 <td><code>NULL</code></td>
25365 </tr>
25366
25367 <tr>
25368 <td><code>posix_time::time_duration</code></td>
25369 <td><code>INTERVAL DAY TO SECOND</code></td>
25370 <td><code>NULL</code></td>
25371 </tr>
25372 </table>
25373
25374 <p>The Boost special value <code>date_time::not_a_date_time</code> is stored
25375 as a <code>NULL</code> value in an Oracle database.</p>
25376
25377 <p>The <code>date-time</code> sub-profile implementation also provides
25378 support for mapping <code>posix_time::ptime</code> to the
25379 <code>DATE</code> Oracle type with fractional seconds that may be
25380 stored in a <code>ptime</code> instance being ignored. This
25381 alternative mapping has to be explicitly requested using the
25382 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
25383 "<code>type</code>"</a>), as shown in the following example:</p>
25384
25385 <pre class="cxx">
25386 #pragma db object
25387 class person
25388 {
25389 ...
25390 #pragma db type("DATE")
25391 boost::posix_time::ptime updated_;
25392 };
25393 </pre>
25394
25395 <p>Some valid Boost date-time values cannot be stored in an Oracle database.
25396 An attempt to persist a <code>gregorian::date</code>,
25397 <code>posix_time::ptime</code>, or
25398 <code>posix_time::time_duration</code> value representing any special
25399 value other than <code>date_time::not_a_date_time</code> will result in
25400 the <code>special_value</code> exception.</p>
25401
25402
25403 <h3><a name="23.5.5">23.5.5 SQL Server Database Type Mapping</a></h3>
25404
25405 <p>The following table summarizes the default mapping between the currently
25406 supported Boost <code>date_time</code> types and the SQL Server database
25407 types.</p>
25408
25409 <!-- border="1" is necessary for html2ps -->
25410 <table id="mapping" border="1">
25411 <tr>
25412 <th>Boost <code>date_time</code> Type</th>
25413 <th>SQL Server Type</th>
25414 <th>Default <code>NULL</code> Semantics</th>
25415 </tr>
25416
25417 <tr>
25418 <td><code>gregorian::date</code></td>
25419 <td><code>DATE</code></td>
25420 <td><code>NULL</code></td>
25421 </tr>
25422
25423 <tr>
25424 <td><code>posix_time::ptime</code></td>
25425 <td><code>DATETIME2</code></td>
25426 <td><code>NULL</code></td>
25427 </tr>
25428
25429 <tr>
25430 <td><code>posix_time::time_duration</code></td>
25431 <td><code>TIME</code></td>
25432 <td><code>NULL</code></td>
25433 </tr>
25434 </table>
25435
25436 <p>The Boost special value <code>date_time::not_a_date_time</code> is stored
25437 as a <code>NULL</code> value in an SQL Server database.</p>
25438
25439 <p>Note that the <code>DATE</code>, <code>TIME</code>, and
25440 <code>DATETIME2</code> types are only available in SQL Server 2008 and
25441 later. SQL Server 2005 only supports the <code>DATETIME</code> and
25442 <code>SMALLDATETIME</code> date-time types. The new types are
25443 also unavailable when connecting to an SQL Server 2008 or
25444 later with the SQL Server 2005 Native Client ODBC driver.</p>
25445
25446 <p>The <code>date-time</code> sub-profile implementation provides
25447 support for mapping <code>posix_time::ptime</code> to the
25448 <code>DATETIME</code> and <code>SMALLDATETIME</code> types,
25449 however, this mapping has to be explicitly requested using the
25450 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
25451 "<code>type</code>"</a>), as shown in the following example:</p>
25452
25453 <pre class="cxx">
25454 #pragma db object
25455 class person
25456 {
25457 ...
25458 #pragma db type("DATETIME")
25459 boost::posix_time::ptime updated_;
25460 };
25461 </pre>
25462
25463 <p>Some valid Boost date-time values cannot be stored in an SQL Server
25464 database. An attempt to persist a <code>gregorian::date</code>,
25465 <code>posix_time::ptime</code>, or <code>posix_time::time_duration</code>
25466 value representing any special value other than
25467 <code>date_time::not_a_date_time</code> will result in the
25468 <code>special_value</code> exception. The range of the <code>TIME</code>
25469 type in SQL server is from <code>00:00:00.0000000</code> to
25470 <code>23:59:59.9999999</code>. An attempt to persist a
25471 <code>posix_time::time_duration</code> value out of this range will
25472 result in the <code>value_out_of_range</code> exception.</p>
25473
25474 <h2><a name="23.6">23.6 Uuid Library</a></h2>
25475
25476 <p>The <code>uuid</code> sub-profile provides persistence support for the
25477 <code>uuid</code> type from the Boost <code>uuid</code> library. To
25478 enable only this profile, pass <code>boost/uuid</code> to the
25479 <code>--profile</code> ODB compiler option.</p>
25480
25481 <p>The manner in which these types are persisted is database system
25482 dependent and is discussed in the sub-sections that follow. By
25483 default a data member of the <code>uuid</code> type is mapped to a
25484 database column with <code>NULL</code> enabled and nil <code>uuid</code>
25485 instances are stored as a <code>NULL</code> value. However, you can
25486 change this behavior by declaring the data member <code>NOT NULL</code>
25487 with the <code>not_null</code> pragma (<a href="#14.4.6">Section
25488 14.4.6, "<code>null</code>/<code>not_null</code>"</a>). In this
25489 case, or if the data member is an object id, the implementation
25490 will store nil <code>uuid</code> instances as zero UUID values
25491 (<code>{00000000-0000-0000-0000-000000000000}</code>). For example:</p>
25492
25493 <pre class="cxx">
25494 #pragma db object
25495 class object
25496 {
25497 ...
25498
25499 boost::uuids::uuid x_; // Nil values stored as NULL.
25500
25501 #pragma db not_null
25502 boost::uuids::uuid y_; // Nil values stored as zero.
25503 };
25504 </pre>
25505
25506 <h3><a name="23.6.1">23.6.1 MySQL Database Type Mapping</a></h3>
25507
25508 <p>The following table summarizes the default mapping between the Boost
25509 <code>uuid</code> type and the MySQL database type.</p>
25510
25511 <!-- border="1" is necessary for html2ps -->
25512 <table id="mapping" border="1">
25513 <tr>
25514 <th>Boost Type</th>
25515 <th>MySQL Type</th>
25516 <th>Default <code>NULL</code> Semantics</th>
25517 </tr>
25518
25519 <tr>
25520 <td><code>boost::uuids::uuid</code></td>
25521 <td><code>BINARY(16)</code></td>
25522 <td><code>NULL</code></td>
25523 </tr>
25524 </table>
25525
25526 <h3><a name="23.6.2">23.6.2 SQLite Database Type Mapping</a></h3>
25527
25528 <p>The following table summarizes the default mapping between the Boost
25529 <code>uuid</code> type and the SQLite database type.</p>
25530
25531 <!-- border="1" is necessary for html2ps -->
25532 <table id="mapping" border="1">
25533 <tr>
25534 <th>Boost Type</th>
25535 <th>SQLite Type</th>
25536 <th>Default <code>NULL</code> Semantics</th>
25537 </tr>
25538
25539 <tr>
25540 <td><code>boost::uuids::uuid</code></td>
25541 <td><code>BLOB</code></td>
25542 <td><code>NULL</code></td>
25543 </tr>
25544 </table>
25545
25546 <h3><a name="23.6.3">23.6.3 PostgreSQL Database Type Mapping</a></h3>
25547
25548 <p>The following table summarizes the default mapping between the Boost
25549 <code>uuid</code> type and the PostgreSQL database type.</p>
25550
25551 <!-- border="1" is necessary for html2ps -->
25552 <table id="mapping" border="1">
25553 <tr>
25554 <th>Boost Type</th>
25555 <th>PostgreSQL Type</th>
25556 <th>Default <code>NULL</code> Semantics</th>
25557 </tr>
25558
25559 <tr>
25560 <td><code>boost::uuids::uuid</code></td>
25561 <td><code>UUID</code></td>
25562 <td><code>NULL</code></td>
25563 </tr>
25564 </table>
25565
25566 <h3><a name="23.6.4">23.6.4 Oracle Database Type Mapping</a></h3>
25567
25568 <p>The following table summarizes the default mapping between the Boost
25569 <code>uuid</code> type and the Oracle database type.</p>
25570
25571 <!-- border="1" is necessary for html2ps -->
25572 <table id="mapping" border="1">
25573 <tr>
25574 <th>Boost Type</th>
25575 <th>Oracle Type</th>
25576 <th>Default <code>NULL</code> Semantics</th>
25577 </tr>
25578
25579 <tr>
25580 <td><code>boost::uuids::uuid</code></td>
25581 <td><code>RAW(16)</code></td>
25582 <td><code>NULL</code></td>
25583 </tr>
25584 </table>
25585
25586 <h3><a name="23.6.5">23.6.5 SQL Server Database Type Mapping</a></h3>
25587
25588 <p>The following table summarizes the default mapping between the Boost
25589 <code>uuid</code> type and the SQL Server database type.</p>
25590
25591 <!-- border="1" is necessary for html2ps -->
25592 <table id="mapping" border="1">
25593 <tr>
25594 <th>Boost Type</th>
25595 <th>SQL Server Type</th>
25596 <th>Default <code>NULL</code> Semantics</th>
25597 </tr>
25598
25599 <tr>
25600 <td><code>boost::uuids::uuid</code></td>
25601 <td><code>UNIQUEIDENTIFIER</code></td>
25602 <td><code>NULL</code></td>
25603 </tr>
25604 </table>
25605
25606
25607 <!-- CHAPTER -->
25608
25609
25610 <hr class="page-break"/>
25611 <h1><a name="24">24 Qt Profile</a></h1>
25612
25613 <p>The ODB profile implementation for Qt is provided by the
25614 <code>libodb-qt</code> library. Both Qt4 and Qt5 as well
25615 as C++98/03 and C++11 are supported.</p>
25616
25617 <p>The Qt profile consists of multiple sub-profiles
25618 corresponding to the common type groups within Qt. Currently,
25619 only types from the <code>QtCore</code> module are supported. To
25620 enable all the available Qt sub-profiles, pass <code>qt</code> as the
25621 profile name to the <code>--profile</code> ODB compiler option.
25622 Alternatively, you can enable only specific sub-profiles by passing
25623 individual sub-profile names to <code>--profile</code>. The following
25624 sections in this chapter discuss each Qt sub-profile in detail. The
25625 <code>qt</code> example in the <code>odb-examples</code>
25626 package shows how to enable and use the Qt profile.</p>
25627
25628 <p>Some sub-profiles may throw exceptions to indicate error conditions,
25629 such as the inability to store a specific value in a particular database
25630 system. All such exceptions derive from the
25631 <code>odb::qt::exception</code> class which in turn derives from
25632 the root of the ODB exception hierarchy, class <code>odb::exception</code>
25633 (<a href="#3.14">Section 3.14, "ODB Exceptions"</a>). The
25634 <code>odb::qt::exception</code> class is defined in the
25635 <code>&lt;odb/qt/exception.hxx></code> header file and has the
25636 same interface as <code>odb::exception</code>. Concrete exceptions
25637 that can be thrown by the Qt sub-profiles are described in the
25638 following sections.</p>
25639
25640 <h2><a name="24.1">24.1 Basic Types Library</a></h2>
25641
25642 <p>The <code>basic</code> sub-profile provides persistence support for basic
25643 types defined by Qt. To enable only this profile, pass
25644 <code>qt/basic</code> to the <code>--profile</code> ODB compiler
25645 option.</p>
25646
25647 <p>The currently supported basic types are <code>QString</code>,
25648 <code>QByteArray</code>, and <code>QUuid</code>. The manner in
25649 which these types are persisted is database system dependent
25650 and is discussed in the sub-sections that follow. The example
25651 below shows how <code>QString</code> may be used within a
25652 persistent object.</p>
25653
25654 <pre class="cxx">
25655 #pragma db object
25656 class Person
25657 {
25658 ...
25659 QString name_;
25660 };
25661 </pre>
25662
25663 <p>By default a data member of the <code>QUuid</code> type is mapped to a
25664 database column with <code>NULL</code> enabled and null <code>QUuid</code>
25665 instances are stored as a <code>NULL</code> value. However, you can
25666 change this behavior by declaring the data member <code>NOT NULL</code>
25667 with the <code>not_null</code> pragma (<a href="#14.4.6">Section
25668 14.4.6, "<code>null</code>/<code>not_null</code>"</a>). In this
25669 case, or if the data member is an object id, the implementation
25670 will store null <code>QUuid</code> instances as zero UUID values
25671 (<code>{00000000-0000-0000-0000-000000000000}</code>). For example:</p>
25672
25673 <pre class="cxx">
25674 #pragma db object
25675 class object
25676 {
25677 ...
25678
25679 QUuid x_; // Null values stored as NULL.
25680
25681 #pragma db not_null
25682 QUuid y_; // Null values stored as zero.
25683 };
25684 </pre>
25685
25686 <h3><a name="24.1.1">24.1.1 MySQL Database Type Mapping</a></h3>
25687
25688 <p>The following table summarizes the default mapping between the currently
25689 supported basic Qt types and the MySQL database types.</p>
25690
25691 <!-- border="1" is necessary for html2ps -->
25692 <table id="mapping" border="1">
25693 <tr>
25694 <th>Qt Type</th>
25695 <th>MySQL Type</th>
25696 <th>Default <code>NULL</code> Semantics</th>
25697 </tr>
25698
25699 <tr>
25700 <td><code>QString</code></td>
25701 <td><code>TEXT/VARCHAR(255)</code></td>
25702 <td><code>NULL</code></td>
25703 </tr>
25704
25705 <tr>
25706 <td><code>QByteArray</code></td>
25707 <td><code>BLOB</code></td>
25708 <td><code>NULL</code></td>
25709 </tr>
25710
25711 <tr>
25712 <td><code>QUuid</code></td>
25713 <td><code>BINARY(16)</code></td>
25714 <td><code>NULL</code></td>
25715 </tr>
25716 </table>
25717
25718 <p>Instances of the <code>QString</code> and <code>QByteArray</code>
25719 types are stored as a <code>NULL</code> value if their
25720 <code>isNull()</code> member function returns <code>true</code>.</p>
25721
25722 <p>Note also that the <code>QString</code> type is mapped
25723 differently depending on whether a member of this type
25724 is an object id or not. If the member is an object id,
25725 then for this member <code>QString</code> is mapped
25726 to the <code>VARCHAR(255)</code> MySQL type. Otherwise,
25727 it is mapped to <code>TEXT</code>.</p>
25728
25729 <p>The <code>basic</code> sub-profile also provides support
25730 for mapping <code>QString</code> to the <code>CHAR</code>,
25731 <code>NCHAR</code>, and <code>NVARCHAR</code> MySQL types.
25732 However, these alternative mappings have to be explicitly
25733 requested using the <code>db&nbsp;type</code> pragma
25734 (<a href="#14.4.3">Section 14.4.3, "type"</a>), as shown in
25735 the following example:</p>
25736
25737 <pre class="cxx">
25738 #pragma db object
25739 class Person
25740 {
25741 ...
25742
25743 #pragma db type("CHAR(2)") not_null
25744 QString licenseState_;
25745 };
25746 </pre>
25747
25748
25749 <h3><a name="24.1.2">24.1.2 SQLite Database Type Mapping</a></h3>
25750
25751 <p>The following table summarizes the default mapping between the currently
25752 supported basic Qt types and the SQLite database types.</p>
25753
25754 <!-- border="1" is necessary for html2ps -->
25755 <table id="mapping" border="1">
25756 <tr>
25757 <th>Qt Type</th>
25758 <th>SQLite Type</th>
25759 <th>Default <code>NULL</code> Semantics</th>
25760 </tr>
25761
25762 <tr>
25763 <td><code>QString</code></td>
25764 <td><code>TEXT</code></td>
25765 <td><code>NULL</code></td>
25766 </tr>
25767
25768 <tr>
25769 <td><code>QByteArray</code></td>
25770 <td><code>BLOB</code></td>
25771 <td><code>NULL</code></td>
25772 </tr>
25773
25774 <tr>
25775 <td><code>QUuid</code></td>
25776 <td><code>BLOB</code></td>
25777 <td><code>NULL</code></td>
25778 </tr>
25779 </table>
25780
25781 <p>Instances of the <code>QString</code> and <code>QByteArray</code> types
25782 are stored as a <code>NULL</code> value if their <code>isNull()</code>
25783 member function returns <code>true</code>.</p>
25784
25785 <h3><a name="24.1.3">24.1.3 PostgreSQL Database Type Mapping</a></h3>
25786
25787 <p>The following table summarizes the default mapping between the currently
25788 supported basic Qt types and the PostgreSQL database types.</p>
25789
25790 <!-- border="1" is necessary for html2ps -->
25791 <table id="mapping" border="1">
25792 <tr>
25793 <th>Qt Type</th>
25794 <th>PostgreSQL Type</th>
25795 <th>Default <code>NULL</code> Semantics</th>
25796 </tr>
25797
25798 <tr>
25799 <td><code>QString</code></td>
25800 <td><code>TEXT</code></td>
25801 <td><code>NULL</code></td>
25802 </tr>
25803
25804 <tr>
25805 <td><code>QByteArray</code></td>
25806 <td><code>BYTEA</code></td>
25807 <td><code>NULL</code></td>
25808 </tr>
25809
25810 <tr>
25811 <td><code>QUuid</code></td>
25812 <td><code>UUID</code></td>
25813 <td><code>NULL</code></td>
25814 </tr>
25815 </table>
25816
25817 <p>Instances of the <code>QString</code> and <code>QByteArray</code> types
25818 are stored as a <code>NULL</code> value if their <code>isNull()</code>
25819 member function returns <code>true</code>.</p>
25820
25821 <p>The <code>basic</code> sub-profile also provides support
25822 for mapping <code>QString</code> to the <code>CHAR</code>
25823 and <code>VARCHAR</code> PostgreSQL types.
25824 However, these alternative mappings have to be explicitly
25825 requested using the <code>db&nbsp;type</code> pragma
25826 (<a href="#14.4.3">Section 14.4.3, "type"</a>), as shown in
25827 the following example:</p>
25828
25829 <pre class="cxx">
25830 #pragma db object
25831 class Person
25832 {
25833 ...
25834
25835 #pragma db type("CHAR(2)") not_null
25836 QString licenseState_;
25837 };
25838 </pre>
25839
25840 <h3><a name="24.1.4">24.1.4 Oracle Database Type Mapping</a></h3>
25841
25842 <p>The following table summarizes the default mapping between the currently
25843 supported basic Qt types and the Oracle database types.</p>
25844
25845 <!-- border="1" is necessary for html2ps -->
25846 <table id="mapping" border="1">
25847 <tr>
25848 <th>Qt Type</th>
25849 <th>Oracle Type</th>
25850 <th>Default <code>NULL</code> Semantics</th>
25851 </tr>
25852
25853 <tr>
25854 <td><code>QString</code></td>
25855 <td><code>VARCHAR2(512)</code></td>
25856 <td><code>NULL</code></td>
25857 </tr>
25858
25859 <tr>
25860 <td><code>QByteArray</code></td>
25861 <td><code>BLOB</code></td>
25862 <td><code>NULL</code></td>
25863 </tr>
25864
25865 <tr>
25866 <td><code>QUuid</code></td>
25867 <td><code>RAW(16)</code></td>
25868 <td><code>NULL</code></td>
25869 </tr>
25870 </table>
25871
25872 <p>Instances of the <code>QString</code> and <code>QByteArray</code> types
25873 are stored as a <code>NULL</code> value if their <code>isNull()</code>
25874 member function returns <code>true</code>.</p>
25875
25876 <p>The <code>basic</code> sub-profile also provides support
25877 for mapping <code>QString</code> to the <code>CHAR</code>,
25878 <code>NCHAR</code>, <code>NVARCHAR</code>, <code>CLOB</code>, and
25879 <code>NCLOB</code> Oracle types, and for mapping <code>QByteArray</code>
25880 to the <code>RAW</code> Oracle type. However, these alternative
25881 mappings have to be explicitly requested using the <code>db&nbsp;type</code>
25882 pragma (<a href="#14.4.3">Section 14.4.3, "type"</a>), as shown in the
25883 following example:</p>
25884
25885 <pre class="cxx">
25886 #pragma db object
25887 class Person
25888 {
25889 ...
25890
25891 #pragma db type("CLOB") not_null
25892 QString firstName_;
25893
25894 #pragma db type("RAW(16)") null
25895 QByteArray uuid_;
25896 };
25897 </pre>
25898
25899 <h3><a name="24.1.5">24.1.5 SQL Server Database Type Mapping</a></h3>
25900
25901 <p>The following table summarizes the default mapping between the currently
25902 supported basic Qt types and the SQL Server database types.</p>
25903
25904 <!-- border="1" is necessary for html2ps -->
25905 <table id="mapping" border="1">
25906 <tr>
25907 <th>Qt Type</th>
25908 <th>SQL Server Type</th>
25909 <th>Default <code>NULL</code> Semantics</th>
25910 </tr>
25911
25912 <tr>
25913 <td><code>QString</code></td>
25914 <td><code>VARCHAR(512)/VARCHAR(256)</code></td>
25915 <td><code>NULL</code></td>
25916 </tr>
25917
25918 <tr>
25919 <td><code>QByteArray</code></td>
25920 <td><code>VARBINARY(max)</code></td>
25921 <td><code>NULL</code></td>
25922 </tr>
25923
25924 <tr>
25925 <td><code>QUuid</code></td>
25926 <td><code>UNIQUEIDENTIFIER</code></td>
25927 <td><code>NULL</code></td>
25928 </tr>
25929 </table>
25930
25931 <p>Instances of the <code>QString</code> and <code>QByteArray</code> types
25932 are stored as a <code>NULL</code> value if their <code>isNull()</code>
25933 member function returns <code>true</code>.</p>
25934
25935 <p>Note also that the <code>QString</code> type is mapped
25936 differently depending on whether a member of this type
25937 is an object id or not. If the member is an object id,
25938 then for this member <code>QString</code> is mapped
25939 to the <code>VARCHAR(256)</code> SQL Server type. Otherwise,
25940 it is mapped to <code>VARCHAR(512)</code>.</p>
25941
25942 <p>The <code>basic</code> sub-profile also provides support
25943 for mapping <code>QString</code> to the <code>CHAR</code>,
25944 <code>NCHAR</code>, <code>NVARCHAR</code>, <code>TEXT</code>, and
25945 <code>NTEXT</code> SQL Server types, and for mapping
25946 <code>QByteArray</code> to the <code>BINARY</code> and
25947 <code>IMAGE</code> SQL Server types. However, these alternative
25948 mappings have to be explicitly requested using the <code>db&nbsp;type</code>
25949 pragma (<a href="#14.4.3">Section 14.4.3, "type"</a>), as shown in the
25950 following example:</p>
25951
25952 <pre class="cxx">
25953 #pragma db object
25954 class Person
25955 {
25956 ...
25957
25958 #pragma db type("NVARCHAR(256)") not_null
25959 QString firstName_;
25960
25961 #pragma db type("BINARY(16)") null
25962 QByteArray uuid_;
25963 };
25964 </pre>
25965
25966 <h2><a name="24.2">24.2 Smart Pointers Library</a></h2>
25967
25968 <p>The <code>smart-ptr</code> sub-profile provides persistence support the
25969 Qt smart pointers. To enable only this profile, pass
25970 <code>qt/smart-ptr</code> to the <code>--profile</code> ODB compiler
25971 option.</p>
25972
25973 <p>The currently supported smart pointers are
25974 <code>QSharedPointer</code> and <code>QWeakPointer</code>.
25975 For more information on using smart pointers as pointers to objects
25976 and views, refer to <a href="#3.3">Section 3.3, "Object and View
25977 Pointers"</a> and <a href="#6">Chapter 6, "Relationships"</a>. For
25978 more information on using smart pointers as pointers to values, refer
25979 to <a href="#7.3">Section 7.3, "Pointers and <code>NULL</code> Value
25980 Semantics"</a>. When used as a pointer to a value, only
25981 <code>QSharedPointer</code> is supported. For example:</p>
25982
25983 <pre class="cxx">
25984 #pragma db object
25985 class person
25986 {
25987 ...
25988
25989 #pragma db null
25990 QSharedPointer&lt;QString> middle_name_;
25991 };
25992 </pre>
25993
25994 <p>To provide finer grained control over object relationship loading,
25995 the <code>smart-ptr</code> sub-profile also provides the lazy
25996 counterparts for the above pointers: <code>QLazySharedPointer</code>
25997 and <code>QLazyWeakPointer</code>. You will need to include the
25998 <code>&lt;odb/qt/lazy-ptr.hxx></code> header file to make the lazy
25999 variants available in your application. For a description of the lazy
26000 pointer interface and semantics refer to <a href="#6.4">Section 6.4,
26001 "Lazy Pointers"</a>. The following example shows how we can use these
26002 smart pointers to establish a relationship between persistent objects.</p>
26003
26004 <pre class="cxx">
26005 class Employee;
26006
26007 #pragma db object
26008 class Position
26009 {
26010 ...
26011
26012 #pragma db inverse(position_)
26013 QLazyWeakPointer&lt;Employee> employee_;
26014 };
26015
26016 #pragma db object
26017 class Employee
26018 {
26019 ...
26020
26021 #pragma db not_null
26022 QSharedPointer&lt;Position> position_;
26023 };
26024 </pre>
26025
26026 <p>Besides providing persistence support for the above smart pointers,
26027 the <code>smart-ptr</code> sub-profile also changes the default
26028 pointer (<a href="#3.3">Section 3.3, "Object and View Pointers"</a>)
26029 to <code>QSharedPointer</code>. In particular, this means that
26030 database functions that return dynamically allocated objects and views
26031 will return them as <code>QSharedPointer</code> pointers. To override
26032 this behavior, add the <code>--default-pointer</code> option specifying
26033 the alternative pointer type after the <code>--profile</code> option.</p>
26034
26035 <h2><a name="24.3">24.3 Containers Library</a></h2>
26036
26037 <p>The <code>containers</code> sub-profile provides persistence support for
26038 Qt containers. To enable only this profile, pass
26039 <code>qt/containers</code> to the <code>--profile</code> ODB compiler
26040 option.</p>
26041
26042 <p>The currently supported ordered containers are <code>QVector</code>,
26043 <code>QList</code>, and <code>QLinkedList</code>. Supported map
26044 containers are <code>QMap</code>, <code>QMultiMap</code>,
26045 <code>QHash</code>, and <code>QMultiHash</code>. The supported set
26046 container is <code>QSet</code>. For more information on using
26047 containers with ODB, refer to <a href="#5">Chapter 5, "Containers"</a>.
26048 The following example shows how the <code>QSet</code> container may
26049 be used within a persistent object.</p>
26050
26051 <pre class="cxx">
26052 #pragma db object
26053 class Person
26054 {
26055 ...
26056 QSet&lt;QString> emails_;
26057 };
26058 </pre>
26059
26060 <p>The <code>containers</code> sub-profile also provide a change-tracking
26061 equivalent for <code>QList</code> (<a href="#24.3.1">Section 24.3.1,
26062 "Change-Tracking <code>QList</code>"</a>) with support for other Qt
26063 container equivalents planned for future releases. For general information
26064 on change-tracking containers refer to <a href="#5.4">Section 5.4,
26065 "Change-Tracking Containers"</a>.</p>
26066
26067 <h3><a name="24.3.1">24.3.1 Change-Tracking <code>QList</code></a></h3>
26068
26069 <p>Class template <code>QOdbList</code>, defined in
26070 <code>&lt;odb/qt/list.hxx></code>, is a change-tracking
26071 equivalent for <code>QList</code>. It
26072 is implemented in terms of <code>QList</code> and is
26073 implicit-convertible to and implicit-constructible from
26074 <code>const QList&amp;</code>. In particular, this
26075 means that we can use <code>QOdbList</code> instance
26076 anywhere <code>const QList&amp;</code> is
26077 expected. In addition, <code>QOdbList</code> constant
26078 iterator (<code>const_iterator</code>) is the same type as
26079 that of <code>QList</code>.</p>
26080
26081 <p><code>QOdbList</code> incurs 2-bit per element overhead
26082 in order to store the change state. It cannot
26083 be stored unordered in the database (<a href="#14.4.19">Section
26084 14.4.19 "<code>unordered</code>"</a>) but can be used as an inverse
26085 side of a relationship (<a href="#6.2">6.2 "Bidirectional
26086 Relationships"</a>). In this case, no change tracking is performed
26087 since no state for such a container is stored in the database.</p>
26088
26089 <p>The number of database operations required to update the state
26090 of <code>QOdbList</code> corresponds well to the complexity
26091 of <code>QList</code> functions, except for
26092 <code>prepend()</code>/<code>push_front()</code>. In particular, adding
26093 or removing an element from the back of the list (for example,
26094 with <code>append()</code>/<code>push_back()</code> and
26095 <code>removeLast()</code>/<code>pop_back()</code>),
26096 requires only a single database statement execution. In contrast,
26097 inserting or erasing an element at the beginning or in the middle
26098 of the list will require a database statement for every element that
26099 follows it.</p>
26100
26101 <p><code>QOdbList</code> replicates most of the <code>QList</code>
26102 interface as defined in both Qt4 and Qt5 and includes support for
26103 C++11. However, functions and operators that provide direct write
26104 access to the elements had to be altered or disabled in order to
26105 support change tracking. Additional functions used to interface with
26106 <code>QList</code> and to control the change tracking state
26107 were also added. The following listing summarizes the differences
26108 between the <code>QOdbList</code> and <code>QList</code>
26109 interfaces. Any <code>QList</code> function or operator
26110 not mentioned in this listing has exactly the same signature
26111 and semantics in <code>QOdbList</code>. Functions and
26112 operators that were disabled are shown as commented out and
26113 are followed by functions/operators that replace them.</p>
26114
26115 <pre class="cxx">
26116 template &lt;typename T>
26117 class QOdbList
26118 {
26119 ...
26120
26121 // Element access.
26122 //
26123
26124 //T&amp; operator[] (int);
26125 T&amp; modify (int);
26126
26127 //T&amp; first();
26128 T&amp; modifyFirst();
26129
26130 //T&amp; last();
26131 T&amp; modifyLast();
26132
26133 //T&amp; front();
26134 T&amp; modify_front();
26135
26136 //T&amp; back();
26137 T&amp; modify_back();
26138
26139 // Iterators.
26140 //
26141 typedef typename QList&lt;T>::const_iterator const_iterator;
26142
26143 class iterator
26144 {
26145 ...
26146
26147 // Element Access.
26148 //
26149
26150 //reference operator* () const;
26151 const_reference operator* () const;
26152 reference modify () const;
26153
26154 //pointer operator-> () const;
26155 const_pointer operator-> () const;
26156
26157 //reference operator[] (difference_type);
26158 const_reference operator[] (difference_type);
26159 reference modify (difference_type) const;
26160
26161 // Interfacing with QList::iterator.
26162 //
26163 typename QList&lt;T>::iterator base () const;
26164 };
26165
26166 // Return QList iterators. The begin() functions mark all
26167 // the elements as modified.
26168 //
26169 typename QList&lt;T>::iterator mbegin ();
26170 typename QList&lt;T>::iterator modifyBegin ();
26171 typename QList&lt;T>::iterator mend ();
26172 typename QList&lt;T>::iterator modifyEnd ();
26173
26174 // Interfacing with QList.
26175 //
26176 QOdbList (const QList&lt;T>&amp;);
26177 QOdbList (QList&lt;T>&amp;&amp;); // C++11 only.
26178
26179 QOdbList&amp; operator= (const QList&lt;T>&amp;);
26180 QOdbList&amp; operator= (QList&lt;T>&amp;&amp;);
26181
26182 operator const QList&lt;T>&amp; () const;
26183 QList&lt;T>&amp; base ();
26184 const QList&lt;T>&amp; base () const;
26185
26186 // Change tracking.
26187 //
26188 bool _tracking () const;
26189 void _start () const;
26190 void _stop () const;
26191 void _arm (transaction&amp;) const;
26192 };
26193 </pre>
26194
26195 <p>The following example highlights some of the differences between
26196 the two interfaces. <code>QList</code> versions are commented
26197 out.</p>
26198
26199 <pre class="cxx">
26200 #include &lt;QtCore/QList>
26201 #include &lt;odb/qt/list.hxx>
26202
26203 void f (const QList&lt;int>&amp;);
26204
26205 QOdbList&lt;int> l ({1, 2, 3});
26206
26207 f (l); // Ok, implicit conversion.
26208
26209 if (l[1] == 2) // Ok, const access.
26210 //l[1]++;
26211 l.modify (1)++;
26212
26213 //l.last () = 4;
26214 l.modifyLast () = 4;
26215
26216 for (auto i (l.begin ()); i != l.end (); ++i)
26217 {
26218 if (*i != 0) // Ok, const access.
26219 //*i += 10;
26220 i.modify () += 10;
26221 }
26222
26223 qSort (l.modifyBegin (), l.modifyEnd ());
26224 </pre>
26225
26226 <p>Note also the subtle difference between copy/move construction
26227 and copy/move assignment of <code>QOdbList</code> instances.
26228 While copy/move constructor will copy/move both the elements as
26229 well as their change state, in contrast, assignment is tracked
26230 as any other change to the vector content.</p>
26231
26232 <p>The <code>QListIterator</code> and <code>QMutableListIterator</code>
26233 equivalents are also provided. These are <code>QOdbListIterator</code>
26234 and <code>QMutableOdbListIterator</code> and are defined in
26235 <code>&lt;odb/qt/list-iterator.hxx></code> and
26236 <code>&lt;odb/qt/mutable-list-iterator.hxx></code>, respectively.</p>
26237
26238 <p><code>QOdbListIterator</code> has exactly the same interface and
26239 semantics as <code>QListIterator</code>. In fact, we can use
26240 <code>QListIterator</code> to iterate over a <code>QOdbList</code>
26241 instance.</p>
26242
26243 <p><code>QMutableOdbListIterator</code> also has exactly the same
26244 interface as <code>QMutableListIterator</code>. Note, however,
26245 that any element that such an iterator passes over with the
26246 call to <code>next()</code> is marked as modified.</p>
26247
26248 <h2><a name="24.4">24.4 Date Time Library</a></h2>
26249
26250 <p>The <code>date-time</code> sub-profile provides persistence support for
26251 the Qt date-time types. To enable only this profile, pass
26252 <code>qt/date-time</code> to the <code>--profile</code> ODB compiler
26253 option.</p>
26254
26255 <p>The currently supported date-time types are <code>QDate</code>,
26256 <code>QTime</code>, and <code>QDateTime</code>. The manner in which
26257 these types are persisted is database system dependent and is
26258 discussed in the sub-sections that follow. The example below shows how
26259 <code>QDate</code> may be used within a persistent object.</p>
26260
26261 <pre class="cxx">
26262 #pragma db object
26263 class Person
26264 {
26265 ...
26266 QDate dateOfBirth_;
26267 };
26268 </pre>
26269
26270 <p>The single concrete exception that can be thrown by the
26271 <code>date-time</code> sub-profile implementation is presented below.</p>
26272
26273
26274 <pre class="cxx">
26275 namespace odb
26276 {
26277 namespace qt
26278 {
26279 namespace date_time
26280 {
26281 struct value_out_of_range: odb::qt::exception
26282 {
26283 virtual const char*
26284 what () const throw ();
26285 };
26286 }
26287 }
26288 }
26289 </pre>
26290
26291 <p>You will need to include the
26292 <code>&lt;odb/qt/date-time/exceptions.hxx&gt;</code> header file to
26293 make this exception available in your application.</p>
26294
26295 <p>The <code>value_out_of_range</code> exception is thrown if an attempt
26296 is made to store a date-time value that is out of the target database
26297 range. The specific conditions under which it is thrown is database
26298 system dependent and is discussed in more detail in the
26299 following sub-sections.</p>
26300
26301 <h3><a name="24.4.1">24.4.1 MySQL Database Type Mapping</a></h3>
26302
26303 <p>The following table summarizes the default mapping between the currently
26304 supported Qt date-time types and the MySQL database types.</p>
26305
26306 <!-- border="1" is necessary for html2ps -->
26307 <table id="mapping" border="1">
26308 <tr>
26309 <th>Qt Date Time Type</th>
26310 <th>MySQL Type</th>
26311 <th>Default <code>NULL</code> Semantics</th>
26312 </tr>
26313
26314 <tr>
26315 <td><code>QDate</code></td>
26316 <td><code>DATE</code></td>
26317 <td><code>NULL</code></td>
26318 </tr>
26319
26320 <tr>
26321 <td><code>QTime</code></td>
26322 <td><code>TIME</code></td>
26323 <td><code>NULL</code></td>
26324 </tr>
26325
26326 <tr>
26327 <td><code>QDateTime</code></td>
26328 <td><code>DATETIME</code></td>
26329 <td><code>NULL</code></td>
26330 </tr>
26331 </table>
26332
26333 <p>Instances of the <code>QDate</code>, <code>QTime</code>, and
26334 <code>QDateTime</code> types are stored as a <code>NULL</code> value
26335 if their <code>isNull()</code> member function returns true.</p>
26336
26337 <p>The <code>date-time</code> sub-profile implementation also provides
26338 support for mapping <code>QDateTime</code> to the <code>TIMESTAMP</code>
26339 MySQL type. However, this mapping has to be explicitly requested using
26340 the <code>db&nbsp;type</code> pragma
26341 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), as shown in
26342 the following example:</p>
26343
26344 <pre class="cxx">
26345 #pragma db object
26346 class Person
26347 {
26348 ...
26349 #pragma db type("TIMESTAMP") not_null
26350 QDateTime updated_;
26351 };
26352 </pre>
26353
26354 <p>Starting with MySQL version 5.6.4 it is possible to store fractional
26355 seconds up to microsecond precision in <code>TIME</code>,
26356 <code>DATETIME</code>, and <code>TIMESTAMP</code> columns. However,
26357 to enable sub-second precision, the corresponding type with the
26358 desired precision has to be specified explicitly, as shown in the
26359 following example:</p>
26360
26361 <pre class="cxx">
26362 #pragma db object
26363 class Person
26364 {
26365 ...
26366 #pragma db type("DATETIME(3)") // Millisecond precision.
26367 QDateTime updated_;
26368 };
26369 </pre>
26370
26371 <p>Alternatively, you can enable sub-second precision on the per-type
26372 basis, for example:</p>
26373
26374 <pre class="cxx">
26375 #pragma db value(QDateTime) type("DATETIME(3)")
26376
26377 #pragma db object
26378 class Person
26379 {
26380 ...
26381 QDateTime created_; // Millisecond precision.
26382 QDateTime updated_; // Millisecond precision.
26383 };
26384 </pre>
26385
26386 <p>Some valid Qt date-time values cannot be stored in a MySQL database. An
26387 attempt to persist a Qt date-time value that is out of the MySQL type
26388 range will result in the <code>out_of_range</code> exception. Refer to
26389 the MySQL documentation for more information on the MySQL data type
26390 ranges.</p>
26391
26392 <h3><a name="24.4.2">24.4.2 SQLite Database Type Mapping</a></h3>
26393
26394 <p>The following table summarizes the default mapping between the currently
26395 supported Qt date-time types and the SQLite database types.</p>
26396
26397 <!-- border="1" is necessary for html2ps -->
26398 <table id="mapping" border="1">
26399 <tr>
26400 <th>Qt Date Time Type</th>
26401 <th>SQLite Type</th>
26402 <th>Default <code>NULL</code> Semantics</th>
26403 </tr>
26404
26405 <tr>
26406 <td><code>QDate</code></td>
26407 <td><code>TEXT</code></td>
26408 <td><code>NULL</code></td>
26409 </tr>
26410
26411 <tr>
26412 <td><code>QTime</code></td>
26413 <td><code>TEXT</code></td>
26414 <td><code>NULL</code></td>
26415 </tr>
26416
26417 <tr>
26418 <td><code>QDateTime</code></td>
26419 <td><code>TEXT</code></td>
26420 <td><code>NULL</code></td>
26421 </tr>
26422 </table>
26423
26424 <p>Instances of the <code>QDate</code>, <code>QTime</code>, and
26425 <code>QDateTime</code> types are stored as a <code>NULL</code> value
26426 if their <code>isNull()</code> member function returns true.</p>
26427
26428 <p>The <code>date-time</code> sub-profile implementation also provides
26429 support for mapping <code>QDate</code> and <code>QDateTime</code> to the
26430 SQLite <code>INTEGER</code> type, with the integer value representing the
26431 UNIX time. Similarly, an alternative mapping for <code>QTime</code> to
26432 the <code>INTEGER</code> type represents a clock time as the number of
26433 seconds since midnight. These mappings have to be explicitly requested
26434 using the <code>db&nbsp;type</code> pragma
26435 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), as shown
26436 in the following example:</p>
26437
26438 <pre class="cxx">
26439 #pragma db object
26440 class Person
26441 {
26442 ...
26443 #pragma db type("INTEGER")
26444 QDate born_;
26445 };
26446 </pre>
26447
26448 <p>Some valid Qt date-time values cannot be stored in an SQLite database.
26449 An attempt to persist any Qt date-time value representing a negative UNIX
26450 time (any point in time prior to the 1970-01-01&nbsp;00:00:00 UNIX time
26451 epoch) as an SQLite <code>INTEGER</code> will result in the
26452 <code>out_of_range</code> exception.</p>
26453
26454 <h3><a name="24.4.3">24.4.3 PostgreSQL Database Type Mapping</a></h3>
26455
26456 <p>The following table summarizes the default mapping between the currently
26457 supported Qt date-time types and the PostgreSQL database types.</p>
26458
26459 <!-- border="1" is necessary for html2ps -->
26460 <table id="mapping" border="1">
26461 <tr>
26462 <th>Qt Date Time Type</th>
26463 <th>PostgreSQL Type</th>
26464 <th>Default <code>NULL</code> Semantics</th>
26465 </tr>
26466
26467 <tr>
26468 <td><code>QDate</code></td>
26469 <td><code>DATE</code></td>
26470 <td><code>NULL</code></td>
26471 </tr>
26472
26473 <tr>
26474 <td><code>QTime</code></td>
26475 <td><code>TIME</code></td>
26476 <td><code>NULL</code></td>
26477 </tr>
26478
26479 <tr>
26480 <td><code>QDateTime</code></td>
26481 <td><code>TIMESTAMP</code></td>
26482 <td><code>NULL</code></td>
26483 </tr>
26484 </table>
26485
26486 <p>Instances of the <code>QDate</code>, <code>QTime</code>, and
26487 <code>QDateTime</code> types are stored as a <code>NULL</code> value
26488 if their <code>isNull()</code> member function returns true.</p>
26489
26490 <h3><a name="24.4.4">24.4.4 Oracle Database Type Mapping</a></h3>
26491
26492 <p>The following table summarizes the default mapping between the currently
26493 supported Qt date-time types and the Oracle database types.</p>
26494
26495 <!-- border="1" is necessary for html2ps -->
26496 <table id="mapping" border="1">
26497 <tr>
26498 <th>Qt Date Time Type</th>
26499 <th>Oracle Type</th>
26500 <th>Default <code>NULL</code> Semantics</th>
26501 </tr>
26502
26503 <tr>
26504 <td><code>QDate</code></td>
26505 <td><code>DATE</code></td>
26506 <td><code>NULL</code></td>
26507 </tr>
26508
26509 <tr>
26510 <td><code>QTime</code></td>
26511 <td><code>INTERVAL DAY(0) TO SECOND(3)</code></td>
26512 <td><code>NULL</code></td>
26513 </tr>
26514
26515 <tr>
26516 <td><code>QDateTime</code></td>
26517 <td><code>TIMESTAMP(3)</code></td>
26518 <td><code>NULL</code></td>
26519 </tr>
26520 </table>
26521
26522 <p>Instances of the <code>QDate</code>, <code>QTime</code>, and
26523 <code>QDateTime</code> types are stored as a <code>NULL</code> value
26524 if their <code>isNull()</code> member function returns true.</p>
26525
26526 <p>The <code>date-time</code> sub-profile implementation also provides
26527 support for mapping <code>QDateTime</code> to the
26528 <code>DATE</code> Oracle type with fractional seconds that may be
26529 stored in a <code>QDateTime</code> instance being ignored. This
26530 alternative mapping has to be explicitly requested using the
26531 <code>db&nbsp;type</code> pragma (<a href="#14.4.3">Section 14.4.3,
26532 "<code>type</code>"</a>), as shown in the following example:</p>
26533
26534 <pre class="cxx">
26535 #pragma db object
26536 class person
26537 {
26538 ...
26539 #pragma db type("DATE")
26540 QDateTime updated_;
26541 };
26542 </pre>
26543
26544 <h3><a name="24.4.5">24.4.5 SQL Server Database Type Mapping</a></h3>
26545
26546 <p>The following table summarizes the default mapping between the currently
26547 supported Qt date-time types and the SQL Server database types.</p>
26548
26549 <!-- border="1" is necessary for html2ps -->
26550 <table id="mapping" border="1">
26551 <tr>
26552 <th>Qt Date Time Type</th>
26553 <th>SQL Server Type</th>
26554 <th>Default <code>NULL</code> Semantics</th>
26555 </tr>
26556
26557 <tr>
26558 <td><code>QDate</code></td>
26559 <td><code>DATE</code></td>
26560 <td><code>NULL</code></td>
26561 </tr>
26562
26563 <tr>
26564 <td><code>QTime</code></td>
26565 <td><code>TIME(3)</code></td>
26566 <td><code>NULL</code></td>
26567 </tr>
26568
26569 <tr>
26570 <td><code>QDateTime</code></td>
26571 <td><code>DATETIME2(3)</code></td>
26572 <td><code>NULL</code></td>
26573 </tr>
26574 </table>
26575
26576 <p>Instances of the <code>QDate</code>, <code>QTime</code>, and
26577 <code>QDateTime</code> types are stored as a <code>NULL</code> value
26578 if their <code>isNull()</code> member function returns true.</p>
26579
26580 <p>Note that the <code>DATE</code>, <code>TIME</code>, and
26581 <code>DATETIME2</code> types are only available in SQL Server 2008 and
26582 later. SQL Server 2005 only supports the <code>DATETIME</code> and
26583 <code>SMALLDATETIME</code> date-time types. The new types are
26584 also unavailable when connecting to an SQL Server 2008 or
26585 later with the SQL Server 2005 Native Client ODBC driver.</p>
26586
26587 <p>The <code>date-time</code> sub-profile implementation provides
26588 support for mapping <code>QDateTime</code> to the <code>DATETIME</code>
26589 and <code>SMALLDATETIME</code> types, however, this mapping has to
26590 be explicitly requested using the <code>db&nbsp;type</code> pragma
26591 (<a href="#14.4.3">Section 14.4.3, "<code>type</code>"</a>), as
26592 shown in the following example:</p>
26593
26594 <pre class="cxx">
26595 #pragma db object
26596 class person
26597 {
26598 ...
26599 #pragma db type("DATETIME")
26600 QDateTime updated_;
26601 };
26602 </pre>
26603
26604 </div>
26605 </div>
26606
26607 </body>
26608 </html>