1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
<TITLE>Transactions and Other Access Contexts
</TITLE>
<SCRIPT type="text/javascript" src="../../../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="4"><!-- Empty --></A>
<H2>4 Transactions and Other Access Contexts
</H2>
<P>This chapter describes the Mnesia transaction system and the
transaction properties which make Mnesia a fault tolerant,
distributed database management system.
<P>Also covered in this chapter are the locking functions,
including table locks and sticky locks, as well as alternative
functions which bypass the transaction system in favor of improved
speed and reduced overheads. These functions are called "dirty
operations". We also describe the usage of nested transactions.
This chapter contains the following sections:
<P>
<UL>
<LI>
transaction properties, which include atomicity,
consistency, isolation, and durability
</LI>
<LI>
Locking
</LI>
<LI>
Dirty operations
</LI>
<LI>
Record names vs table names
</LI>
<LI>
Activity concept and various access contexts
</LI>
<LI>
Nested transactions
</LI>
<LI>
Pattern matching
</LI>
<LI>
Iteration
</LI>
</UL>
<A NAME="trans_prop"><!-- Empty --></A><A NAME="4.1"><!-- Empty --></A>
<H3>4.1 Transaction Properties</H3>
<P>Transactions are an important tool when designing fault
tolerant, distributed systems. A Mnesia transaction is a mechanism
by which a series of database operations can be executed as one
functional block. The functional block which is run as a
transaction is called a Functional Object (Fun), and this code can
read, write, or delete Mnesia records. The Fun is evaluated as a
transaction which either commits, or aborts. If a transaction
succeeds in executing Fun it will replicate the action on all nodes
involved, or abort if an error occurs.
<P>The following example shows a transaction which raises the
salary of certain employee numbers.
<PRE>
raise(Eno, Raise) ->
F = fun() ->
[E] = mnesia:read(employee, Eno, write),
Salary = E#employee.salary + Raise,
New = E#employee{salary = Salary},
mnesia:write(New)
end,
mnesia:transaction(F).
</PRE>
<P>The transaction <CODE>raise(Eno, Raise) - ></CODE> contains a Fun
made up of four lines of code. This Fun is called by the statement
<CODE>mnesia:transaction(F)</CODE> and returns a value.
<P>The Mnesia transaction system facilitates the construction of
reliable, distributed systems by providing the following important
properties:
<P>
<UL>
<LI>
The transaction handler ensures that a Fun which is placed
inside a transaction does not interfere with operations embedded
in other transactions when it executes a series of operations on
tables.
</LI>
<LI>
The transaction handler ensures that either all operations
in the transaction are performed successfully on all nodes
atomically, or the transaction fails without permanent effect on
any of the nodes.
</LI>
<LI>
The Mnesia transactions have four important properties,
which we call <STRONG>A</STRONG>tomicity,
<STRONG>C</STRONG>onsistency,<STRONG>I</STRONG>solation, and
<STRONG>D</STRONG>urability, or ACID for short. These properties are
described in the following sub-sections.
</LI>
</UL>
<A NAME="4.1.1"><!-- Empty --></A>
<H4>4.1.1 Atomicity</H4>
<P><STRONG>Atomicity</STRONG> means that database changes which are
executed by a transaction take effect on all nodes involved, or
on none of the nodes. In other words, the transaction either
succeeds entirely, or it fails entirely.
<P>Atomicity is particularly important when we want to
atomically write more than one record in the same
transaction. The <CODE>raise/2</CODE> function, shown as an example
above, writes one record only. The <CODE>insert_emp/3</CODE> function,
shown in the program listing in Chapter 2, writes the record
<CODE>employee</CODE> as well as employee relations such as
<CODE>at_dep</CODE> and <CODE>in_proj</CODE> into the database. If we run
this latter code inside a transaction, then the transaction
handler ensures that the transaction either succeeds completely,
or not at all.
<P>Mnesia is a distributed DBMS where data can be replicated on
several nodes. In many such applications, it is important that a
series of write operations are performed atomically inside a
transaction. The atomicity property ensures that a transaction
take effect on all nodes, or none at all.
<A NAME="4.1.2"><!-- Empty --></A>
<H4>4.1.2 Consistency</H4>
<P><STRONG>Consistency</STRONG>. This transaction property ensures that
a transaction always leaves the DBMS in a consistent state. For
example, Mnesia ensures that inconsistencies will not occur if
Erlang, Mnesia or the computer crashes while a write operation
is in progress.
<A NAME="4.1.3"><!-- Empty --></A>
<H4>4.1.3 Isolation</H4>
<P><STRONG>Isolation</STRONG>. This transaction property ensures that
transactions which execute on different nodes in a network, and
access and manipulate the same data records, will not interfere
with each other.
<P>The isolation property makes it possible to concurrently execute
the <CODE>raise/2</CODE> function. A classical problem in concurrency control
theory is the so called "lost update problem".
<P>The isolation property is extremely useful if the following
circumstances occurs where an employee (with an employee number
123) and two processes, (P1 and P2), are concurrently trying to
raise the salary for the employee. The initial value of the
employees salary is, for example, 5. Process P1 then starts to execute,
it reads the employee record and adds 2 to the salary. At this
point in time, process P1 is for some reason preempted and
process P2 has the opportunity to run. P2 reads the record, adds 3
to the salary, and finally writes a new employee record with
the salary set to 8. Now, process P1 start to run again and
writes its employee record with salary set to 7, thus
effectively overwriting and undoing the work performed by
process P2. The update performed by P2 is lost.
<P>A transaction system makes it possible to concurrently
execute two or more processes which manipulate the same
record. The programmer does not need to check that the
updates are synchronous, this is overseen by the
transaction handler. All programs accessing the database through
the transaction system may be written as if they had sole access
to the data.
<A NAME="4.1.4"><!-- Empty --></A>
<H4>4.1.4 Durability</H4>
<P><STRONG>Durability</STRONG>. This transaction property ensures that
changes made to the DBMS by a transaction are permanent. Once a
transaction has been committed, all changes made to the database
are durable - i.e. they are written safely to disc and will not
be corrupted or disappear.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P>The durability feature described does not entirely apply to
situations where Mnesia is configured as a "pure" primary memory
database.
</TD>
</TR>
</TABLE>
<A NAME="4.2"><!-- Empty --></A>
<H3>4.2 Locking</H3>
<P>Different transaction managers employ different strategies to
satisfy the isolation property. Mnesia uses the standard technique
of two-phase locking. This means that locks are set on records
before they are read or written. Mnesia uses five different kinds
of locks.
<P>
<UL>
<LI>
<STRONG>Read locks</STRONG>. A read lock is set on one replica of
a record before it can be read.
</LI>
<LI>
<STRONG>Write locks</STRONG>. Whenever a transaction writes to an
record, write locks are first set on all replicas of that
particular record.
</LI>
<LI>
<STRONG>Read table locks</STRONG>. If a transaction traverses an
entire table in search for a record which satisfy some
particular property, it is most inefficient to set read locks on
the records, one by one. It is also very memory consuming, since
the read locks themselves may take up considerable space if the
table is very large. For this reason, Mnesia can set a read lock
on an entire table.
</LI>
<LI>
<STRONG>Write table locks</STRONG>. If a transaction writes a
large number of records to one table, it is possible to set a
write lock on the entire table.
</LI>
<LI>
<STRONG>Sticky locks</STRONG>. These are write locks that stay in
place at a node after the transaction which initiated the lock
has terminated.
</LI>
</UL>
<P>Mnesia employs a strategy whereby functions such as
<CODE>mnesia:read/1</CODE> acquire the necessary locks dynamically as
the transactions execute. Mnesia automatically sets and releases
the locks and the programmer does not have to code these
operations.
<P>Deadlocks can occur when concurrent processes set and release
locks on the same records. Mnesia employs a "wait-die" strategy to
resolve these situations. If Mnesia suspects that a deadlock can
occur when a transaction tries to set a lock, the transaction is
forced to release all its locks and sleep for a while. The
Fun in the transaction will be evaluated one more time.
<P>For this reason, it is important that the code inside the Fun given to
<CODE>mnesia:transaction/1</CODE> is pure. Some strange results can
occur if, for example, messages are sent by the transaction
Fun. The following example illustrates this situation:
<PRE>
bad_raise(Eno, Raise) ->
F = fun() ->
[E] = mnesia:read({employee, Eno}),
Salary = E#employee.salary + Raise,
New = E#employee{salary = Salary},
io:format("Trying to write ... ~n", []),
mnesia:write(New)
end,
mnesia:transaction(F).
</PRE>
<P>This transaction could write the text <CODE>"Trying to write
... "</CODE> a thousand times to the terminal. Mnesia does guarantee,
however, that each and every transaction will eventually run. As a
result, Mnesia is not only deadlock free, but also livelock
free.
<P>The Mnesia programmer cannot prioritize one particular
transaction to execute before other transactions which are waiting
to execute. As a result, the Mnesia DBMS transaction system is not
suitable for hard real time applications. However, Mnesia contains
other features that have real time properties.
<P>Mnesia dynamically sets and releases locks as
transactions execute, therefore, it is very dangerous to execute code with
transaction side-effects. In particular, a <CODE>receive</CODE>
statement inside a transaction can lead to a situation where the
transaction hangs and never returns, which in turn can cause locks
not to release. This situation could bring the whole system to a
standstill since other transactions which execute in other
processes, or on other nodes, are forced to wait for the defective
transaction.
<P>If a transaction terminates abnormally, Mnesia will
automatically release the locks held by the transaction.
<P>We have shown examples of a number of functions that can be
used inside a transaction. The following list shows the
<STRONG>simplest</STRONG> Mnesia functions that work with transactions. It
is important to realize that these functions must be embedded in a
transaction. If no enclosing transaction (or other enclosing
Mnesia activity) exists, they will all fail.
<P>
<UL>
<LI>
<CODE>mnesia:transaction(Fun) -> {aborted, Reason} |{atomic,
Value}</CODE>. This function executes one transaction with the
functional object <CODE>Fun</CODE> as the single parameter.
</LI>
<LI>
<CODE>mnesia:read({Tab, Key}) -> transaction abort |
RecordList</CODE>. This function reads all records with <CODE>Key</CODE>
as key from table <CODE>Tab</CODE>. This function has the same semantics
regardless of the location of <CODE>Table</CODE>. If the table is of
type <CODE>bag</CODE>, the <CODE>read({Tab, Key})</CODE> can return an arbitrarily
long list. If the table is of type <CODE>set</CODE>, the list is
either of length one, or <CODE>[]</CODE>.
</LI>
<LI>
<CODE>mnesia:wread({Tab, Key}) -> transaction abort |
RecordList</CODE>. This function behaves the same way as the
previously listed <CODE>read/1</CODE> function, except that it
acquires a write lock instead of a read lock. If we execute a
transaction which reads a record, modifies the record, and then
writes the record, it is slightly more efficient to set the
write lock immediately. In cases where we issue a
<CODE>mnesia:read/1</CODE>, followed by a <CODE>mnesia:write/1</CODE>, the
first read lock must be upgraded to a write lock when the write
operation is executed.
</LI>
<LI>
<CODE>mnesia:write(Record) -> transaction abort |
ok</CODE>. This function writes a record into the database. The
<CODE>Record</CODE> argument is an instance of a record. The function
returns <CODE>ok</CODE>, or aborts the transaction if an error should
occur.
</LI>
<LI>
<CODE>mnesia:delete({Tab, Key}) -> transaction abort | ok</CODE>. This
function deletes all records with the given key.
</LI>
<LI>
<CODE>mnesia:delete_object(Record) -> transaction abort |
ok</CODE>. This function deletes records with object id
<CODE>Record</CODE>. This function is used when we want to delete only
some records in a table of type <CODE>bag</CODE>.
</LI>
</UL>
<A NAME="4.2.1"><!-- Empty --></A>
<H4>4.2.1 Sticky Locks</H4>
<P>As previously stated, the locking strategy used by Mnesia is
to lock one record when we read a record, and lock all replicas
of a record when we write a record. However, there are
applications which use Mnesia mainly for its fault-tolerant
qualities, and these applications may be configured with one
node doing all the heavy work, and a standby node which is ready
to take over in case the main node fails. Such applications may
benefit from using sticky locks instead of the normal locking
scheme.
<P>A sticky lock is a lock which stays in place at a node after
the transaction which first acquired the lock has terminated. To
illustrate this, assume that we execute the following
transaction:
<PRE>
F = fun() ->
mnesia:write(#foo{a = kalle})
end,
mnesia:transaction(F).
</PRE>
<P>The <CODE>foo</CODE> table is replicated on the two nodes <CODE>N1</CODE>
and <CODE>N2</CODE>.
<BR>
Normal locking requires:
<P>
<UL>
<LI>
one network rpc (2 messages) to acquire the write lock
</LI>
<LI>
three network messages to execute the two-phase commit protocol.
</LI>
</UL>
<P>If we use sticky locks, we must first change the code as follows:
<PRE>
F = fun() ->
mnesia:s_write(#foo{a = kalle})
end,
mnesia:transaction(F).
</PRE>
<P>This code uses the <CODE>s_write/1</CODE> function instead of the
<CODE>write/1</CODE> function. The <CODE>s_write/1</CODE> function sets a
sticky lock instead of a normal lock. If the table is not
replicated, sticky locks have no special effect. If the table is
replicated, and we set a sticky lock on node <CODE>N1</CODE>, this
lock will then stick to node <CODE>N1</CODE>. The next time we try to
set a sticky lock on the same record at node <CODE>N1</CODE>, Mnesia
will see that the lock is already set and will not do a network
operation in order to acquire the lock.
<P>It is much more efficient to set a local lock than it is to set
a networked lock, and for this reason sticky locks can benefit
application that use a replicated table and perform most of the
work on only one of the nodes.
<P>If a record is stuck at node <CODE>N1</CODE> and we try to set a
sticky lock for the record on node <CODE>N2</CODE>, the record must be
unstuck. This operation is expensive and will reduce performance. The unsticking is
done automatically if we issue <CODE>s_write/1</CODE> requests at
<CODE>N2</CODE>.
<A NAME="4.2.2"><!-- Empty --></A>
<H4>4.2.2 Table Locks</H4>
<P>Mnesia supports read and write locks on whole tables as a
complement to the normal locks on single records. As previously
stated, Mnesia sets and releases locks automatically, and the
programmer does not have to code these operations. However,
transactions which read and write a large number of records in a
specific table will execute more efficiently if we start the
transaction by setting a table lock on this table. This will
block other concurrent transactions from the table. The
following two function are used to set explicit table locks for
read and write operations:
<P>
<UL>
<LI>
<CODE>mnesia:read_lock_table(Tab)</CODE> Sets a read lock on
the table <CODE>Tab</CODE>
</LI>
<LI>
<CODE>mnesia:write_lock_table(Tab)</CODE> Sets a write lock on
the table <CODE>Tab</CODE>
</LI>
</UL>
<P>Alternate syntax for acquisition of table locks is as follows:
<PRE>
mnesia:lock({table, Tab}, read)
mnesia:lock({table, Tab}, write)
</PRE>
<P>The matching operations in Mnesia may either lock the entire
table or just a single record (when the key is bound in the
pattern).
<A NAME="4.2.3"><!-- Empty --></A>
<H4>4.2.3 Global Locks</H4>
<P>Write locks are normally acquired on all nodes where a
replica of the table resides (and is active). Read locks are
acquired on one node (the local one if a local
replica exists).
<P>The function <CODE>mnesia:lock/2</CODE> is intended to support
table locks (as mentioned previously)
but also for situations when locks need to be
acquired regardless of how tables have been replicated:
<PRE>
mnesia:lock({global, GlobalKey, Nodes}, LockKind)
LockKind ::= read | write | ...
</PRE>
<P>The lock is acquired on the LockItem on all Nodes in the
nodes list.
<A NAME="4.3"><!-- Empty --></A>
<H3>4.3 Dirty Operations</H3>
<P>In many applications, the overhead of processing a transaction
may result in a loss of performance. Dirty operation are short
cuts which bypass much of the processing and increase the speed
of the transaction.
<P>Dirty operation are useful in many situations, for example in a datagram routing
application where Mnesia stores the routing table, and it is time
consuming to start a whole transaction every time a packet is
received. For this reason, Mnesia has functions which manipulate
tables without using transactions. This alternative
to processing is known as a dirty operation. However, it is important to
realize the trade-off in avoiding the overhead of transaction
processing:
<P>
<UL>
<LI>
The atomicity and the isolation properties of Mnesia are lost.
</LI>
<LI>
The isolation property is compromised, because other
Erlang processes, which use transaction to manipulate the data,
do not get the benefit of isolation if we simultaneously use
dirty operations to read and write records from the same table.
</LI>
</UL>
<P>The major advantage of dirty operations is that they execute
much faster than equivalent operations that are processed as
functional objects within a transaction.
<P>Dirty operations
are written to disc if they are performed on a table of type
<CODE>disc_copies</CODE>, or type <CODE>disc_only_copies</CODE>. Mnesia also
ensures that all replicas of a table are updated if a
dirty write operation is performed on a table.
<P>A dirty operation will ensure a certain level of consistency.
For example, it is not possible for dirty operations to return
garbled records. Hence, each individual read or write operation
is performed in an atomic manner.
<P>All dirty functions execute a call to <CODE>exit({aborted,
Reason})</CODE> on failure. Even if the following functions are
executed inside a transaction no locks will be aquired. The
following functions are available:
<P>
<UL>
<LI>
<CODE>mnesia:dirty_read({Tab, Key})</CODE>. This function reads
record(s) from Mnesia.
</LI>
<LI>
<CODE>mnesia:dirty_write(Record)</CODE>. This function writes
the record <CODE>Record</CODE>
</LI>
<LI>
<CODE>mnesia:dirty_delete({Tab, Key})</CODE>. This function deletes
record(s) with the key <CODE>Key</CODE>.
</LI>
<LI>
<CODE>mnesia:dirty_delete_object(Record)</CODE> This function is
the dirty operation alternative to the function
<CODE>delete_object/1</CODE>
</LI>
<LI>
<CODE>mnesia:dirty_first(Tab)</CODE>. This function returns the
"first" key in the table <CODE>Tab</CODE>.
Records in <CODE>set</CODE> or <CODE>bag</CODE> tables are not sorted.
However, there is
a record order which is not known to the user.
This means that it is possible to traverse a table by means of
this function in conjunction with the <CODE>dirty_next/2</CODE>
function.
<BR>
If there are no records at all in the table, this function
will return the atom <CODE>'$end_of_table'</CODE>. It is not
recommended to use this atom as the key for any user
records.
<BR>
</LI>
<LI>
<CODE>mnesia:dirty_next(Tab, Key)</CODE>. This function returns
the "next" key in the table <CODE>Tab</CODE>. This function makes it
possible to traverse a table and perform some operation on all
records in the table. When the end of the table is reached the
special key <CODE>'$end_of_table'</CODE> is returned. Otherwise, the
function returns a key which can be used to read the actual
record.
<BR>
The behavior is undefined if any process perform a write
operation on the table while we traverse the table with the
<CODE>dirty_next/2</CODE> function. This is because <CODE>write</CODE>
operations on a Mnesia table may lead to internal reorganizations
of the table itself. This is an implementation detail, but remember
the dirty functions are low level functions.
</LI>
<LI>
<CODE>mnesia:dirty_last(Tab)</CODE> This function works exactly as
<CODE>mnesia:dirty_first/1</CODE> but returns the last object in
Erlang term order for the <CODE>ordered_set</CODE> table type. For
all other table types, <CODE>mnesia:dirty_first/1</CODE> and
<CODE>mnesia:dirty_last/1</CODE> are synonyms.
</LI>
<LI>
<CODE>mnesia:dirty_prev(Tab, Key)</CODE> This function works exactly as
<CODE>mnesia:dirty_next/2</CODE> but returns the previous object in
Erlang term order for the ordered_set table type. For
all other table types, <CODE>mnesia:dirty_next/2</CODE> and
<CODE>mnesia:dirty_prev/2</CODE> are synonyms.
</LI>
<LI>
<CODE>mnesia:dirty_slot(Tab, Slot)</CODE>
<BR>
Returns the list of records that are associated with Slot
in a table. It can be used to traverse a table in a manner
similar to the <CODE>dirty_next/2</CODE> function. A table has a
number of slots that range from zero to some unknown upper
bound. The function <CODE>dirty_slot/2</CODE> returns the special
atom <CODE>'$end_of_table'</CODE> when the end of the table is
reached.
<BR>
The behavior of this function is undefined if the
table is written on while being
traversed. <CODE>mnesia:read_lock_table(Tab)</CODE> may be used to
ensure that no transaction protected writes are performed
during the iteration.
<BR>
</LI>
<LI>
<CODE>mnesia:dirty_update_counter({Tab,Key}, Val)</CODE>.
Counters are positive integers with a value greater than or
equal to zero. Updating a counter will add the <CODE> Val</CODE> and
the counter where <CODE>Val</CODE> is a positive or negative integer.
<BR>
There exists no special counter records in
Mnesia. However, records on the form of <CODE>{TabName, Key,
Integer}</CODE> can be used as counters, and can be
persistent.
<BR>
It is not possible to have transaction protected updates of
counter records.
<BR>
There are two significant differences when using this
function instead of reading the record, performing the
arithmetic, and writing the record:
<BR>
<OL>
<LI>
it is much more efficient
</LI>
<LI>
the <CODE>dirty_update_counter/2</CODE> function is
performed as an atomic operation although it is not protected by
a transaction. Accordingly, no table update is lost if two
processes simultaneously execute the
<CODE>dirty_update_counter/2</CODE> function.
</LI>
</OL>
</LI>
<LI>
<CODE>mnesia:dirty_match_object(Pat)</CODE>. This function is
the dirty equivalent of <CODE>mnesia:match_object/1</CODE>.
</LI>
<LI>
<CODE>mnesia:dirty_select(Tab, Pat)</CODE>. This function is
the dirty equivalent of <CODE>mnesia:select/2</CODE>.
</LI>
<LI>
<CODE>mnesia:dirty_index_match_object(Pat, Pos)</CODE>. This
function is the dirty equivalent of
<CODE>mnesia:index_match_object/2</CODE>.
</LI>
<LI>
<CODE>mnesia:dirty_index_read(Tab, SecondaryKey, Pos)</CODE>. This
function is the dirty equivalent of <CODE>mnesia:index_read/3</CODE>.
</LI>
<LI>
<CODE>mnesia:dirty_all_keys(Tab)</CODE>. This function is the
dirty equivalent of <CODE>mnesia:all_keys/1</CODE>.
</LI>
</UL>
<A NAME="recordnames_tablenames"><!-- Empty --></A><A NAME="4.4"><!-- Empty --></A>
<H3>4.4 Record Names versus Table Names</H3>
<P>In Mnesia, all records in a table must have the same name. All
the records must be instances of the same
record type. The record name does however not necessarily be
the same as the table name. Even though that it is the case in
the most of the examples in this document. If a table is created
without the <CODE>record_name</CODE> property the code below will
ensure all records in the tables have the same name as the table:
<PRE>
mnesia:create_table(subscriber, [])
</PRE>
<P>However, if the table is is created with an explicit record name
as argument, as shown below, it is possible to store subscriber
records in both of the tables regardless of the table names:
<PRE>
TabDef = [{record_name, subscriber}],
mnesia:create_table(my_subscriber, TabDef),
mnesia:create_table(your_subscriber, TabDef).
</PRE>
<P> In order to access such
tables it is not possible to use the simplified access functions
as described earlier in the document. For example,
writing a subscriber record into a table requires a
<CODE>mnesia:write/3</CODE>function instead of the simplified functions
<CODE>mnesia:write/1</CODE> and <CODE>mnesia:s_write/1</CODE>:
<PRE>
mnesia:write(subscriber, #subscriber{}, write)
mnesia:write(my_subscriber, #subscriber{}, sticky_write)
mnesia:write(your_subscriber, #subscriber{}, write)
</PRE>
<P>The following simplified piece of code illustrates the
relationship between the simplified access functions used in
most examples and their more flexible counterparts:
<PRE>
mnesia:dirty_write(Record) ->
Tab = element(1, Record),
mnesia:dirty_write(Tab, Record).
mnesia:dirty_delete({Tab, Key}) ->
mnesia:dirty_delete(Tab, Key).
mnesia:dirty_delete_object(Record) ->
Tab = element(1, Record),
mnesia:dirty_delete_object(Tab, Record)
mnesia:dirty_update_counter({Tab, Key}, Incr) ->
mnesia:dirty_update_counter(Tab, Key, Incr).
mnesia:dirty_read({Tab, Key}) ->
Tab = element(1, Record),
mnesia:dirty_read(Tab, Key).
mnesia:dirty_match_object(Pattern) ->
Tab = element(1, Pattern),
mnesia:dirty_match_object(Tab, Pattern).
mnesia:dirty_index_match_object(Pattern, Attr)
Tab = element(1, Pattern),
mnesia:dirty_index_match_object(Tab, Pattern, Attr).
mnesia:write(Record) ->
Tab = element(1, Record),
mnesia:write(Tab, Record, write).
mnesia:s_write(Record) ->
Tab = element(1, Record),
mnesia:write(Tab, Record, sticky_write).
mnesia:delete({Tab, Key}) ->
mnesia:delete(Tab, Key, write).
mnesia:s_delete({Tab, Key}) ->
mnesia:delete(Tab, Key, sticky_write).
mnesia:delete_object(Record) ->
Tab = element(1, Record),
mnesia:delete_object(Tab, Record, write).
mnesia:s_delete_object(Record) ->
Tab = element(1, Record),
mnesia:delete_object(Tab, Record. sticky_write).
mnesia:read({Tab, Key}) ->
mnesia:read(Tab, Key, read).
mnesia:wread({Tab, Key}) ->
mnesia:read(Tab, Key, write).
mnesia:match_object(Pattern) ->
Tab = element(1, Pattern),
mnesia:match_object(Tab, Pattern, read).
mnesia:index_match_object(Pattern, Attr) ->
Tab = element(1, Pattern),
mnesia:index_match_object(Tab, Pattern, Attr, read).
</PRE>
<A NAME="4.5"><!-- Empty --></A>
<H3>4.5 Activity Concept and Various Access Contexts</H3>
<P>As previously described, a functional object (Fun) performing
table access operations as listed below may be
passed on as arguments to the function
<CODE>mnesia:transaction/1,2,3</CODE>:
<P>
<UL>
<LI>
mnesia:write/3 (write/1, s_write/1)
<BR>
</LI>
<LI>
mnesia:delete/3 (delete/1, s_delete/1)
<BR>
</LI>
<LI>
mnesia:delete_object/3 (delete_object/1, s_delete_object/1)
<BR>
</LI>
<LI>
mnesia:read/3 (read/1, wread/1)
<BR>
</LI>
<LI>
mnesia:match_object/2 (match_object/1)
<BR>
</LI>
<LI>
mnesia:select/3 (select/2)
<BR>
</LI>
<LI>
mnesia:foldl/3 (foldl/4, foldr/3, foldr/4)
<BR>
</LI>
<LI>
mnesia:all_keys/1
<BR>
</LI>
<LI>
mnesia:index_match_object/4 (index_match_object/2)
<BR>
</LI>
<LI>
mnesia:index_read/3
<BR>
</LI>
<LI>
mnesia:lock/2 (read_lock_table/1, write_lock_table/1)
<BR>
</LI>
<LI>
mnesia:table_info/2
<BR>
</LI>
</UL>
<P>These functions will be performed in a
transaction context involving mechanisms like locking, logging,
replication, checkpoints, subscriptions, commit protocols
etc.However, the same function may also be
evaluated in other activity contexts.
<BR>
The following activity access contexts are currently supported:
<P>
<UL>
<LI>
transaction
<BR>
</LI>
<LI>
sync_transaction
<BR>
</LI>
<LI>
async_dirty
<BR>
</LI>
<LI>
sync_dirty
<BR>
</LI>
<LI>
ets
<BR>
</LI>
</UL>
<P>By passing the same "fun" as argument to the function
<CODE>mnesia:sync_transaction(Fun [, Args])</CODE> it will be performed
in synced transaction context. Synced transactions waits until all
active replicas has committed the transaction (to disc) before
returning from the mnesia:sync_transaction call. Using
sync_transaction is useful for applications that are executing on
several nodes and want to be sure that the update is performed on
the remote nodes before a remote process is spawned or a message
is sent to a remote process, and also when combining transaction
writes with dirty_reads. This is also useful in situations where
an application performs frequent or voluminous updates which may
overload Mnesia on other nodes.
<P>By passing the same "fun" as argument to the function
<CODE>mnesia:async_dirty(Fun [, Args])</CODE> it will be performed in
dirty context. The function calls will be mapped to the
corresponding dirty functions. This will still involve logging,
replication and subscriptions but there will be no locking,
local transaction storage or commit protocols involved.
Checkpoint retainers will be updated but will be updated
"dirty". Thus, they will be updated asynchronously. The
functions will wait for the operation to be performed on one
node but not the others. If the table resides locally no waiting
will occur.
<P>By passing the same "fun" as an argument to the function
<CODE>mnesia:sync_dirty(Fun [, Args])</CODE> it will be performed in
almost the same context as <CODE>mnesia:async_dirty/1,2</CODE>. The
difference is that the operations are performed
synchronously. The caller will wait for the updates to be
performed on all active replicas. Using sync_dirty is useful for
applications that are executing on several nodes and want to be
sure that the update is performed on the remote nodes before a remote
process is spawned or a message is sent to a remote process. This
is also useful in situations where an application performs frequent or
voluminous updates which may overload Mnesia on other
nodes.
<P>Mnesia tables with storage type RAM_copies and disc_copies
are implemented internally as "ets-tables" and
it is possible for applications to access the these tables
directly. This is only recommended if all options have been weighed
and the possible outcomes are understood. By passing the earlier
mentioned "fun" to the function
<CODE>mnesia:ets(Fun [, Args])</CODE> it will be performed but in a very raw
context. The operations will be performed directly on the
local ets tables assuming that the local storage type are
RAM_copies and that the table is not replicated on other
nodes. Subscriptions will not be triggered nor
checkpoints updated, but this operation is blindingly fast. Disc resident
tables should not be updated with the ets-function since the
disc will not be updated.
<P>The Fun may also be passed as an argument to the function
<CODE>mnesia:activity/2,3,4</CODE> which enables usage of customized
activity access callback modules. It can either be obtained
directly by stating the module name as argument or implicitly
by usage of the <CODE>access_module</CODE> configuration parameter. A
customized callback module may be used for several purposes,
such as providing triggers, integrity constraints, run time
statistics, or virtual tables.
<BR>
The callback module does
not have to access real Mnesia tables, it is free to do whatever
it likes as long as the callback interface is fulfilled.
<BR>
In Appendix C "The Activity Access Call Back Interface" the source
code for one alternate implementation is provided
(mnesia_frag.erl). The context sensitive function
<CODE>mnesia:table_info/2</CODE> may be used to provide virtual
information about a table. One usage of this is to perform
<CODE>QLC</CODE> queries within an activity context with a
customized callback module. By providing table information about
table indices and other <CODE>QLC</CODE> requirements,
<CODE>QLC</CODE> may be used as a generic query language to
access virtual tables.
<P>QLC queries may be performed in all these activity
contexts (transaction, sync_transaction, async_dirty, sync_dirty
and ets). The ets activity will only work if the table has no
indices.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P> The mnesia:dirty_* function always executes with
async_dirty semantics regardless of which activity access contexts
are invoked. They may even invoke contexts without any
enclosing activity access context.
</TD>
</TR>
</TABLE>
<A NAME="4.6"><!-- Empty --></A>
<H3>4.6 Nested transactions</H3>
<P>Transactions may be nested in an arbitrary fashion. A child transaction
must run in the same process as its parent. When a child transaction
aborts, the caller of the child transaction will get the
return value <CODE>{aborted, Reason}</CODE> and any work performed
by the child will be erased. If a child transaction commits, the
records written by the child will be propagated to the parent.
<P>No locks are released when child transactions terminate. Locks
created by a sequence of nested transactions are kept until
the topmost transaction terminates. Furthermore, any updates
performed by a nested transaction are only propagated
in such a manner so that the parent of the nested transaction
sees the updates. No final commitment will be done until
the top level transaction is terminated.
So, although a nested transaction returns <CODE>{atomic, Val}</CODE>,
if the enclosing parent transaction is aborted, the entire
nested operation is aborted.
<P>The ability to have nested transaction with identical semantics
as top level transaction makes it easier to write
library functions that manipulate mnesia tables.
<P>Say for example that we have a function that adds a
new subscriber to a telephony system:
<PRE>
add_subscriber(S) ->
mnesia:transaction(fun() ->
case mnesia:read( ..........
</PRE>
<P>This function needs to be called as a transaction.
Now assume that we wish to write a function that
both calls the <CODE>add_subscriber/1</CODE> function and
is in itself protected by the context of a transaction.
By simply calling the <CODE>add_subscriber/1</CODE> from within
another transaction, a nested transaction is created.
<P>It is also possible to mix different activity access contexts while nesting,
but the dirty ones (async_dirty,sync_dirty and ets) will inherit the transaction
semantics if they are called inside a transaction and thus it will grab locks and
use two or three phase commit.
<PRE>
add_subscriber(S) ->
mnesia:transaction(fun() ->
%% Transaction context
mnesia:read({some_tab, some_data}),
mnesia:sync_dirty(fun() ->
%% Still in a transaction context.
case mnesia:read( ..) ..end), end).
add_subscriber2(S) ->
mnesia:sync_dirty(fun() ->
%% In dirty context
mnesia:read({some_tab, some_data}),
mnesia:transaction(fun() ->
%% In a transaction context.
case mnesia:read( ..) ..end), end).
</PRE>
<A NAME="4.7"><!-- Empty --></A>
<H3>4.7 Pattern Matching</H3>
<A NAME="matching"><!-- Empty --></A>
<P>When it is not possible to use <CODE>mnesia:read/3</CODE> Mnesia
provides the programmer with several functions for matching
records against a pattern. The most useful functions of these are:
<PRE>
mnesia:select(Tab, MatchSpecification, LockKind) ->
transaction abort | [ObjectList]
mnesia:select(Tab, MatchSpecification, NObjects, Lock) ->
transaction abort | {[Object],Continuation} | '$end_of_table'
mnesia:select(Cont) ->
transaction abort | {[Object],Continuation} | '$end_of_table'
mnesia:match_object(Tab, Pattern, LockKind) ->
transaction abort | RecordList
</PRE>
<P>These functions matches a <CODE>Pattern</CODE> against all records in
table <CODE>Tab</CODE>. In a <CODE>mnesia:select</CODE> call <CODE>Pattern</CODE> is
a part of <CODE>MatchSpecification</CODE> described below. It is not
necessarily performed as an exhaustive search of the entire
table. By utilizing indices and bound values in the key of the
pattern, the actual work done by the function may be condensed
into a few hash lookups. Using <CODE>ordered_set</CODE> tables may reduce the
search space if the keys are partially bound.
<P>The pattern provided to the functions must be a valid record,
and the first element of the provided tuple must be the
<CODE>record_name</CODE> of the table. The special element <CODE>'_'</CODE>
matches any data structure in Erlang (also known as an Erlang
term). The special elements <CODE>'$<number>'</CODE> behaves as Erlang
variables i.e. matches anything and binds the first occurrence and
matches the coming occurrences of that variable against the bound value.
<P>Use the function <CODE>mnesia:table_info(Tab, wild_pattern)</CODE>
to obtain a basic pattern which matches all records in a table
or use the default value in record creation.
Do not make the pattern hard coded since it will make your code more
vulnerable to future changes of the record definition.
<PRE>
Wildpattern = mnesia:table_info(employee, wild_pattern),
%% Or use
Wildpattern = #employee{_ = '_'},
</PRE>
<P>For the employee table the wild pattern will look like:
<PRE>
{employee, '_', '_', '_', '_', '_',' _'}.
</PRE>
<P>In order to constrain the match you must replace some
of the <CODE>'_'</CODE> elements. The code for matching out
all female employees, looks like:
<PRE>
Pat = #employee{sex = female, _ = '_'},
F = fun() -> mnesia:match_object(Pat) end,
Females = mnesia:transaction(F).
</PRE>
<P>It is also possible to use the match function if we want to
check the equality of different attributes. Assume that we want
to find all employees which happens to have a employee number
which is equal to their room number:
<PRE>
Pat = #employee{emp_no = '$1', room_no = '$1', _ = '_'},
F = fun() -> mnesia:match_object(Pat) end,
Odd = mnesia:transaction(F).
</PRE>
<P> The function <CODE>mnesia:match_object/3</CODE> lacks some important
features that <CODE>mnesia:select/3</CODE> have. For example
<CODE>mnesia:match_object/3</CODE> can only return the matching records,
and it can not express constraints other then equality.
If we want to find the names of the male employees on the second floor
we could write:
<PRE>
MatchHead = #employee{name='$1', sex=male, room_no={'$2', '_'}, _='_'},
Guard = [{'>=', '$2', 220},{'<', '$2', 230}],
Result = '$1',
mnesia:select(employee,[{MatchHead, Guard, [Result]}])
</PRE>
<P> Select can be used to add additional constraints and create
output which can not be done with <CODE>mnesia:match_object/3</CODE>.
<P> The second argument to select is a <CODE>MatchSpecification</CODE>.
A <CODE>MatchSpecification</CODE> is list of <CODE>MatchFunctions</CODE>, where
each <CODE>MatchFunction</CODE> consists of a tuple containing
<CODE>{MatchHead, MatchCondition, MatchBody}</CODE>. <CODE>MatchHead</CODE>
is the same pattern used in <CODE>mnesia:match_object/3</CODE>
described above. <CODE>MatchCondition</CODE> is a list of additional
constraints applied to each record, and <CODE>MatchBody</CODE> is used
to construct the return values.
<P> A detailed explanation of match specifications can be found in
the <STRONG>Erts users guide: Match specifications in Erlang </STRONG>,
and the ets/dets documentations may provide some additional
information.
<P> The functions <CODE>select/4</CODE> and <CODE>select/1</CODE> are used to
get a limited number of results, where the <CODE>Continuation</CODE>
are used to get the next chunk of results. Mnesia uses the
<CODE>NObjects</CODE> as an recommendation only, thus more or less
results then specified with <CODE>NObjects</CODE> may be returned in
the result list, even the empty list may be returned despite there
are more results to collect.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Warning!" SRC="warning.gif"></TD>
<TD>
<P>There is a severe performance penalty in using
<CODE>mnesia:select/[1|2|3|4]</CODE> after any modifying operations
are done on that table in the same transaction, i.e. avoid using
<CODE>mnesia:write/1</CODE> or <CODE>mnesia:delete/1</CODE> before a
<CODE>mnesia:select</CODE> in the same transaction.
</TD>
</TR>
</TABLE>
<P>If the key attribute is bound in a pattern, the match operation
is very efficient. However, if the key attribute in a pattern is
given as <CODE>'_'</CODE>, or <CODE>'$1'</CODE>, the whole <CODE>employee</CODE>
table must be searched for records that match. Hence if the table is
large, this can become a time consuming operation, but it can be
remedied with indices (refer to Chapter 5: <A HREF="Mnesia_chap5.html#indexing">Indexing</A>) if
<CODE>mnesia:match_object</CODE> is used.
<P> QLC queries can also be used to search Mnesia tables. By
using <CODE>mnesia:table/[1|2]</CODE> as the generator inside a QLC
query you let the query operate on a mnesia table. Mnesia
specific options to <CODE>mnesia:table/2</CODE> are {lock, Lock},
{n_objects,Integer} and {traverse, SelMethod}. The <CODE>lock</CODE>
option specifies whether mnesia should acquire a read or write
lock on the table, and <CODE>n_objects</CODE> specifies how many
results should be returned in each chunk to QLC. The last option is
<CODE>traverse</CODE> and it specifies which function mnesia should
use to traverse the table. Default <CODE>select</CODE> is used, but by using
<CODE>{traverse, {select, MatchSpecification}}</CODE> as an option to
<CODE>mnesia:table/2</CODE> the user can specify it's own view of the
table.
<P> If no options are specified a read lock will acquired and 100
results will be returned in each chunk, and select will be used
to traverse the table, i.e.:
<PRE>
mnesia:table(Tab) ->
mnesia:table(Tab, [{n_objects,100},{lock, read}, {traverse, select}]).
</PRE>
<P>The function <CODE>mnesia:all_keys(Tab)</CODE> returns all keys in a
table.
<A NAME="4.8"><!-- Empty --></A>
<H3>4.8 Iteration</H3>
<A NAME="iteration"><!-- Empty --></A>
<P>Mnesia provides a couple of functions which iterates over all
the records in a table.
<PRE>
mnesia:foldl(Fun, Acc0, Tab) -> NewAcc | transaction abort
mnesia:foldr(Fun, Acc0, Tab) -> NewAcc | transaction abort
mnesia:foldl(Fun, Acc0, Tab, LockType) -> NewAcc | transaction abort
mnesia:foldr(Fun, Acc0, Tab, LockType) -> NewAcc | transaction abort
</PRE>
<P>These functions iterate over the mnesia table <CODE>Tab</CODE> and
apply the function <CODE>Fun</CODE> to each record. The <CODE>Fun</CODE>
takes two arguments, the first argument is a record from the
table and the second argument is the accumulator. The
<CODE>Fun</CODE> return a new accumulator.
<P>The first time the <CODE>Fun</CODE> is applied <CODE>Acc0</CODE> will
be the second argument. The next time the <CODE>Fun</CODE> is called
the return value from the previous call, will be used as the
second argument. The term the last call to the Fun returns
will be the return value of the <CODE>fold[lr]</CODE> function.
<P>The difference between <CODE>foldl</CODE> and <CODE>foldr</CODE> is the
order the table is accessed for <CODE>ordered_set</CODE> tables,
for every other table type the functions are equivalent.
<P><CODE>LockType</CODE> specifies what type of lock that shall be
acquired for the iteration, default is <CODE>read</CODE>. If
records are written or deleted during the iteration a write
lock should be acquired.
<P> These functions might be used to find records in a table
when it is impossible to write constraints for
<CODE>mnesia:match_object/3</CODE>, or when you want to perform
some action on certain records.
<P> For example finding all the employees who has a salary
below 10 could look like:
<PRE>
find_low_salaries() ->
Constraint =
fun(Emp, Acc) when Emp#employee.salary < 10 ->
[Emp | Acc];
(_, Acc) ->
Acc
end,
Find = fun() -> mnesia:foldl(Constraint, [], employee) end,
mnesia:transaction(Find).
</PRE>
<P> Raising the salary to 10 for everyone with a salary below 10
and return the sum of all raises:
<PRE>
increase_low_salaries() ->
Increase =
fun(Emp, Acc) when Emp#employee.salary < 10 ->
OldS = Emp#employee.salary,
ok = mnesia:write(Emp#employee{salary = 10}),
Acc + 10 - OldS;
(_, Acc) ->
Acc
end,
IncLow = fun() -> mnesia:foldl(Increase, 0, employee, write) end,
mnesia:transaction(IncLow).
</PRE>
<P> A lot of nice things can be done with the iterator functions
but some caution should be taken about performance and memory
utilization for large tables.
<P>Call these iteration functions on nodes that contain a replica of the
table. Each call to the function <CODE>Fun</CODE> access the table and if the table
resides on another node it will generate a lot of unnecessary
network traffic.
<P>Mnesia also provides some functions that make it possible for
the user to iterate over the table. The order of the
iteration is unspecified if the table is not of the <CODE>ordered_set</CODE>
type.
<PRE>
mnesia:first(Tab) -> Key | transaction abort
mnesia:last(Tab) -> Key | transaction abort
mnesia:next(Tab,Key) -> Key | transaction abort
mnesia:prev(Tab,Key) -> Key | transaction abort
</PRE>
<P>The order of first/last and next/prev are only valid for
<CODE>ordered_set</CODE> tables, for all other tables, they are synonyms.
When the end of the table is reached the special key
<CODE>'$end_of_table'</CODE> is returned.
<P> If records are written and deleted during the traversal, use
<CODE>mnesia:fold[lr]/4</CODE> with a <CODE>write</CODE> lock. Or
<CODE>mnesia:write_lock_table/1</CODE> when using first and next.
<P> Writing or deleting in transaction context creates a local copy
of each modified record, so modifying each record in a large
table uses a lot of memory. Mnesia will compensate for every
written or deleted record during the iteration in a transaction
context, which may reduce the performance. If possible avoid writing
or deleting records in the same transaction before iterating over the
table.
<P> In dirty context, i.e. <CODE>sync_dirty</CODE> or <CODE>async_dirty</CODE>,
the modified records are not stored in a local copy; instead,
each record is updated separately. This generates a lot of
network traffic if the table has a replica on another node and
has all the other drawbacks that dirty operations
have. Especially for the <CODE>mnesia:first/1</CODE> and
<CODE>mnesia:next/2</CODE> commands, the same drawbacks as described
above for <CODE>dirty_first</CODE> and <CODE>dirty_next</CODE> applies, i.e.
no writes to the table should be done during iteration.
<P> <CENTER>
<HR>
<SMALL>
Copyright © 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>
|