<!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 -- Getting Started with Mnesia</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.4.13.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.4.13</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#id2264416">About Mnesia</a></li> <li title="The Mnesia DataBase Management System (DBMS)"><a href="Mnesia_chap1.html#id2259328">The Mnesia DataBase Management System (DBMS)</a></li> </ul> </li> <li id="loadscrollpos" title="Getting Started with Mnesia" expanded="true">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#id2259207">Starting Mnesia for the first time</a></li> <li title="An Introductory Example"><a href="Mnesia_chap2.html#id2259513">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#id2268730">Defining a Schema</a></li> <li title="The Data Model"><a href="Mnesia_chap3.html#id2269025">The Data Model</a></li> <li title="Starting Mnesia"><a href="Mnesia_chap3.html#id2269927">Starting Mnesia</a></li> <li title="Creating New Tables"><a href="Mnesia_chap3.html#id2270354">Creating New Tables</a></li> </ul> </li> <li id="no" title="Transactions and Other Access Contexts" expanded="false">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#id2270987">Transaction Properties</a></li> <li title="Locking"><a href="Mnesia_chap4.html#id2271248">Locking</a></li> <li title="Dirty Operations"><a href="Mnesia_chap4.html#id2271791">Dirty Operations</a></li> <li title="Record Names versus Table Names"><a href="Mnesia_chap4.html#id2272219">Record Names versus Table Names</a></li> <li title="Activity Concept and Various Access Contexts"><a href="Mnesia_chap4.html#id2272338">Activity Concept and Various Access Contexts</a></li> <li title="Nested transactions"><a href="Mnesia_chap4.html#id2272678">Nested transactions</a></li> <li title="Pattern Matching"><a href="Mnesia_chap4.html#id2272772">Pattern Matching</a></li> <li title="Iteration"><a href="Mnesia_chap4.html#id2273172">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#id2273564">Indexing</a></li> <li title="Distribution and Fault Tolerance"><a href="Mnesia_chap5.html#id2273702">Distribution and Fault Tolerance</a></li> <li title="Table Fragmentation"><a href="Mnesia_chap5.html#id2273885">Table Fragmentation</a></li> <li title="Local Content Tables"><a href="Mnesia_chap5.html#id2274960">Local Content Tables</a></li> <li title="Disc-less Nodes"><a href="Mnesia_chap5.html#id2274992">Disc-less Nodes</a></li> <li title="More Schema Management"><a href="Mnesia_chap5.html#id2275179">More Schema Management</a></li> <li title="Mnesia Event Handling"><a href="Mnesia_chap5.html#id2275329">Mnesia Event Handling</a></li> <li title="Debugging Mnesia Applications"><a href="Mnesia_chap5.html#id2275937">Debugging Mnesia Applications</a></li> <li title="Concurrent Processes in Mnesia"><a href="Mnesia_chap5.html#id2276097">Concurrent Processes in Mnesia</a></li> <li title="Prototyping"><a href="Mnesia_chap5.html#id2276148">Prototyping</a></li> <li title="Object Based Programming with Mnesia"><a href="Mnesia_chap5.html#id2276292">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#id2276572">Database Configuration Data</a></li> <li title="Core Dumps"><a href="Mnesia_chap7.html#id2276614">Core Dumps</a></li> <li title="Dumping Tables"><a href="Mnesia_chap7.html#id2276638">Dumping Tables</a></li> <li title="Checkpoints"><a href="Mnesia_chap7.html#id2276678">Checkpoints</a></li> <li title="Files"><a href="Mnesia_chap7.html#id2276957">Files</a></li> <li title="Loading of Tables at Start-up"><a href="Mnesia_chap7.html#id2277368">Loading of Tables at Start-up</a></li> <li title="Recovery from Communication Failure"><a href="Mnesia_chap7.html#id2277560">Recovery from Communication Failure</a></li> <li title="Recovery of Transactions"><a href="Mnesia_chap7.html#id2277693">Recovery of Transactions</a></li> <li title="Backup, Fallback, and Disaster Recovery"><a href="Mnesia_chap7.html#id2277864">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#id2278809">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#id2278969">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#id2279207">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#id2279378">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#id2279587">mnesia_frag_hash callback behavior</a></li> </ul> </li> </ul> </div></div> <div id="content"> <div class="innertube"> <h1>2 Getting Started with Mnesia</h1> <p>This chapter introduces Mnesia. Following a brief discussion about the first initial setup, a Mnesia database example is demonstrated. This database example will be referenced in the following chapters, where this example is modified in order to illustrate various program constructs. In this chapter, the following mandatory procedures are illustrated by examples: </p> <ul> <li>Starting an Erlang session and specifying a directory for the Mnesia database. </li> <li>Initializing a database schema. </li> <li>Starting Mnesia and creating the required tables.</li> </ul> <h3><a name="id2259207">2.1 Starting Mnesia for the first time</a></h3> <p>Following is a simplified demonstration of a Mnesia system startup. This is the dialogue from the Erlang shell: </p> <div class="example"><pre> unix> erl -mnesia dir '"/tmp/funky"' Erlang (BEAM) emulator version 4.9 Eshell V4.9 (abort with ^G) 1> 1> mnesia:create_schema([node()]). ok 2> mnesia:start(). ok 3> mnesia:create_table(funky, []). {atomic,ok} 4> mnesia:info(). ---> Processes holding locks <--- ---> Processes waiting for locks <--- ---> Pending (remote) transactions <--- ---> Active (local) transactions <--- ---> Uncertain transactions <--- ---> Active tables <--- funky : with 0 records occupying 269 words of mem schema : with 2 records occupying 353 words of mem ===> System info in version "1.0", debug level = none <=== opt_disc. Directory "/tmp/funky" is used. use fall-back at restart = false running db nodes = [nonode@nohost] stopped db nodes = [] remote = [] ram_copies = [funky] disc_copies = [schema] disc_only_copies = [] [{nonode@nohost,disc_copies}] = [schema] [{nonode@nohost,ram_copies}] = [funky] 1 transactions committed, 0 aborted, 0 restarted, 1 logged to disc 0 held locks, 0 in queue; 0 local transactions, 0 remote 0 transactions waits for other nodes: [] ok </pre></div> <p>In the example above the following actions were performed: </p> <ul> <li>The Erlang system was started from the UNIX prompt with a flag <span class="code">-mnesia dir '"/tmp/funky"'</span>. This flag indicates to Mnesia which directory will store the data. </li> <li>A new empty schema was initialized on the local node by evaluating <span class="code">mnesia:create_schema([node()]).</span> The schema contains information about the database in general. This will be thoroughly explained later on. </li> <li>The DBMS was started by evaluating <span class="code">mnesia:start()</span>. </li> <li>A first table was created, called <span class="code">funky</span> by evaluating the expression <span class="code">mnesia:create_table(funky, [])</span>. The table was given default properties. </li> <li> <span class="code">mnesia:info()</span> was evaluated and subsequently displayed information regarding the status of the database on the terminal. </li> </ul> <h3><a name="id2259513">2.2 An Introductory Example</a></h3> <p>A Mnesia database is organized as a set of tables. Each table is populated with instances (Erlang records). A table also has a number of properties, such as location and persistence. </p> <p>In this example we shall: </p> <ul> <li>Start an Erlang system, and specify the directory where the database will be located. </li> <li>Initiate a new schema with an attribute that specifies on which node, or nodes, the database will operate. </li> <li>Start Mnesia itself. </li> <li>Create and populate the database tables. </li> </ul> <h4>The Example Database</h4> <p>In this database example, we will create the database and relationships depicted in the following diagram. We will call this database the <strong>Company</strong> database. </p> <img alt="IMAGE MISSING" src="company.gif"><br> <em>Figure 2.1: Company Entity-Relation Diagram</em> <p>The database model looks as follows: </p> <ul> <li>There are three entities: employee, project, and department. </li> <li> <p>There are three relationships between these entities:</p> <ul> <li>A department is managed by an employee, hence the <strong>manager</strong> relationship. </li> <li>An employee works at a department, hence the <strong>at_dep</strong> relationship. </li> <li>Each employee works on a number of projects, hence the <strong>in_proj</strong> relationship. </li> </ul> </li> </ul> <h4>Defining Structure and Content</h4> <p>We first enter our record definitions into a text file named <span class="code">company.hrl</span>. This file defines the following structure for our sample database: </p> <div class="example"><pre> -record(employee, {emp_no, name, salary, sex, phone, room_no}). -record(dept, {id, name}). -record(project, {name, number}). -record(manager, {emp, dept}). -record(at_dep, {emp, dept_id}). -record(in_proj, {emp, proj_name}). </pre></div> <p>The structure defines six tables in our database. In Mnesia, the function <span class="code">mnesia:create_table(Name, ArgList)</span> is used to create tables. <span class="code">Name</span> is the table name <strong>Note:</strong> The current version of Mnesia does not require that the name of the table is the same as the record name, See Chapter 4: <span class="bold_code"><a href="Mnesia_chap4.html#recordnames_tablenames">Record Names Versus Table Names.</a></span></p> <p>For example, the table for employees will be created with the function <span class="code">mnesia:create_table(employee, [{attributes, record_info(fields, employee)}]).</span> The table name <span class="code">employee</span> matches the name for records specified in <span class="code">ArgList</span>. The expression <span class="code">record_info(fields, RecordName)</span> is processed by the Erlang preprocessor and evaluates to a list containing the names of the different fields for a record. </p> <h4>The Program</h4> <p>The following shell interaction starts Mnesia and initializes the schema for our <span class="code">company</span> database: </p> <div class="example"><pre> % <span class="bold_code">erl -mnesia dir '"/ldisc/scratch/Mnesia.Company"'</span> Erlang (BEAM) emulator version 4.9 Eshell V4.9 (abort with ^G) 1> mnesia:create_schema([node()]). ok 2> mnesia:start(). ok </pre></div> <p>The following program module creates and populates previously defined tables: </p> <div class="example"><pre> -include_lib("stdlib/include/qlc.hrl"). -include("company.hrl"). init() -> mnesia:create_table(employee, [{attributes, record_info(fields, employee)}]), mnesia:create_table(dept, [{attributes, record_info(fields, dept)}]), mnesia:create_table(project, [{attributes, record_info(fields, project)}]), mnesia:create_table(manager, [{type, bag}, {attributes, record_info(fields, manager)}]), mnesia:create_table(at_dep, [{attributes, record_info(fields, at_dep)}]), mnesia:create_table(in_proj, [{type, bag}, {attributes, record_info(fields, in_proj)}]). </pre></div> <h4>The Program Explained</h4> <p>The following commands and functions were used to initiate the Company database: </p> <ul> <li> <span class="code">% erl -mnesia dir '"/ldisc/scratch/Mnesia.Company"'.</span> This is a UNIX command line entry which starts the Erlang system. The flag <span class="code">-mnesia dir Dir</span> specifies the location of the database directory. The system responds and waits for further input with the prompt <strong>1></strong>. </li> <li> <span class="code">mnesia:create_schema([node()]).</span> This function has the format <span class="code">mnesia:create_schema(DiscNodeList)</span> and initiates a new schema. In this example, we have created a non-distributed system using only one node. Schemas are fully explained in Chapter 3:<span class="bold_code"><a href="Mnesia_chap3.html#def_schema">Defining a Schema</a></span>. </li> <li> <span class="code">mnesia:start().</span> This function starts Mnesia. This function is fully explained in Chapter 3: <span class="bold_code"><a href="Mnesia_chap3.html#start_mnesia">Starting Mnesia</a></span>. </li> </ul> <p>Continuing the dialogue with the Erlang shell will produce the following the following: </p> <div class="example"><pre> 3> company:init(). {atomic,ok} 4> mnesia:info(). ---> Processes holding locks <--- ---> Processes waiting for locks <--- ---> Pending (remote) transactions <--- ---> Active (local) transactions <--- ---> Uncertain transactions <--- ---> Active tables <--- in_proj : with 0 records occuping 269 words of mem at_dep : with 0 records occuping 269 words of mem manager : with 0 records occuping 269 words of mem project : with 0 records occuping 269 words of mem dept : with 0 records occuping 269 words of mem employee : with 0 records occuping 269 words of mem schema : with 7 records occuping 571 words of mem ===> System info in version "1.0", debug level = none <=== opt_disc. Directory "/ldisc/scratch/Mnesia.Company" is used. use fall-back at restart = false running db nodes = [nonode@nohost] stopped db nodes = [] remote = [] ram_copies = [at_dep,dept,employee,in_proj,manager,project] disc_copies = [schema] disc_only_copies = [] [{nonode@nohost,disc_copies}] = [schema] [{nonode@nohost,ram_copies}] = [employee,dept,project,manager,at_dep,in_proj] 6 transactions committed, 0 aborted, 0 restarted, 6 logged to disc 0 held locks, 0 in queue; 0 local transactions, 0 remote 0 transactions waits for other nodes: [] ok </pre></div> <p>A set of tables is created: </p> <ul> <li> <span class="code">mnesia:create_table(Name,ArgList)</span>. This function is used to create the required database tables. The options available with <span class="code">ArgList</span> are explained in Chapter 3: <span class="bold_code"><a href="Mnesia_chap3.html#create_tables">Creating New Tables</a></span>. </li> </ul> <p>The <span class="code">company:init/0</span> function creates our tables. Two tables are of type <span class="code">bag</span>. This is the <span class="code">manager</span> relation as well the <span class="code">in_proj</span> relation. This shall be interpreted as: An employee can be manager over several departments, and an employee can participate in several projects. However, the <span class="code">at_dep</span> relation is <span class="code">set</span> because an employee can only work in one department. In this data model we have examples of relations that are one-to-one (<span class="code">set</span>), as well as one-to-many (<span class="code">bag</span>). </p> <p><span class="code">mnesia:info()</span> now indicates that a database which has seven local tables, of which, six are our user defined tables and one is the schema. Six transactions have been committed, as six successful transactions were run when creating the tables. </p> <p>To write a function which inserts an employee record into the database, there must be an <span class="code">at_dep</span> record and a set of <span class="code">in_proj</span> records inserted. Examine the following code used to complete this action: </p> <div class="example"><pre> insert_emp(Emp, DeptId, ProjNames) -> Ename = Emp#employee.name, Fun = fun() -> mnesia:write(Emp), AtDep = #at_dep{emp = Ename, dept_id = DeptId}, mnesia:write(AtDep), mk_projs(Ename, ProjNames) end, mnesia:transaction(Fun). mk_projs(Ename, [ProjName|Tail]) -> mnesia:write(#in_proj{emp = Ename, proj_name = ProjName}), mk_projs(Ename, Tail); mk_projs(_, []) -> ok. </pre></div> <ul> <li> <p><span class="code">insert_emp(Emp, DeptId, ProjNames) -></span>. The <span class="code">insert_emp/3</span> arguments are:</p> <ul> <li> <span class="code">Emp</span> is an employee record. </li> <li> <span class="code">DeptId</span> is the identity of the department where the employee is working. </li> <li> <span class="code">ProjNames</span> is a list of the names of the projects where the employee are working.</li> </ul> </li> </ul> <p>The <span class="code">insert_emp(Emp, DeptId, ProjNames) -></span> function creates a <strong>functional object</strong>. Functional objects are identified by the term <span class="code">Fun</span>. The Fun is passed as a single argument to the function <span class="code">mnesia:transaction(Fun)</span>. This means that Fun is run as a transaction with the following properties: </p> <ul> <li>Fun either succeeds or fails completely. </li> <li>Code which manipulates the same data records can be run concurrently without the different processes interfering with each other. </li> </ul> <p>The function can be used as:</p> <div class="example"><pre> Emp = #employee{emp_no= 104732, name = klacke, salary = 7, sex = male, phone = 98108, room_no = {221, 015}}, insert_emp(Me, 'B/SFR', [Erlang, mnesia, otp]). </pre></div> <div class="note"> <div class="label">Note</div> <div class="content"><p> <p>Functional Objects (Funs) are described in the Erlang Reference Manual, "Fun Expressions". </p> </p></div> </div> <h4>Initial Database Content</h4> <p>After the insertion of the employee named <span class="code">klacke</span> we have the following records in the database: </p> <a name="table2_1"></a> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle">emp_no</td> <td align="left" valign="middle">name</td> <td align="left" valign="middle">salary</td> <td align="left" valign="middle">sex</td> <td align="left" valign="middle">phone</td> <td align="left" valign="middle">room_no</td> </tr> <tr> <td align="left" valign="middle">104732</td> <td align="left" valign="middle">klacke</td> <td align="left" valign="middle">7</td> <td align="left" valign="middle">male</td> <td align="left" valign="middle">99586</td> <td align="left" valign="middle">{221, 015}</td> </tr> </table> <em>Table 2.1: Employee</em> <p>An employee record has the following Erlang record/tuple representation: <span class="code">{employee, 104732, klacke, 7, male, 98108, {221, 015}}</span></p> <a name="table2_2"></a> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle">emp</td> <td align="left" valign="middle">dept_name</td> </tr> <tr> <td align="left" valign="middle">klacke</td> <td align="left" valign="middle">B/SFR</td> </tr> </table> <em>Table 2.2: At_dep</em> <p>At_dep has the following Erlang tuple representation: <span class="code">{at_dep, klacke, 'B/SFR'}</span>. </p> <a name="table3_3"></a> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle">emp</td> <td align="left" valign="middle">proj_name</td> </tr> <tr> <td align="left" valign="middle">klacke</td> <td align="left" valign="middle">Erlang</td> </tr> <tr> <td align="left" valign="middle">klacke</td> <td align="left" valign="middle">otp</td> </tr> <tr> <td align="left" valign="middle">klacke</td> <td align="left" valign="middle">mnesia</td> </tr> </table> <em>Table 2.3: In_proj</em> <p>In_proj has the following Erlang tuple representation: <span class="code">{in_proj, klacke, 'Erlang', klacke, 'otp', klacke, 'mnesia'}</span></p> <p>There is no difference between rows in a table and Mnesia records. Both concepts are the same and will be used interchangeably throughout this book. </p> <p>A Mnesia table is populated by Mnesia records. For example, the tuple <span class="code">{boss, klacke, bjarne}</span> is an record. The second element in this tuple is the key. In order to uniquely identify a table row both the key and the table name is needed. The term <strong>object identifier</strong>, (oid) is sometimes used for the arity two tuple {Tab, Key}. The oid for the <span class="code">{boss, klacke, bjarne}</span> record is the arity two tuple <span class="code">{boss, klacke}</span>. The first element of the tuple is the type of the record and the second element is the key. An oid can lead to zero, one, or more records depending on whether the table type is <span class="code">set</span> or <span class="code">bag</span>. </p> <p>We were also able to insert the <span class="code">{boss, klacke, bjarne}</span> record which contains an implicit reference to another employee which does not yet exist in the database. Mnesia does not enforce this. </p> <h4>Adding Records and Relationships to the Database</h4> <p>After adding additional record to the Company database, we may end up with the following records: </p> <p><strong>Employees</strong></p> <div class="example"><pre> {employee, 104465, "Johnson Torbjorn", 1, male, 99184, {242,038}}. {employee, 107912, "Carlsson Tuula", 2, female,94556, {242,056}}. {employee, 114872, "Dacker Bjarne", 3, male, 99415, {221,035}}. {employee, 104531, "Nilsson Hans", 3, male, 99495, {222,026}}. {employee, 104659, "Tornkvist Torbjorn", 2, male, 99514, {222,022}}. {employee, 104732, "Wikstrom Claes", 2, male, 99586, {221,015}}. {employee, 117716, "Fedoriw Anna", 1, female,99143, {221,031}}. {employee, 115018, "Mattsson Hakan", 3, male, 99251, {203,348}}. </pre></div> <p><strong>Dept</strong></p> <div class="example"><pre> {dept, 'B/SF', "Open Telecom Platform"}. {dept, 'B/SFP', "OTP - Product Development"}. {dept, 'B/SFR', "Computer Science Laboratory"}. </pre></div> <p><strong>Projects</strong></p> <div class="example"><pre> %% projects {project, erlang, 1}. {project, otp, 2}. {project, beam, 3}. {project, mnesia, 5}. {project, wolf, 6}. {project, documentation, 7}. {project, www, 8}. </pre></div> <p>The above three tables, titled <span class="code">employees</span>, <span class="code">dept</span>, and <span class="code">projects</span>, are the tables which are made up of real records. The following database content is stored in the tables which is built on relationships. These tables are titled <span class="code">manager</span>, <span class="code">at_dep</span>, and <span class="code">in_proj</span>. </p> <p><strong>Manager</strong></p> <div class="example"><pre> {manager, 104465, 'B/SF'}. {manager, 104465, 'B/SFP'}. {manager, 114872, 'B/SFR'}. </pre></div> <p><strong>At_dep</strong></p> <div class="example"><pre> {at_dep, 104465, 'B/SF'}. {at_dep, 107912, 'B/SF'}. {at_dep, 114872, 'B/SFR'}. {at_dep, 104531, 'B/SFR'}. {at_dep, 104659, 'B/SFR'}. {at_dep, 104732, 'B/SFR'}. {at_dep, 117716, 'B/SFP'}. {at_dep, 115018, 'B/SFP'}. </pre></div> <p><strong>In_proj</strong></p> <div class="example"><pre> {in_proj, 104465, otp}. {in_proj, 107912, otp}. {in_proj, 114872, otp}. {in_proj, 104531, otp}. {in_proj, 104531, mnesia}. {in_proj, 104545, wolf}. {in_proj, 104659, otp}. {in_proj, 104659, wolf}. {in_proj, 104732, otp}. {in_proj, 104732, mnesia}. {in_proj, 104732, erlang}. {in_proj, 117716, otp}. {in_proj, 117716, documentation}. {in_proj, 115018, otp}. {in_proj, 115018, mnesia}. </pre></div> <p>The room number is an attribute of the employee record. This is a structured attribute which consists of a tuple. The first element of the tuple identifies a corridor, and the second element identifies the actual room in the corridor. We could have chosen to represent this as a record <span class="code">-record(room, {corr, no}).</span> instead of an anonymous tuple representation. </p> <p>The Company database is now initialized and contains data. </p> <h4>Writing Queries</h4> <p>Retrieving data from DBMS should usually be done with <span class="code">mnesia:read/3</span> or <span class="code">mnesia:read/1</span> functions. The following function raises the salary:</p> <div class="example"><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></div> <p>Since we want to update the record using <span class="code">mnesia:write/1</span> after we have increased the salary we acquire a write lock (third argument to read) when we read the record from the table. </p> <p>It is not always the case that we can directly read the values from the table, we might need to search the table or several tables to get the data we want, this is done by writing database queries. Queries are always more expensive operations than direct lookups done with <span class="code">mnesia:read</span> and should be avoided in performance critical code.</p> <p>There are two methods for writing database queries: </p> <ul> <li>Mnesia functions </li> <li>QLC</li> </ul> <p></p> <p>The following function extracts the names of the female employees stored in the database: </p> <div class="example"><pre> \011 mnesia:select(employee, [{#employee{sex = female, name = '$1', _ = '_'},[], ['$1']}]). </pre></div> <p>Select must always run within an activity such as a transaction. To be able to call from the shell we might construct a function as: </p> <div class="example"><pre> all_females() -> F = fun() -> Female = #employee{sex = female, name = '$1', _ = '_'}, mnesia:select(employee, [{Female, [], ['$1']}]) end, mnesia:transaction(F).</pre></div> <p>The select expression matches all entries in table employee with the field sex set to female. </p> <p>This function can be called from the shell as follows: </p> <div class="example"><pre> (klacke@gin)1> <span class="bold_code">company:all_females().</span> {atomic, ["Carlsson Tuula", "Fedoriw Anna"]} </pre></div> <p>See also the <span class="bold_code"><a href="Mnesia_chap4.html#matching">Pattern Matching </a></span> chapter for a description of select and its syntax. </p> <p>This section contains simple introductory examples only. Refer to <strong>QLC reference manual</strong> for a full description of the QLC query language. Using QLC might be more expensive than using Mnesia functions directly but offers a nice syntax. </p> <p>The following function extracts a list of female employees from the database: </p> <div class="example"><pre> Q = qlc:q([E#employee.name || E <- mnesia:table(employee), \011 E#employee.sex == female]), \011 qlc:e(Q), </pre></div> <p>Accessing mnesia tables from a QLC list comprehension must always be done within a transaction. Consider the following function: </p> <div class="example"><pre> females() -> F = fun() -> Q = qlc:q([E#employee.name || E <- mnesia:table(employee), E#employee.sex == female]), qlc:e(Q) end, mnesia:transaction(F).</pre></div> <p>This function can be called from the shell as follows: </p> <div class="example"><pre> (klacke@gin)1> <span class="bold_code">company:females().</span> {atomic, ["Carlsson Tuula", "Fedoriw Anna"]} </pre></div> <p>In traditional relational database terminology, the above operation would be called a selection, followed by a projection. </p> <p>The list comprehension expression shown above contains a number of syntactical elements. </p> <ul> <li>the first <span class="code">[</span> bracket should be read as "build the list" </li> <li>the <span class="code">||</span> "such that" and the arrow <span class="code"><-</span> should be read as "taken from" </li> </ul> <p>Hence, the above list comprehension demonstrates the formation of the list <span class="code">E#employee.name</span> such that <span class="code">E</span> is taken from the table of employees and the <span class="code">sex</span> attribute of each records is equal with the atom <span class="code">female</span>. </p> <p>The whole list comprehension must be given to the <span class="code">qlc:q/1</span> function. </p> <p>It is possible to combine list comprehensions with low level Mnesia functions in the same transaction. If we want to raise the salary of all female employees we execute: </p> <div class="example"><pre> raise_females(Amount) -> F = fun() -> Q = qlc:q([E || E <- mnesia:table(employee), E#employee.sex == female]), Fs = qlc:e(Q), over_write(Fs, Amount) end, mnesia:transaction(F). over_write([E|Tail], Amount) -> Salary = E#employee.salary + Amount, New = E#employee{salary = Salary}, mnesia:write(New), 1 + over_write(Tail, Amount); over_write([], _) -> 0.</pre></div> <p>The function <span class="code">raise_females/1</span> returns the tuple <span class="code">{atomic, Number}</span>, where <span class="code">Number</span> is the number of female employees who received a salary increase. Should an error occur, the value <span class="code">{aborted, Reason}</span> is returned. In the case of an error, Mnesia guarantees that the salary is not raised for any employees at all. </p> <div class="example"><pre> 33><span class="bold_code">company:raise_females(33).</span> {atomic,2} </pre></div> </div> <div class="footer"> <hr> <p>Copyright © 1997-2010 Ericsson AB. All Rights Reserved.</p> </div> </div> </div></body> </html>