Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 1000

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- Transactions and Other Access Contexts</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../../../../doc/js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../../../../doc/js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../../../../doc/erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="index.html">Reference Manual</a><br><a href="release_notes.html">Release Notes</a><br><a href="../pdf/mnesia-4.7.1.pdf">PDF</a><br><a href="../../../../doc/index.html">Top</a></small><p><strong>Mnesia</strong><br><strong>User's Guide</strong><br><small>Version 4.7.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../../../../doc/js/flipmenu">
<li id="no" title="Introduction" expanded="false">Introduction<ul>
<li><a href="Mnesia_chap1.html">
              Top of chapter
            </a></li>
<li title="About Mnesia"><a href="Mnesia_chap1.html#id57488">About Mnesia</a></li>
<li title="The Mnesia DataBase Management System (DBMS)"><a href="Mnesia_chap1.html#id57481">The Mnesia DataBase Management System (DBMS)</a></li>
</ul>
</li>
<li id="no" title="Getting Started with Mnesia" expanded="false">Getting Started with Mnesia<ul>
<li><a href="Mnesia_chap2.html">
              Top of chapter
            </a></li>
<li title="Starting Mnesia for the first time"><a href="Mnesia_chap2.html#id61530">Starting Mnesia for the first time</a></li>
<li title="An Introductory Example"><a href="Mnesia_chap2.html#id62101">An Introductory Example</a></li>
</ul>
</li>
<li id="no" title="Building A Mnesia Database" expanded="false">Building A Mnesia Database<ul>
<li><a href="Mnesia_chap3.html">
              Top of chapter
            </a></li>
<li title="Defining a Schema"><a href="Mnesia_chap3.html#id67814">Defining a Schema</a></li>
<li title="The Data Model"><a href="Mnesia_chap3.html#id68070">The Data Model</a></li>
<li title="Starting Mnesia"><a href="Mnesia_chap3.html#id68125">Starting Mnesia</a></li>
<li title="Creating New Tables"><a href="Mnesia_chap3.html#id72288">Creating New Tables</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Transactions and Other Access Contexts" expanded="true">Transactions and Other Access Contexts<ul>
<li><a href="Mnesia_chap4.html">
              Top of chapter
            </a></li>
<li title="Transaction Properties"><a href="Mnesia_chap4.html#id72980">Transaction Properties</a></li>
<li title="Locking"><a href="Mnesia_chap4.html#id73193">Locking</a></li>
<li title="Dirty Operations"><a href="Mnesia_chap4.html#id73653">Dirty Operations</a></li>
<li title="Record Names versus Table Names"><a href="Mnesia_chap4.html#id74026">Record Names versus Table Names</a></li>
<li title="Activity Concept and Various Access Contexts"><a href="Mnesia_chap4.html#id74114">Activity Concept and Various Access Contexts</a></li>
<li title="Nested transactions"><a href="Mnesia_chap4.html#id74404">Nested transactions</a></li>
<li title="Pattern Matching"><a href="Mnesia_chap4.html#id74476">Pattern Matching</a></li>
<li title="Iteration"><a href="Mnesia_chap4.html#id74822">Iteration</a></li>
</ul>
</li>
<li id="no" title="Miscellaneous Mnesia Features" expanded="false">Miscellaneous Mnesia Features<ul>
<li><a href="Mnesia_chap5.html">
              Top of chapter
            </a></li>
<li title="Indexing"><a href="Mnesia_chap5.html#id75164">Indexing</a></li>
<li title="Distribution and Fault Tolerance"><a href="Mnesia_chap5.html#id75284">Distribution and Fault Tolerance</a></li>
<li title="Table Fragmentation"><a href="Mnesia_chap5.html#id75432">Table Fragmentation</a></li>
<li title="Local Content Tables"><a href="Mnesia_chap5.html#id76375">Local Content Tables</a></li>
<li title="Disc-less Nodes"><a href="Mnesia_chap5.html#id76402">Disc-less Nodes</a></li>
<li title="More Schema Management"><a href="Mnesia_chap5.html#id76560">More Schema Management</a></li>
<li title="Mnesia Event Handling"><a href="Mnesia_chap5.html#id76675">Mnesia Event Handling</a></li>
<li title="Debugging Mnesia Applications"><a href="Mnesia_chap5.html#id77250">Debugging Mnesia Applications</a></li>
<li title="Concurrent Processes in Mnesia"><a href="Mnesia_chap5.html#id77395">Concurrent Processes in Mnesia</a></li>
<li title="Prototyping"><a href="Mnesia_chap5.html#id77432">Prototyping</a></li>
<li title="Object Based Programming with Mnesia"><a href="Mnesia_chap5.html#id77546">Object Based Programming with Mnesia</a></li>
</ul>
</li>
<li id="no" title="Mnesia System Information" expanded="false">Mnesia System Information<ul>
<li><a href="Mnesia_chap7.html">
              Top of chapter
            </a></li>
<li title="Database Configuration Data"><a href="Mnesia_chap7.html#id77779">Database Configuration Data</a></li>
<li title="Core Dumps"><a href="Mnesia_chap7.html#id77817">Core Dumps</a></li>
<li title="Dumping Tables"><a href="Mnesia_chap7.html#id77838">Dumping Tables</a></li>
<li title="Checkpoints"><a href="Mnesia_chap7.html#id77873">Checkpoints</a></li>
<li title="Files"><a href="Mnesia_chap7.html#id78113">Files</a></li>
<li title="Loading of Tables at Start-up"><a href="Mnesia_chap7.html#id78474">Loading of Tables at Start-up</a></li>
<li title="Recovery from Communication Failure"><a href="Mnesia_chap7.html#id78632">Recovery from Communication Failure</a></li>
<li title="Recovery of Transactions"><a href="Mnesia_chap7.html#id78755">Recovery of Transactions</a></li>
<li title="Backup, Fallback, and Disaster Recovery"><a href="Mnesia_chap7.html#id78876">Backup, Fallback, and Disaster Recovery</a></li>
</ul>
</li>
<li id="no" title="Combining Mnesia with SNMP" expanded="false">Combining Mnesia with SNMP<ul>
<li><a href="Mnesia_chap8.html">
              Top of chapter
            </a></li>
<li title="Combining Mnesia and SNMP "><a href="Mnesia_chap8.html#id79691">Combining Mnesia and SNMP </a></li>
</ul>
</li>
<li id="no" title="Appendix A: Mnesia Error Messages" expanded="false">Appendix A: Mnesia Error Messages<ul>
<li><a href="Mnesia_App_A.html">
              Top of chapter
            </a></li>
<li title="Errors in Mnesia"><a href="Mnesia_App_A.html#id79834">Errors in Mnesia</a></li>
</ul>
</li>
<li id="no" title="Appendix B: The Backup Call Back Interface" expanded="false">Appendix B: The Backup Call Back Interface<ul>
<li><a href="Mnesia_App_B.html">
              Top of chapter
            </a></li>
<li title="mnesia_backup callback behavior"><a href="Mnesia_App_B.html#id80051">mnesia_backup callback behavior</a></li>
</ul>
</li>
<li id="no" title="Appendix C: The Activity Access Call Back Interface" expanded="false">Appendix C: The Activity Access Call Back Interface<ul>
<li><a href="Mnesia_App_C.html">
              Top of chapter
            </a></li>
<li title="mnesia_access callback behavior"><a href="Mnesia_App_C.html#id80172">mnesia_access callback behavior</a></li>
</ul>
</li>
<li id="no" title="Appendix D: The Fragmented Table Hashing Call Back Interface" expanded="false">Appendix D: The Fragmented Table Hashing Call Back Interface<ul>
<li><a href="Mnesia_App_D.html">
              Top of chapter
            </a></li>
<li title="mnesia_frag_hash callback behavior"><a href="Mnesia_App_D.html#id80315">mnesia_frag_hash callback behavior</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>4 Transactions and Other Access Contexts</h1>
  
  <p>This chapter describes the Mnesia transaction system and the
    transaction properties which make Mnesia a fault tolerant,
    distributed database management system. 
    </p>
  <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>

  <h3><a name="id72980">4.1 
        Transaction Properties</a></h3>
    <a name="trans_prop"></a>
    
    <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>
    <p>The following example shows a transaction which raises the
      salary of certain employee numbers. 
      </p>
<div class="example"><pre>

raise(Eno, Raise) -&gt;
    F = fun() -&gt;
                [E] = mnesia:read(employee, Eno, write),
                Salary = E#employee.salary + Raise,
                New = E#employee{salary = Salary},
                mnesia:write(New)
        end,
    mnesia:transaction(F).</pre></div>    <p>The transaction <span class="code">raise(Eno, Raise) - &gt;</span> contains a Fun
      made up of four lines of code. This Fun is called by the statement
      <span class="code">mnesia:transaction(F)</span> and returns a value. 
      </p>
    <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>

    <h4>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>
      <p>Atomicity is particularly important when we want to
        atomically write more than one record in the same
        transaction. The <span class="code">raise/2</span> function, shown as an example
        above, writes one record only. The <span class="code">insert_emp/3</span> function,
        shown in the program listing in Chapter 2, writes the record
        <span class="code">employee</span> as well as employee relations such as
        <span class="code">at_dep</span> and <span class="code">in_proj</span> 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>
      <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. </p>
    

    <h4>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.
        </p>
    

    <h4>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>
      <p>The isolation property makes it possible to concurrently execute 
        the <span class="code">raise/2</span> function. A classical problem in concurrency control
        theory is the so called "lost update problem". 
        </p>
      <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>
      <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.
        </p>
    

    <h4>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>
      <div class="note">
<div class="label">Note</div>
<div class="content"><p>
        <p>The durability feature described does not entirely apply to
          situations where Mnesia is configured as a "pure" primary memory
          database. 
          </p>
      </p></div>
</div>
    
  

  <h3><a name="id73193">4.2 
        Locking</a></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
      <span class="code">mnesia:read/1</span> 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>
    <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>
    <p>For this reason, it is important that the code inside the Fun given to
      <span class="code">mnesia:transaction/1</span> is pure. Some strange results can
      occur if, for example, messages are sent by the transaction
      Fun. The following example illustrates this situation:  
      </p>
<div class="example"><pre>

bad_raise(Eno, Raise) -&gt;
    F = fun() -&gt;
                [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></div>    <p>This transaction could write the text <span class="code">"Trying to write ... "</span> 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>
    <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>
    <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 <span class="code">receive</span>
      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>
    <p>If a transaction terminates abnormally, Mnesia will
      automatically release the locks held by the transaction. 
      </p>
    <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>
<span class="code">mnesia:transaction(Fun) -&gt; {aborted, Reason} |{atomic, Value}</span>. This function executes one transaction with the
       functional object <span class="code">Fun</span> as the single parameter. 
      </li>
      <li>
<span class="code">mnesia:read({Tab, Key}) -&gt; transaction abort | RecordList</span>. This function reads all records with <span class="code">Key</span>
       as key from table <span class="code">Tab</span>.  This function has the same semantics
       regardless of the location of <span class="code">Table</span>. If the table is of
       type <span class="code">bag</span>, the <span class="code">read({Tab, Key})</span> can return an arbitrarily
       long list. If the table is of type <span class="code">set</span>, the list is
       either of length one, or <span class="code">[]</span>.
      </li>
      <li>
<span class="code">mnesia:wread({Tab, Key}) -&gt; transaction abort | RecordList</span>. This function behaves the same way as the
       previously listed <span class="code">read/1</span> 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
      <span class="code">mnesia:read/1</span>, followed by a <span class="code">mnesia:write/1</span>, the
       first read lock must be upgraded to a write lock when the write
       operation is executed. 
      </li>
      <li>
<span class="code">mnesia:write(Record) -&gt; transaction abort | ok</span>. This function writes a record into the database. The
      <span class="code">Record</span> argument is an instance of a record. The function
       returns <span class="code">ok</span>, or aborts the transaction if an error should
       occur. 
      </li>
      <li>
<span class="code">mnesia:delete({Tab, Key}) -&gt; transaction abort | ok</span>. This
       function deletes all records with the given key.
      </li>
      <li>
<span class="code">mnesia:delete_object(Record) -&gt; transaction abort | ok</span>.  This function deletes records with object id
      <span class="code">Record</span>. This function is used when we want to delete only
       some records in a table of type <span class="code">bag</span>. </li>
    </ul>

    <h4>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>
      <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: 
        </p>
      <div class="example"><pre>
        F = fun() -&gt;
              mnesia:write(#foo{a = kalle})
            end,
        mnesia:transaction(F).
      </pre></div>
      <p>The <span class="code">foo</span> table is replicated on the two nodes <span class="code">N1</span>
        and <span class="code">N2</span>. 
                <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:
        </p>
      <div class="example"><pre>

        F = fun() -&gt;
              mnesia:s_write(#foo{a = kalle})
            end,
        mnesia:transaction(F).
      </pre></div>
      <p>This code uses the <span class="code">s_write/1</span> function instead of the
        <span class="code">write/1</span> function. The <span class="code">s_write/1</span> 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 <span class="code">N1</span>, this
        lock will then stick to node <span class="code">N1</span>. The next time we try to
        set a sticky lock on the same record at node <span class="code">N1</span>, Mnesia
        will see that the lock is already set and will not do a network
        operation in order to acquire the lock. 
        </p>
      <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>
      <p>If a record is stuck at node <span class="code">N1</span> and we try to set a
        sticky lock for the record on node <span class="code">N2</span>, the record must be
        unstuck. This operation is expensive and will reduce performance. The unsticking is
        done automatically if we issue <span class="code">s_write/1</span> requests at
        <span class="code">N2</span>.
        </p>
    

    <h4>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>
<span class="code">mnesia:read_lock_table(Tab)</span> Sets a read lock on
         the table <span class="code">Tab</span>
</li>
        <li>
<span class="code">mnesia:write_lock_table(Tab)</span> Sets a write lock on
         the table <span class="code">Tab</span>
</li>
      </ul>
      <p>Alternate syntax for acquisition of table locks is as follows:
        </p>
      <div class="example"><pre>
        mnesia:lock({table, Tab}, read)
        mnesia:lock({table, Tab}, write)
      </pre></div>
      <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).
        </p>
    

    <h4>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>
      <p>The function <span class="code">mnesia:lock/2</span> 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:
        </p>
      <div class="example"><pre>
        mnesia:lock({global, GlobalKey, Nodes}, LockKind)

        LockKind ::= read | write | ...
      </pre></div>
      <p>The lock is acquired on the LockItem on all Nodes in the
        nodes list.</p>
    
  

  <h3><a name="id73653">4.3 
        Dirty Operations</a></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>
    <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>
    <p>Dirty operations
      are written to disc if they are performed on a table of type
      <span class="code">disc_copies</span>, or type <span class="code">disc_only_copies</span>. Mnesia also
      ensures that all replicas of a table are updated if a
      dirty write operation is performed on a table.
      </p>
    <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>
    <p>All dirty functions execute a call to <span class="code">exit({aborted, Reason})</span> on failure. Even if the following functions are
      executed inside a transaction no locks will be acquired.  The
      following functions are available:
      </p>
    <ul>
      <li>
<span class="code">mnesia:dirty_read({Tab, Key})</span>. This function reads
       record(s) from Mnesia.
      </li>
      <li>
<span class="code">mnesia:dirty_write(Record)</span>. This function writes
       the record <span class="code">Record</span>
</li>
      <li>
<span class="code">mnesia:dirty_delete({Tab, Key})</span>. This function deletes
       record(s) with the key <span class="code">Key</span>. 
      </li>
      <li>
<span class="code">mnesia:dirty_delete_object(Record)</span> This function is
       the dirty operation alternative to the function
      <span class="code">delete_object/1</span>
</li>
      <li>
        <p><span class="code">mnesia:dirty_first(Tab)</span>. This function returns the
          "first" key in the table <span class="code">Tab</span>.  </p>
        <p>Records in <span class="code">set</span> or <span class="code">bag</span> 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 <span class="code">dirty_next/2</span>
          function.
          </p>
        <p>If there are no records at all in the table, this function
          will return the atom <span class="code">'$end_of_table'</span>. It is not
          recommended to use this atom as the key for any user
          records. 
          </p>
      </li>
      <li>
<span class="code">mnesia:dirty_next(Tab, Key)</span>. This function returns
       the "next" key in the table <span class="code">Tab</span>. 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 <span class="code">'$end_of_table'</span> 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
      <span class="code">dirty_next/2</span> function. This is because <span class="code">write</span>
       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>
<span class="code">mnesia:dirty_last(Tab)</span> This function works exactly like
      <span class="code">mnesia:dirty_first/1</span> but returns the last object in
       Erlang  term  order for the <span class="code">ordered_set</span> table type. For
       all other table types, <span class="code">mnesia:dirty_first/1</span> and 
      <span class="code">mnesia:dirty_last/1</span> are synonyms.
      </li>
      <li>
<span class="code">mnesia:dirty_prev(Tab, Key)</span> This function works exactly like
      <span class="code">mnesia:dirty_next/2</span> but returns the previous object in
       Erlang term  order for the ordered_set table type. For
       all other table types, <span class="code">mnesia:dirty_next/2</span> and 
      <span class="code">mnesia:dirty_prev/2</span> are synonyms.
      </li>
      <li>
        <p><span class="code">mnesia:dirty_slot(Tab, Slot)</span></p>
        <p>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 <span class="code">dirty_next/2</span> function. A table has a
          number of slots that range from zero to some unknown upper
          bound. The function <span class="code">dirty_slot/2</span> returns the special
          atom <span class="code">'$end_of_table'</span> 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. <span class="code">mnesia:read_lock_table(Tab)</span> may be used to
          ensure that no transaction protected writes are performed
          during the iteration. 
          </p>
      </li>
      <li>
        <p><span class="code">mnesia:dirty_update_counter({Tab,Key}, Val)</span>. </p>
        <p>Counters are positive integers with a value greater than or
          equal to zero. Updating a counter will add the <span class="code">Val</span> and
          the counter where  <span class="code">Val</span> is a positive or negative integer.
                    <br>
 There exists no special counter records in
          Mnesia. However, records on the form of <span class="code">{TabName, Key, Integer}</span> can be used as counters, and can be
          persistent.  
          </p>
        <p>It is not possible to have transaction protected updates of
          counter records.
          </p>
        <p>There are two significant differences when using this
          function instead of reading the record, performing the
          arithmetic, and writing the record:
          </p>
        <ul>
          <li>it is much more efficient
          </li>
          <li>the <span class="code">dirty_update_counter/2</span> 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
          <span class="code">dirty_update_counter/2</span> function.
          </li>
        </ul>
      </li>
      <li>
<span class="code">mnesia:dirty_match_object(Pat)</span>. This function is
       the dirty equivalent of <span class="code">mnesia:match_object/1</span>. 
      </li>
      <li>
<span class="code">mnesia:dirty_select(Tab, Pat)</span>. This function is
       the dirty equivalent of <span class="code">mnesia:select/2</span>. 
      </li>
      <li>
<span class="code">mnesia:dirty_index_match_object(Pat, Pos)</span>. This
       function is the dirty equivalent of
      <span class="code">mnesia:index_match_object/2</span>. 
      </li>
      <li>
<span class="code">mnesia:dirty_index_read(Tab, SecondaryKey, Pos)</span>. This
       function is the dirty equivalent of <span class="code">mnesia:index_read/3</span>. 
      </li>
      <li>
<span class="code">mnesia:dirty_all_keys(Tab)</span>. This function is the
       dirty equivalent of <span class="code">mnesia:all_keys/1</span>. 
      </li>
    </ul>
  

  <h3><a name="id74026">4.4 
        Record Names versus Table Names</a></h3>
    <a name="recordnames_tablenames"></a>
    
    <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 <span class="code">record_name</span> property the code below will 
      ensure all records in the tables have the same name as the table:
      </p>
    <div class="example"><pre>
      mnesia:create_table(subscriber, [])
    </pre></div>
    <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:
      </p>
    <div class="example"><pre>
      TabDef = [{record_name, subscriber}],
      mnesia:create_table(my_subscriber, TabDef),
      mnesia:create_table(your_subscriber, TabDef).
    </pre></div>
    <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
      <span class="code">mnesia:write/3</span>function instead of the simplified functions
      <span class="code">mnesia:write/1</span> and <span class="code">mnesia:s_write/1</span>:
      </p>
    <div class="example"><pre>
      mnesia:write(subscriber, #subscriber{}, write)
      mnesia:write(my_subscriber, #subscriber{}, sticky_write)
      mnesia:write(your_subscriber, #subscriber{}, write)
    </pre></div>
    <p>The following simplified piece of code illustrates the
      relationship between the simplified access functions used in
      most examples and their more flexible counterparts:
      </p>
    <div class="example"><pre>
      mnesia:dirty_write(Record) -&gt;
        Tab = element(1, Record),
        mnesia:dirty_write(Tab, Record).
      
      mnesia:dirty_delete({Tab, Key}) -&gt;
        mnesia:dirty_delete(Tab, Key).
      
      mnesia:dirty_delete_object(Record) -&gt;
        Tab = element(1, Record),
        mnesia:dirty_delete_object(Tab, Record) 
      
      mnesia:dirty_update_counter({Tab, Key}, Incr) -&gt;
        mnesia:dirty_update_counter(Tab, Key, Incr).
      
      mnesia:dirty_read({Tab, Key}) -&gt;
        Tab = element(1, Record),
        mnesia:dirty_read(Tab, Key).
      
      mnesia:dirty_match_object(Pattern) -&gt;
        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) -&gt;
        Tab = element(1, Record),
        mnesia:write(Tab, Record, write).
      
      mnesia:s_write(Record) -&gt;
        Tab = element(1, Record),
        mnesia:write(Tab, Record, sticky_write).
      
      mnesia:delete({Tab, Key}) -&gt;
        mnesia:delete(Tab, Key, write).
      
      mnesia:s_delete({Tab, Key}) -&gt;
        mnesia:delete(Tab, Key, sticky_write).
      
      mnesia:delete_object(Record) -&gt;
        Tab = element(1, Record),
        mnesia:delete_object(Tab, Record, write).
      
      mnesia:s_delete_object(Record) -&gt;
        Tab = element(1, Record),
        mnesia:delete_object(Tab, Record. sticky_write).
      
      mnesia:read({Tab, Key}) -&gt;
        mnesia:read(Tab, Key, read).
      
      mnesia:wread({Tab, Key}) -&gt;
        mnesia:read(Tab, Key, write).
      
      mnesia:match_object(Pattern) -&gt;
        Tab = element(1, Pattern),
        mnesia:match_object(Tab, Pattern, read).
      
      mnesia:index_match_object(Pattern, Attr) -&gt;
        Tab = element(1, Pattern),
        mnesia:index_match_object(Tab, Pattern, Attr, read).
    </pre></div>
  

  <h3><a name="id74114">4.5 
        Activity Concept and Various Access Contexts</a></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
      <span class="code">mnesia:transaction/1,2,3</span>: 
      </p>
    <ul>
      <li>
        <p>mnesia:write/3 (write/1, s_write/1)</p>
      </li>
      <li>
        <p>mnesia:delete/3 (delete/1, s_delete/1)</p>
      </li>
      <li>
        <p>mnesia:delete_object/3 (delete_object/1, s_delete_object/1)</p>
      </li>
      <li>
        <p>mnesia:read/3 (read/1, wread/1)</p>
      </li>
      <li>
        <p>mnesia:match_object/2 (match_object/1)</p>
      </li>
      <li>
        <p>mnesia:select/3 (select/2)</p>
      </li>
      <li>
        <p>mnesia:foldl/3 (foldl/4, foldr/3, foldr/4)</p>
      </li>
      <li>
        <p>mnesia:all_keys/1</p>
      </li>
      <li>
        <p>mnesia:index_match_object/4 (index_match_object/2)</p>
      </li>
      <li>
        <p>mnesia:index_read/3</p>
      </li>
      <li>
        <p>mnesia:lock/2 (read_lock_table/1, write_lock_table/1)</p>
      </li>
      <li>
        <p>mnesia:table_info/2</p>
      </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>
        <p>transaction      </p>
      </li>
      <li>
        <p>sync_transaction</p>
      </li>
      <li>
        <p>async_dirty</p>
      </li>
      <li>
        <p>sync_dirty</p>
      </li>
      <li>
        <p>ets</p>
      </li>
    </ul>
    <p>By passing the same "fun" as argument to the function
      <span class="code">mnesia:sync_transaction(Fun [, Args])</span> 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>
    <p>By passing the same "fun" as argument to the function
      <span class="code">mnesia:async_dirty(Fun [, Args])</span> 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>
    <p>By passing the same "fun" as an argument to the function
      <span class="code">mnesia:sync_dirty(Fun [, Args])</span> it will be performed in
      almost the same context as <span class="code">mnesia:async_dirty/1,2</span>. 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>
    <p>You can check if your code is executed within a transaction with
      <span class="code">mnesia:is_transaction/0</span>, it returns <span class="code">true</span> when called
      inside a transaction context and false otherwise.</p>

    <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
      <span class="code">mnesia:ets(Fun [, Args])</span> 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>
    <p>The Fun may also be passed as an argument to the function
      <span class="code">mnesia:activity/2,3,4</span> 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 <span class="code">access_module</span> 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
      <span class="code">mnesia:table_info/2</span> may be used to provide virtual
      information about a table. One usage of this is to perform
      <span class="code">QLC</span> queries within an activity context with a
      customized callback module. By providing table information about
      table indices and other <span class="code">QLC</span> requirements,
      <span class="code">QLC</span> may be used as a generic query language to
      access virtual tables.
      </p>
    <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>
    <div class="note">
<div class="label">Note</div>
<div class="content"><p>
      <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.</p>
    </p></div>
</div>
  

  <h3><a name="id74404">4.6 
        Nested transactions</a></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 <span class="code">{aborted, Reason}</span> 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>
    <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 <span class="code">{atomic, Val}</span>,
      if the enclosing parent transaction is aborted, the entire
      nested operation is aborted.
      </p>
    <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>
    <p>Say for example that we have a function that adds a
      new subscriber to a telephony system:</p>
    <div class="example"><pre>
      add_subscriber(S) -&gt;
          mnesia:transaction(fun() -&gt;
              case mnesia:read( ..........
    </pre></div>
    <p>This function needs to be called as a transaction.
      Now assume that we wish to write a function that
      both calls the <span class="code">add_subscriber/1</span> function and
      is in itself protected by the context of a transaction.
      By simply calling the <span class="code">add_subscriber/1</span> from within
      another transaction, a nested transaction is created.
      </p>
    <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.
      </p>
    <div class="example"><pre>
      add_subscriber(S) -&gt;
          mnesia:transaction(fun() -&gt;
             %% Transaction context 
             mnesia:read({some_tab, some_data}),
             mnesia:sync_dirty(fun() -&gt;
                 %% Still in a transaction context.
                 case mnesia:read( ..) ..end), end).
      add_subscriber2(S) -&gt;
          mnesia:sync_dirty(fun() -&gt;
             %% In dirty context 
             mnesia:read({some_tab, some_data}),
             mnesia:transaction(fun() -&gt;
                 %% In a transaction context.
                 case mnesia:read( ..) ..end), end).
    </pre></div>
  

  <h3><a name="id74476">4.7 
        Pattern Matching</a></h3>
    
    <a name="matching"></a>
    <p>When it is not possible to use <span class="code">mnesia:read/3</span> Mnesia
      provides the programmer with several functions for matching
      records against a pattern. The most useful functions of these are:
      </p>
    <div class="example"><pre>
      mnesia:select(Tab, MatchSpecification, LockKind) -&gt;
          transaction abort | [ObjectList]
      mnesia:select(Tab, MatchSpecification, NObjects, Lock) -&gt;  
          transaction abort | {[Object],Continuation} | '$end_of_table'
      mnesia:select(Cont) -&gt;
          transaction abort | {[Object],Continuation} | '$end_of_table'
      mnesia:match_object(Tab, Pattern, LockKind) -&gt;
          transaction abort | RecordList
    </pre></div>
    <p>These functions matches a <span class="code">Pattern</span> against all records in
      table <span class="code">Tab</span>. In a <span class="code">mnesia:select</span> call <span class="code">Pattern</span> is
      a part of <span class="code">MatchSpecification</span> 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 <span class="code">ordered_set</span> tables may reduce the
      search space if the keys are partially bound.
      </p>
    <p>The pattern provided to the functions must be a valid record,
      and the first element of the provided tuple must be the
      <span class="code">record_name</span> of the table. The special element <span class="code">'_'</span>
      matches any data structure in Erlang (also known as an Erlang
      term). The special elements <span class="code">'$&lt;number&gt;'</span> 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>
    <p>Use the function <span class="code">mnesia:table_info(Tab, wild_pattern)</span> 
      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.
      </p>
    <div class="example"><pre>
      Wildpattern = mnesia:table_info(employee, wild_pattern), 
      %% Or use
      Wildpattern = #employee{_ = '_'},
    </pre></div>
    <p>For the employee table the wild pattern will look like:</p>
    <div class="example"><pre>
      {employee, '_', '_', '_', '_', '_',' _'}.
    </pre></div>
    <p>In order to constrain the match you must replace some
      of the <span class="code">'_'</span> elements. The code for matching out
      all female employees, looks like:
      </p>
    <div class="example"><pre>
      Pat = #employee{sex = female, _ = '_'},
      F = fun() -&gt; mnesia:match_object(Pat) end,
      Females = mnesia:transaction(F).
    </pre></div>
    <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:
      </p>
    <div class="example"><pre>
      Pat = #employee{emp_no = '$1', room_no = '$1', _ = '_'},
      F = fun() -&gt; mnesia:match_object(Pat) end,
      Odd = mnesia:transaction(F).
    </pre></div>
    <p>The function <span class="code">mnesia:match_object/3</span> lacks some important
      features that <span class="code">mnesia:select/3</span> have. For example
      <span class="code">mnesia:match_object/3</span> 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:
      </p>
<div class="example"><pre>

      MatchHead = #employee{name='$1', sex=male, room_no={'$2', '_'}, _='_'},
      Guard = [{'&gt;=', '$2', 220},{'&lt;', '$2', 230}],
      Result = '$1',
      mnesia:select(employee,[{MatchHead, Guard, [Result]}])</pre></div>    <p>Select can be used to add additional constraints and create
      output which can not be done with <span class="code">mnesia:match_object/3</span>.  </p>
    <p>The second argument to select is a <span class="code">MatchSpecification</span>.
      A <span class="code">MatchSpecification</span> is list of <span class="code">MatchFunctions</span>, where
      each <span class="code">MatchFunction</span> consists of a tuple containing
      <span class="code">{MatchHead, MatchCondition, MatchBody}</span>.  <span class="code">MatchHead</span>
      is the same pattern used in <span class="code">mnesia:match_object/3</span> 
      described above. <span class="code">MatchCondition</span> is a list of additional
      constraints applied to each record, and <span class="code">MatchBody</span> is used 
      to construct the return values.
      </p>
    <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>
    <p>The functions <span class="code">select/4</span> and <span class="code">select/1</span> are used to
      get a limited number of results, where the <span class="code">Continuation</span>
      are used to get the next chunk of results. Mnesia uses the
      <span class="code">NObjects</span> as an recommendation only, thus more or less
      results then specified with <span class="code">NObjects</span> may be returned in
      the result list, even the empty list may be returned despite there
      are more results to collect.
      </p>
    <div class="warning">
<div class="label">Warning</div>
<div class="content"><p>
      <p>There is a severe performance penalty in using
        <span class="code">mnesia:select/[1|2|3|4]</span> after any modifying operations
        are done on that table in the same transaction, i.e. avoid using
        <span class="code">mnesia:write/1</span> or <span class="code">mnesia:delete/1</span> before a
        <span class="code">mnesia:select</span> in the same transaction.</p>
    </p></div>
</div>
    <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 <span class="code">'_'</span>, or <span class="code">'$1'</span>, the whole <span class="code">employee</span>
      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: <span class="bold_code"><a href="Mnesia_chap5.html#indexing">Indexing</a></span>) if
      <span class="code">mnesia:match_object</span> is used.
      </p>
    <p>QLC queries can also be used to search Mnesia tables.  By
      using <span class="code">mnesia:table/[1|2]</span> as the generator inside a QLC
      query you let the query operate on a mnesia table.  Mnesia
      specific options to <span class="code">mnesia:table/2</span> are {lock, Lock},
      {n_objects,Integer} and {traverse, SelMethod}. The <span class="code">lock</span>
      option specifies whether mnesia should acquire a read or write
      lock on the table, and <span class="code">n_objects</span> specifies how many
      results should be returned in each chunk to QLC. The last option is
      <span class="code">traverse</span> and it specifies which function mnesia should
      use to traverse the table. Default <span class="code">select</span> is used, but by using
      <span class="code">{traverse, {select, MatchSpecification}}</span> as an option to
      <span class="code">mnesia:table/2</span> the user can specify it's own view of the
      table.
      </p>
    <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.:
      </p>
    <div class="example"><pre>
      mnesia:table(Tab) -&gt;
          mnesia:table(Tab, [{n_objects,100},{lock, read}, {traverse, select}]).
    </pre></div>
    <p>The function <span class="code">mnesia:all_keys(Tab)</span> returns all keys in a
      table.</p>
  

  <h3><a name="id74822">4.8 
        Iteration</a></h3>
    
    <a name="iteration"></a>
    <p>Mnesia provides a couple of functions which iterates over all
      the records in a table. 
      </p>
    <div class="example"><pre>
      mnesia:foldl(Fun, Acc0, Tab) -&gt; NewAcc | transaction abort
      mnesia:foldr(Fun, Acc0, Tab) -&gt; NewAcc | transaction abort
      mnesia:foldl(Fun, Acc0, Tab, LockType) -&gt; NewAcc | transaction abort
      mnesia:foldr(Fun, Acc0, Tab, LockType) -&gt; NewAcc | transaction abort
    </pre></div>
    <p>These functions iterate over the mnesia table <span class="code">Tab</span> and
      apply the function <span class="code">Fun</span> to each record. The <span class="code">Fun</span>
      takes two arguments, the first argument is a record from the
      table and the second argument is the accumulator. The
      <span class="code">Fun</span> return a new accumulator. </p>
    <p>The first time the <span class="code">Fun</span> is applied <span class="code">Acc0</span> will
      be the second argument. The next time the <span class="code">Fun</span> 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 <span class="code">fold[lr]</span> function.
      </p>
    <p>The difference between <span class="code">foldl</span> and <span class="code">foldr</span> is the 
      order the table is accessed for <span class="code">ordered_set</span> tables,
      for every other table type the functions are equivalent.
      </p>
    <p><span class="code">LockType</span> specifies what type of lock that shall be 
      acquired for the iteration, default is <span class="code">read</span>. If
      records are written or deleted during the iteration a write 
      lock should be acquired. </p>
    <p>These functions might be used to find records in a table
      when it is impossible to write constraints for
      <span class="code">mnesia:match_object/3</span>, or when you want to perform 
      some action on certain records.       
      </p>
    <p>For example finding all the employees who has a salary 
      below 10 could look like:</p>
    <div class="example"><pre>
      find_low_salaries() -&gt;
        Constraint = 
             fun(Emp, Acc) when Emp#employee.salary &lt; 10 -&gt;
                    [Emp | Acc];
                (_, Acc) -&gt;
                    Acc
             end,
        Find = fun() -&gt; mnesia:foldl(Constraint, [], employee) end,
        mnesia:transaction(Find).
    </pre></div>
    <p>Raising the salary to 10 for everyone with a salary below 10
      and return the sum of all raises:</p>
    <div class="example"><pre>
      increase_low_salaries() -&gt;
         Increase = 
             fun(Emp, Acc) when Emp#employee.salary &lt; 10 -&gt;
                    OldS = Emp#employee.salary,
                    ok = mnesia:write(Emp#employee{salary = 10}),
                    Acc + 10 - OldS;
                (_, Acc) -&gt;
                    Acc
             end,
        IncLow = fun() -&gt; mnesia:foldl(Increase, 0, employee, write) end,
        mnesia:transaction(IncLow).
    </pre></div>
    <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>
    <p>Call these iteration functions on nodes that contain a replica of the
      table. Each call to the function <span class="code">Fun</span> access the table and if the table
      resides on another node it will generate a lot of unnecessary
      network traffic. </p>
    <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 <span class="code">ordered_set</span> 
      type.      </p>
    <div class="example"><pre>
      mnesia:first(Tab) -&gt;  Key | transaction abort
      mnesia:last(Tab)  -&gt;  Key | transaction abort
      mnesia:next(Tab,Key)  -&gt;  Key | transaction abort
      mnesia:prev(Tab,Key)  -&gt;  Key | transaction abort
      mnesia:snmp_get_next_index(Tab,Index) -&gt; {ok, NextIndex} | endOfTable
    </pre></div>
    <p>The order of first/last and next/prev are only valid for
      <span class="code">ordered_set</span> tables, for all other tables, they are synonyms.
      When the end of the table is reached the special key
      <span class="code">'$end_of_table'</span> is returned.</p>
    <p>If records are written and deleted during the traversal, use
      <span class="code">mnesia:fold[lr]/4</span> with a <span class="code">write</span> lock. Or
      <span class="code">mnesia:write_lock_table/1</span> when using first and next.</p>
    <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>
    <p>In dirty context, i.e. <span class="code">sync_dirty</span> or <span class="code">async_dirty</span>,
      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 <span class="code">mnesia:first/1</span> and
      <span class="code">mnesia:next/2</span> commands, the same drawbacks as described
      above for <span class="code">dirty_first</span> and <span class="code">dirty_next</span> applies, i.e. 
      no writes to the table should be done during iteration.</p>
    <p></p>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 1997-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>