File: Mnesia_chap2.html

package info (click to toggle)
erlang-doc-html 1%3A11.b.2-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 23,284 kB
  • ctags: 10,724
  • sloc: erlang: 505; ansic: 323; makefile: 62; perl: 61; sh: 45
file content (1112 lines) | stat: -rw-r--r-- 27,379 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
  <TITLE>Getting Started with Mnesia
</TITLE>
  <SCRIPT type="text/javascript" src="../../../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
      ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="2"><!-- Empty --></A>
<H2>2 Getting Started with Mnesia
</H2>

<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>
<A NAME="2.1"><!-- Empty --></A>
<H3>2.1 Starting Mnesia for the first time</H3>

<P>Following is a simplified demonstration of a Mnesia system startup. This is the dialogue from the Erlang
shell:


<PRE>
        unix&#62;  erl -mnesia dir '&#34;/tmp/funky&#34;'
        Erlang (BEAM) emulator version 4.9
        
        Eshell V4.9  (abort with ^G)
        1&#62; 
        1&#62; mnesia:create_schema([node()]).
        ok
        2&#62; mnesia:start().
        ok
        3&#62; mnesia:create_table(funky, []).
        {atomic,ok}
        4&#62; mnesia:info().
        ---&#62; Processes holding locks &#60;--- 
        ---&#62; Processes waiting for locks &#60;--- 
        ---&#62; Pending (remote) transactions &#60;--- 
        ---&#62; Active (local) transactions &#60;---
        ---&#62; Uncertain transactions &#60;--- 
        ---&#62; Active tables &#60;--- 
        funky          : with 0 records occupying 269 words of mem 
        schema         : with 2 records occupying 353 words of mem 
        ===&#62; System info in version &#34;1.0&#34;, debug level = none &#60;===
        opt_disc. Directory &#34;/tmp/funky&#34; 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>

<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 <CODE>-mnesia dir '&#34;/tmp/funky&#34;'</CODE>. 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 
<CODE>mnesia:create_schema([node()]).</CODE> The schema contains
information about the database in general. This will be
thoroughly explained later on.


</LI>


<LI>
 The DBMS was started by evaluating <CODE>mnesia:start()</CODE>.


</LI>


<LI>
 A first table was created, called <CODE>funky</CODE> by evaluating
the expression <CODE>mnesia:create_table(funky, [])</CODE>. The table
was given default properties.


</LI>


<LI>
 <CODE>mnesia:info()</CODE> was evaluated and subsequently displayed 
information regarding the status of the database on the terminal.


</LI>


</UL>
<A NAME="2.2"><!-- Empty --></A>
<H3>2.2 An Introductory Example</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>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>
<A NAME="2.2.1"><!-- Empty --></A>
<H4>2.2.1 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>
<CENTER>
<IMG ALT="company" SRC="company.gif"><BR>
<EM>Company Entity-Relation Diagram</EM>

</CENTER>

<P>The database model looks as follows:


<P>
<UL>

<LI>
There are three entities: employee, project, and
department. 


</LI>


<LI>
There are three relationships between these entities:


<OL>

<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>


</OL>



</LI>


</UL>
<A NAME="2.2.2"><!-- Empty --></A>
<H4>2.2.2 Defining Structure and Content</H4>

<P>We first enter our record definitions into a text file
named <CODE>company.hrl</CODE>. This file defines the following
structure for our sample database: 


<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>

<P>The structure defines six tables in our database. In Mnesia,
        the function <CODE>mnesia:create_table(Name, ArgList)</CODE> is
        used to create tables. <CODE>Name</CODE> 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:
        <A HREF="Mnesia_chap4.html#recordnames_tablenames"> Record Names Versus Table Names.</A>


<P>For example, the table
for employees will be created with the function
<CODE>mnesia:create_table(employee, [{attributes,
record_info(fields, employee)}]).</CODE> The table
name <CODE>employee</CODE> matches the name for records specified
in <CODE>ArgList</CODE>. The expression <CODE>record_info(fields,
RecordName)</CODE> is processed by the Erlang preprocessor and
evaluates to a list containing the names of the different
fields for a record. 

<A NAME="2.2.3"><!-- Empty --></A>
<H4>2.2.3 The Program</H4>

<P>The following shell interaction starts Mnesia and
initializes the schema for our <CODE>company</CODE> database: 



<PRE>

        % <STRONG>erl -mnesia dir '&#34;/ldisc/scratch/Mnesia.Company&#34;'</STRONG>
         Erlang (BEAM) emulator version 4.9
          
          Eshell V4.9  (abort with ^G)
          1&#62; mnesia:create_schema([node()]).
          ok
          2&#62; mnesia:start().
          ok

        
</PRE>

<P>The following program module creates and populates previously defined tables:


<PRE>

-include_lib(&#34;stdlib/include/qlc.hrl&#34;).
-include(&#34;company.hrl&#34;).

init() -&#62;
    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>
<A NAME="2.2.4"><!-- Empty --></A>
<H4>2.2.4 The Program Explained</H4>

<P>The following commands and functions were used to initiate the 
Company database:


<P>
<UL>

<LI>
<CODE>% erl -mnesia dir
'&#34;/ldisc/scratch/Mnesia.Company&#34;'.</CODE> This is a UNIX
command line entry which starts the Erlang system. The flag
<CODE>-mnesia dir Dir</CODE> specifies the location of the
database directory. The system responds and waits for
further input with the prompt <STRONG>1&#62;</STRONG>. 



</LI>


<LI>
<CODE>mnesia:create_schema([node()]).</CODE> This function
has the format <CODE>mnesia:create_schema(DiscNodeList)</CODE> 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:<A HREF="Mnesia_chap3.html#def_schema">Defining a Schema</A>. 



</LI>


<LI>
<CODE>mnesia:start().</CODE> This function starts
Mnesia. This function is fully explained in Chapter 3:
<A HREF="Mnesia_chap3.html#start_mnesia">Starting Mnesia</A>.


</LI>


</UL>

<P>Continuing the dialogue with the Erlang shell will produce the following
the following:


<PRE>
        3&#62; company:init().
        {atomic,ok}
        4&#62; mnesia:info().
        ---&#62; Processes holding locks &#60;--- 
        ---&#62; Processes waiting for locks &#60;--- 
        ---&#62; Pending (remote) transactions &#60;--- 
        ---&#62; Active (local) transactions &#60;---
        ---&#62; Uncertain transactions &#60;--- 
        ---&#62; Active tables &#60;--- 
        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 
        ===&#62; System info in version &#34;1.0&#34;, debug level = none &#60;===
        opt_disc. Directory &#34;/ldisc/scratch/Mnesia.Company&#34; 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>

<P> A set of tables is created:


<P>
<UL>

<LI>
<CODE>mnesia:create_table(Name,ArgList)</CODE>. This
function is used to create the required database tables. The
options available with <CODE>ArgList</CODE> are explained in
Chapter 3: <A HREF="Mnesia_chap3.html#create_tables">Creating New
Tables</A>. 
</LI>


</UL>

<P> The <CODE>company:init/0</CODE> function creates our tables. Two tables are
        of type <CODE>bag</CODE>. This is the <CODE>manager</CODE> relation as well
        the <CODE>in_proj</CODE> relation. This shall be interpreted as: An
        employee can be manager over several departments, and an employee
        can participate in several projects. However, the <CODE>at_dep</CODE>
        relation is <CODE>set</CODE> because an employee can only work in one department.
        In this data model we have examples of relations that are one-to-one (<CODE>set</CODE>),
        as well as one-to-many (<CODE>bag</CODE>).


<P><CODE>mnesia:info()</CODE> 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>To write a function which inserts an employee record into the database, there must be an 
         <CODE>at_dep</CODE> record and a set of <CODE>in_proj</CODE> records inserted. Examine the following
        code used to complete this action:


<PRE>

insert_emp(Emp, DeptId, ProjNames) -&#62;
    Ename = Emp#employee.name,
    Fun = fun() -&#62;
                  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]) -&#62;
    mnesia:write(#in_proj{emp = Ename, proj_name = ProjName}),
    mk_projs(Ename, Tail);
mk_projs(_, []) -&#62; ok.
    


</PRE>

<P>
<UL>

<LI>
<CODE>insert_emp(Emp, DeptId, ProjNames) -&#62;</CODE>. The
<CODE>insert_emp/3</CODE> arguments are:


<OL>

<LI>
<CODE>Emp</CODE> is an employee record.


</LI>


<LI>
<CODE>DeptId</CODE> is the identity of the department where the employee is working.


</LI>


<LI>
<CODE>ProjNames</CODE> is a list of the names of the projects where the employee are working.

</LI>


</OL>



</LI>


</UL>

<P>The <CODE>insert_emp(Emp, DeptId, ProjNames) -&#62;</CODE> function
        creates a <STRONG>functional object</STRONG>. Functional objects
        are identified by the term <CODE>Fun</CODE>. The Fun is passed
        as a single argument to the function
        <CODE>mnesia:transaction(Fun)</CODE>. 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:

<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>

<P>
<TABLE CELLPADDING=4>
  <TR>
    <TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
    <TD>

<P>Functional Objects (Funs) are described in the
Erlang Reference Manual, &#34;Fun Expressions&#34;. 

    </TD>
  </TR>
</TABLE>
<A NAME="2.2.5"><!-- Empty --></A>
<H4>2.2.5 Initial Database Content</H4>

<P> After the insertion of the employee named <CODE>klacke</CODE>
we have the following records in the database: 


<P>
<CENTER>
<TABLE CELLSPACING=0 CELLPADDING=2 BORDER=1>
  <CAPTION ALIGN=BOTTOM><EM><A NAME="table2_1"><!-- Empty --></A>Employee

</EM></CAPTION>
  <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>
</CENTER>

<P>An employee record has the following Erlang record/tuple
representation: <CODE>{employee, 104732, klacke, 7, male,
98108, {221, 015}}</CODE>


<P>
<CENTER>
<TABLE CELLSPACING=0 CELLPADDING=2 BORDER=1>
  <CAPTION ALIGN=BOTTOM><EM><A NAME="table2_2"><!-- Empty --></A>At_dep

</EM></CAPTION>
  <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>
</CENTER>

<P>At_dep has the following Erlang tuple representation:
<CODE>{at_dep, klacke, 'B/SFR'}</CODE>. 


<P>
<CENTER>
<TABLE CELLSPACING=0 CELLPADDING=2 BORDER=1>
  <CAPTION ALIGN=BOTTOM><EM><A NAME="table3_3"><!-- Empty --></A>In_proj

</EM></CAPTION>
  <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>
</CENTER>

<P>In_proj has the following Erlang tuple representation:
<CODE>{in_proj, klacke, 'Erlang', klacke, 'otp', klacke,
'mnesia'}</CODE> 


<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>A Mnesia table is populated by Mnesia records. For example,
the tuple <CODE>{boss, klacke, bjarne}</CODE> 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 <CODE>{boss, klacke, bjarne}</CODE> record is the arity two
tuple <CODE>{boss, klacke}</CODE>. 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 <CODE>set</CODE> or <CODE>bag</CODE>.


<P>We were also able to insert the <CODE>{boss, klacke,
bjarne}</CODE> record which contains an implicit reference to
another employee which does not yet exist in the
database. Mnesia does not enforce this. 

<A NAME="2.2.6"><!-- Empty --></A>
<H4>2.2.6 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><STRONG>Employees</STRONG>


<PRE>
        {employee, 104465, &#34;Johnson Torbjorn&#34;,   1, male,  99184, {242,038}}.
        {employee, 107912, &#34;Carlsson Tuula&#34;,     2, female,94556, {242,056}}.
        {employee, 114872, &#34;Dacker Bjarne&#34;,      3, male,  99415, {221,035}}.
        {employee, 104531, &#34;Nilsson Hans&#34;,       3, male,  99495, {222,026}}.
        {employee, 104659, &#34;Tornkvist Torbjorn&#34;, 2, male,  99514, {222,022}}.
        {employee, 104732, &#34;Wikstrom Claes&#34;,     2, male,  99586, {221,015}}.
        {employee, 117716, &#34;Fedoriw Anna&#34;,       1, female,99143, {221,031}}.
        {employee, 115018, &#34;Mattsson Hakan&#34;,     3, male,  99251, {203,348}}.
        
</PRE>

<P><STRONG>Dept</STRONG>


<PRE>

        {dept, 'B/SF',  &#34;Open Telecom Platform&#34;}.
        {dept, 'B/SFP', &#34;OTP - Product Development&#34;}.
        {dept, 'B/SFR', &#34;Computer Science Laboratory&#34;}.
        
</PRE>

<P><STRONG>Projects</STRONG>

<PRE>
        %% projects
        {project, erlang, 1}.
        {project, otp, 2}.
        {project, beam, 3}.
        {project, mnesia, 5}.
        {project, wolf, 6}.
        {project, documentation, 7}.
        {project, www, 8}.
        
</PRE>

<P>The above three tables, titled <CODE>employees</CODE>,
<CODE>dept</CODE>, and <CODE>projects</CODE>, 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 <CODE>manager</CODE>,
<CODE>at_dep</CODE>, and <CODE>in_proj</CODE>. 


<P><STRONG>Manager</STRONG>


<PRE>

        {manager, 104465, 'B/SF'}.
        {manager, 104465, 'B/SFP'}.
        {manager, 114872, 'B/SFR'}.
        
</PRE>

<P><STRONG>At_dep</STRONG>


<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>

<P><STRONG>In_proj</STRONG>


<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>

<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
<CODE>-record(room, {corr, no}).</CODE> instead of an anonymous
tuple representation. 


<P>The Company database is now initialized and contains
data. 
<A NAME="2.2.7"><!-- Empty --></A>
<H4>2.2.7 Writing Queries</H4>

<P> Retrieving data from DBMS should usually be done with <CODE>mnesia:read/3</CODE> or
        <CODE>mnesia:read/1</CODE> functions. The following function raises the salary:
<PRE>
raise(Eno, Raise) -&#62;
    F = fun() -&#62;
                [E] = mnesia:read(employee, Eno, write),
                Salary = E#employee.salary + Raise,
                New = E#employee{salary = Salary},
                mnesia:write(New)
        end,
    mnesia:transaction(F).

</PRE>

<P> Since we want to update the record using <CODE>mnesia:write/1</CODE> after we have 
        increased the salary we acquire a write lock (third argument to read) when we read the 
        record from the table.


<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 <CODE>mnesia:read</CODE> and should be avoided in performance 
        critical code.
<P> There are two methods for writing database queries:
        

<P>
<UL>

<LI>
Mnesia functions

        
</LI>


<LI>
QLC

</LI>


</UL>
<A NAME="2.2.7.1"><!-- Empty --></A>
<H5>2.2.7.1  Mnesia functions </H5>

<P>     
<P>The following function extracts the names of the female employees
         stored in the database: 


<PRE>
          mnesia:select(employee, [{#employee{sex = female, name = '$1', _ = '_'},[], ['$1']}]).
        
</PRE>

<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:


<PRE>
all_females() -&#62;
    F = fun() -&#62;
                Female = #employee{sex = female, name = '$1', _ = '_'},
                mnesia:select(employee, [{Female, [], ['$1']}])
        end,
    mnesia:transaction(F).

</PRE>

<P> The select expression matches all entries in table employee with
         the field sex set to female.

        
<P>This function can be called from the shell as follows:
         

<PRE>
          (klacke@gin)1&#62; <STRONG>company:all_females().</STRONG>
          {atomic,  [&#34;Carlsson Tuula&#34;, &#34;Fedoriw Anna&#34;]}
        
</PRE>

<P>See also the <A HREF="Mnesia_chap4.html#matching"> Pattern Matching </A>
         chapter for a description of select and its syntax.
         
        <A NAME="2.2.7.2"><!-- Empty --></A>
<H5>2.2.7.2  Using QLC </H5>

<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>The following function extracts a list of female employees
from the database: 


<PRE>
          Q = qlc:q([E#employee.name || E &#60;- mnesia:table(employee),
                                        E#employee.sex == female]),
          qlc:e(Q),
        
</PRE>

<P>Accessing mnesia tables from a QLC list comprehension must
         always be done within a transaction. Consider the following
         function:


<PRE>
females() -&#62;
    F = fun() -&#62;
                Q = qlc:q([E#employee.name || E &#60;- mnesia:table(employee),
                                              E#employee.sex == female]),
                qlc:e(Q)
        end,
    mnesia:transaction(F).

</PRE>

<P>This function can be called from the shell as follows:


<PRE>
          (klacke@gin)1&#62; <STRONG>company:females().</STRONG>
          {atomic, [&#34;Carlsson Tuula&#34;, &#34;Fedoriw Anna&#34;]}
        
</PRE>

<P>In traditional relational database terminology, the above
operation would be called a selection, followed by a projection. 


<P>The list comprehension expression shown above contains a
number of syntactical elements. 


<P>
<UL>

<LI>
the first <CODE>[</CODE> bracket should be read as &#34;build the
list&#34; 



</LI>


<LI>
the <CODE>||</CODE> &#34;such that&#34; and the arrow <CODE>&#60;-</CODE> should
be read as &#34;taken from&#34; 


</LI>


</UL>

<P>Hence, the above list comprehension demonstrates the
        formation of the list <CODE>E#employee.name</CODE> such that <CODE>E</CODE> is
taken from the table of employees and the <CODE>sex</CODE> attribute
of each records is equal with the atom <CODE>female</CODE>. 


<P>The whole list comprehension must be given to the
<CODE>qlc:q/1</CODE> function.


<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: 


<PRE>
raise_females(Amount) -&#62;
    F = fun() -&#62;
                Q = qlc:q([E || E &#60;- mnesia:table(employee),
                                E#employee.sex == female]),
                Fs = qlc:e(Q),
                over_write(Fs, Amount)
        end,
    mnesia:transaction(F).

over_write([E|Tail], Amount) -&#62;
    Salary = E#employee.salary + Amount,
    New = E#employee{salary = Salary},
    mnesia:write(New),
    1 + over_write(Tail, Amount);
over_write([], _) -&#62;
    0.

</PRE>

<P>The function <CODE>raise_females/1</CODE> returns the tuple
<CODE>{atomic, Number}</CODE>, where <CODE>Number</CODE> is the number of
female employees who received a salary increase. Should an error
occur, the value <CODE>{aborted, Reason}</CODE> is returned. In the
case of an error, Mnesia guarantees that the salary is not
raised for any employees at all. 


<PRE>

          33&#62;<STRONG> company:raise_females(33).</STRONG>
          {atomic,2}
        
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright &copy; 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>