File: MnesiaSessionExamples.html

package info (click to toggle)
erlang-doc-html 1%3A10.b.1a-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 22,488 kB
  • ctags: 9,933
  • sloc: erlang: 505; ansic: 323; perl: 61; sh: 45; makefile: 39
file content (533 lines) | stat: -rw-r--r-- 15,981 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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.2 -->
<HTML>
<HEAD>
  <TITLE>Session Examples</TITLE>
  <SCRIPT type="text/javascript" src="../../../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
      ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="4"><!-- Empty --></A>
<H2>4 Session Examples</H2>
<A NAME="4.1"><!-- Empty --></A>
<H3>4.1 Example Introduction</H3>

<P> In this and the following chapter several examples of the usage
of the Mnesia_Session interface will be introduced. The
examples will first be written in Erlang and than the same
functionality will be shown in a foreign language.

<P> The examples will contain some basic operations, create_table, write and
read records both via the <CODE>mnesia_session</CODE> and the 
<CODE>mnesia_corba_session</CODE> interfaces.
<A NAME="4.1.1"><!-- Empty --></A>
<H4>4.1.1 Data Definition</H4>
<A NAME="exdatadef"><!-- Empty --></A>
<P>     A simple database has been created, with people as the subject. The person
        record containing other data types will be demonstrated in the
        rest of the examples. To begin with we define the data types that 
        will be used in IDL.

<PRE>
//
// A simple example on different structures used to access mnesia from
// the outside 
//
// If the tables and structures should be accessed through a corba
// interface, they need to be defined in a IDL specification so that
// the mnesia_session interface can access the types needed to use
// corba type any.
//

module persons
{
  enum Sex {male, female};

  struct data
  {
    Sex sex;
    long age;
    long phone;
  };
  
  struct person 
  {
    string name;                 // Used as key
    data personData;             // A reference to other data structure
    string married_to;           // A relation 
    sequence &#60;string&#62; children;  // A list
  };

};


</PRE>

<P>     Observe that the struct person, when mapping from IDL to Erlang, is prefixed
        with the module name followed by '_'. In this example, the
        table name would be <CODE>persons_person</CODE>. If this is not
        wanted the struct definition should be placed on the top level,
        i.e. above the module definition.
<A NAME="4.2"><!-- Empty --></A>
<H3>4.2 A Session Example in Erlang</H3>

<P> A simplified example of a client written in Erlang to access
<CODE>Mnesia</CODE> via the session interface is shown below. 


<P>Compile the person data definitions with:

<PRE>
erlc +'{be, erl_genserv}' person.idl
</PRE>

<P>Include the necessary files:
<PRE>
%% Include to get the mnesia types, used in create table
-include_lib(&#34;mnesia_session/include/mnesia.hrl&#34;).   

%% Include my own definitions
-include(&#34;persons.hrl&#34;).  

</PRE>

<P>Find the connector and create a private session:
<PRE>
start_session(Node) -&#62;
    ConnPid = rpc:call(Node, mnesia_session_lib, lookup_connector, []),
    %% Use the factory to create a session
    SessPid = mnesia_connector:connect(ConnPid),
    {ConnPid, SessPid}.

</PRE>

<P> In this example, we used
<CODE>mnesia_session_lib:lookup_connector/0</CODE> but it is also possible to
use <CODE>erlang:whereis(mnesia_connector)</CODE>.
In Erlang, objects are represented as processes. To access the method 
of the object, call the method where the first argument is the object 
reference, as in <CODE>mnesia_connector:connect(ConnPid)</CODE>.


<P> All functions in the IDL specification have an additional first
argument which is the object reference. More information is given in the
<CODE>IC</CODE> and <CODE>Orber</CODE> documentation.

<P> To create a table with the structure defined in the IDL
definition, we use the function create_person_table.


<P> Define the table properties and call the function:

<PRE>
create_person_table(ObjKey) -&#62;
    %% Define the table properties
    Attrs = [atom_to_list(F) || F &#60;- record_info(fields, persons_person)],
    TabDef = #mnesia_TableDef{type = bag, mode = read_write, 
                              ram_copies = [],
                              disc_copies = [], 
                              disc_only_copies = [],
                              index_list = [4],  %% Index on married_to
                              attributes = Attrs,
                              %% OBSERVE that the record_name must be 
                              %% exactly the same as the name of the 
                              %% structure/record  
                              record_name = &#34;persons_person&#34;},
    
    Res = mnesia_session:create_table(ObjKey, &#34;persons&#34;, TabDef),
    case Res of 
        {ok, &#34;&#34;} -&#62;    
            ok;
        Else-&#62;
            io:format(&#34;ERROR: ~s~n&#34;, [Else])
    end.

</PRE>

<P> The example insert and a read operation looks like:

<PRE>
insert_person(SessionKey, Name, Sex, Age, Phone, Mt, Ch) 
  when list(Name), atom(Sex), integer(Age), 
       integer(Phone), list(Mt), list(Ch) -&#62;
    
    Data = #persons_data{sex = Sex, age = Age, phone = Phone},
    Person = #persons_person{name = Name, personData = Data, 
                             married_to = Mt, children = Ch},
    
    {ok, &#34;&#34;} = mnesia_session:dirty_write(SessionKey, &#34;persons&#34;, Person),
    Person.

</PRE>

<PRE>
get_person(SessionKey, Name) when list(Name) -&#62;
    {ok, RObj, &#34;&#34;} = 
        mnesia_session:dirty_read(SessionKey, &#34;persons&#34;, Name),    
    hd(RObj).

</PRE>
<A NAME="4.3"><!-- Empty --></A>
<H3>4.3 A Session Example in Java</H3>

<P> Compile the person data definitions:

<PRE>
erlc +'{be, java}' person.idl
</PRE>

<P>Import the necessary files.
<PRE>
import com.ericsson.otp.ic.*;

</PRE>

<P>Find the connector and create a private session:
<PRE>
  public static mnesia._sessionStub start_session(String args[])
    {
      String SNode = new String(args[0]);
      String PNode = new String(args[1]);
      String Cookie = new String(args[2]);

      mnesia._connectorStub mccRef = null;
      mnesia._sessionStub mcsRef = null;
               
      try
        {
          
          mccRef = new mnesia._connectorStub(SNode+&#34;0&#34;,PNode,Cookie,
                                             &#34;mnesia_connector&#34;);
          
          com.ericsson.otp.ic.Pid mccPid = mccRef.connect();
          
          mcsRef = new mnesia._sessionStub(SNode+&#34;1&#34;,PNode,Cookie,mccPid);

          return mcsRef;
        }
      catch(Exception se)
        {
          System.out.println(&#34;Unexpected exception: &#34; + se.toString());
          se.printStackTrace();
          return null;
        }
    }

</PRE>

<P> To create a table with the structure defined in the IDL definition, we 
use the function create_person_table. Define the table properties and 
call the function.

<PRE>
  public static void create_person_table(mnesia._sessionStub mcsRef)
    {
      try {
      
        String name = &#34;persons&#34;;
        mnesia.TableDef def = new mnesia.TableDef();
        def.type = mnesia.SetOrBag.bag;
        def.mode = mnesia.AccessMode.read_write;
        def.ram_copies = new String[0];
        def.disc_copies = new String[0];
        def.disc_only_copies = new String[0];
        int[] idxs = new int[1];
        idxs[0] = 4;
        def.index_list = idxs;
        String[] attrs = new String[4];
        attrs[0] = &#34;name&#34;;
        attrs[1] = &#34;personData&#34;;
        attrs[2] = &#34;married_to&#34;;
        attrs[3] = &#34;children&#34;;
        def.attributes = attrs;
        def.record_name = &#34;persons_person&#34;; // The used IDL type
        
        StringHolder reason;
        reason = new StringHolder();
        
        if(mnesia.Status.ok != mcsRef.create_table(name, def, reason))
          System.out.println(&#34;Create Table Error &#34; + reason.value); 
      }
      catch(Exception se)
        {
          System.out.println(&#34;Unexpected exception: &#34; + se.toString());
          return;
        } 
    }

</PRE>

<P> The example insert and a read operation looks like: 

<PRE>
  public static void insert_person(mnesia._sessionStub mcsRef,
                                   String name,
                                   persons.Sex sex,
                                   int age,
                                   int phone,
                                   String mt,
                                   java.lang.String[] children)
    {
      persons.data data;
      data = new persons.data(sex, age, phone);
      persons.person person = new persons.person();
      person.name = name;
      person.personData = data;
      person.married_to = mt;
      person.children = children;
      
      try
        {
          StringHolder reason = new StringHolder();       
          Term object = new Term();
          persons.personHelper.insert(object,person);
          
          if(mnesia.Status.ok != mcsRef.dirty_write(&#34;persons&#34;, object, reason))
            System.out.println(&#34;Insert person Error &#34; + reason.value);
        }
      catch(Exception se)
        {
          System.out.println(&#34;Unexpected exception: &#34; + se.toString());
          return;
        }
    }

</PRE>

<PRE>
  public static persons.person 
    get_person(mnesia._sessionStub mcsRef, String name)
    {   
      try
        {
          StringHolder reason = new StringHolder();       
          Term key = new Term();
          mnesia.RecordlistHolder res = new mnesia.RecordlistHolder();
          key.insert_string(name);

          if(mnesia.Status.ok == mcsRef.dirty_read(&#34;persons&#34;, 
                                                   key, res, reason))
            {
              if(res.value.length &#62; 0) 
                {
                  persons.person rec1 = 
                    persons.personHelper.extract(res.value[0]);

                  return rec1;
                }
              else
                return null;                        
            }
          else
            {
              System.out.println(&#34;Insert person Error &#34; + reason.value);
              return null;
            }
        }
        catch(Exception se)
          {
            System.out.println(&#34;Unexpected exception: &#34; + se.toString());
            return null;
          }     
    }

</PRE>

<P> <STRONG>Note:</STRONG> the usage of <CODE>ETERM</CODE> differs a little to the CORBA case, when using Java it mapps to the <CODE>Term</CODE> class which inherits from <CODE>Any</CODE> class.
<A NAME="4.4"><!-- Empty --></A>
<H3>4.4 A Session Example in C</H3>

<P> Compile the person data definitions:

<PRE>
erlc +'{be, c_genserv}' person.idl
</PRE>

<P>Include the necessary files.
<PRE>
#include &#60;erl_interface.h&#62;
#include &#34;mnesia_session.h&#34;
#include &#34;mnesia_connector.h&#34;
#include &#34;persons.h&#34;
#include &#60;ic.h&#62;

</PRE>

<P>Find the connector and create a private session:
<PRE>
erlang_pid start_session(CORBA_Environment * env)
{
    erlang_pid session_pid;
    
    session_pid = mnesia_connector_connect(NULL, env);
    
    if(env-&#62;_major != CORBA_NO_EXCEPTION) 
        handle_error(&#34;connector_connect&#34;, env);
    return session_pid;
}

</PRE>

<P> To create a table with the structure defined in the IDL definition, we 
use the function create_person_table. Define the table properties and 
call the function.

<PRE>
void create_person_table(CORBA_Environment * env)
{
    int err;
    char * reason;
    mnesia_Status result;    
    mnesia_TableDef tabdef;
    mnesia_Indices idxs;
    
    long idx_list[1] = {4};
    char * attrs[4] = {&#34;name&#34;, &#34;personData&#34;, &#34;married_to&#34;, &#34;children&#34;};
    
    tabdef.type = mnesia_bag;
    tabdef.mode = mnesia_read_write;

    tabdef.ram_copies._maximum = 0;
    tabdef.ram_copies._length = 0;
    tabdef.ram_copies._buffer = NULL;
    
    tabdef.disc_copies._maximum = 0;
    tabdef.disc_copies._length = 0;
    tabdef.disc_copies._buffer = NULL;

    tabdef.disc_only_copies._maximum = 0;
    tabdef.disc_only_copies._length = 0;
    tabdef.disc_only_copies._buffer = NULL;
    
    tabdef.index_list._maximum = 5;
    tabdef.index_list._length = 1;
    tabdef.index_list._buffer = idx_list;

    tabdef.attributes._maximum = 5;
    tabdef.attributes._length = 4;
    tabdef.attributes._buffer = attrs;
   
    tabdef.record_name = &#34;persons_person&#34;; /* The name of the stored 
                                              type/struct */

    result = mnesia_session_create_table(NULL, &#34;persons&#34;, &#38;tabdef, &#38;reason, env);

    if(env-&#62;_major != CORBA_NO_EXCEPTION)
    {   
        fprintf(stderr,&#34;\n error in create_table: %d\n&#34;, env-&#62;_major);
        exit(1);
    }
    else if(result != mnesia_ok)
    {
        fprintf(stderr, &#34;Create table failed with reason %s&#34;, reason);
    }
    CORBA_free(reason);
}

</PRE>

<P> The example insert and a read operation looks like: 

<PRE>
void insert_person(CORBA_Environment * env,
                   char *name, persons_Sex sex, int age, 
                   int phone, char * mt, persons_person_children * ch)
{
    ETERM *person, *children, *temp;
    int err, i;
    char * reason;
    mnesia_Status result;
    extern char * oe_persons_Sex[];
    
    children = erl_mk_empty_list();
    
    if(ch != NULL)
        for(i = 0; i &#60; ch-&#62;_length; i++)
        {
            temp = erl_mk_string(ch-&#62;_buffer[i]);
            children = erl_cons(temp, children);
            erl_free_term(temp);
        };
    
    person = erl_format(&#34;{persons_person,~s,{persons_data,~a,~i,~i}, ~s, ~w}&#34;,
                        name, oe_persons_Sex[sex], age, phone, mt, children);
    
    result = mnesia_session_dirty_write(NULL, &#34;persons&#34;, person, &#38;reason, env);
    
    if(env-&#62;_major != CORBA_NO_EXCEPTION) 
    {   
        fprintf(stderr,&#34;\n error in insert_person: %d\n&#34;, env-&#62;_major);
        exit(1);
    }
    else if(result != mnesia_ok)
    {
        fprintf(stderr, &#34;Insert person failed with reason %s&#34;, reason); 
        exit(-1);
    }
    
    erl_free_term(children);
    erl_free_term(person);    
    
    CORBA_free(reason);
}

</PRE>

<PRE>
void get_person(CORBA_Environment * env, char * name, persons_person * person)
{
    int err, i;
    char * reason;
    mnesia_Status result;
    mnesia_Recordlist *rec_list;
    ETERM * key;

    key = erl_mk_string(name);
    
    result = mnesia_session_dirty_read(NULL, &#34;persons&#34;, key, &#38;rec_list, 
                                       &#38;reason, env);
    if(env-&#62;_major != CORBA_NO_EXCEPTION) 
    {   
        fprintf(stderr,&#34;\n error in get_person: %d\n&#34;, env-&#62;_major);
        exit(1);
    }
    else if(result != mnesia_ok)
    {
        fprintf(stderr, &#34;Get person failed with reason %s&#34;, reason);    
        exit(-1);
    }
    
    if(rec_list-&#62;_length &#62; 0)
    {
        /* Only interrested in the first match */
        decode_person(rec_list-&#62;_buffer[0], person);
        for(i=0; i &#60; rec_list-&#62;_length; i++)
            erl_free_term(rec_list-&#62;_buffer[i]);
    }
    else 
    {
        fprintf(stderr, &#34;Insert person failed empty_list returned &#34;);   
        exit(-1);
    }
    
    CORBA_free(rec_list);
    CORBA_free(reason);
    erl_free_term(key);
}

</PRE>

<P> <STRONG>Note:</STRONG> the usage of <CODE>ETERM</CODE> differs when using C as the user must develop their own code to create and extract information from the <CODE>ETERM</CODE> structures, whereas, CORBA does this automatically.
<CENTER>
<HR>
<SMALL>
Copyright &copy; 1991-2004
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>