~ubuntu-branches/ubuntu/precise/libtangram-perl/precise

« back to all changes in this revision

Viewing changes to Tangram/Tour.pod

  • Committer: Bazaar Package Importer
  • Author(s): Stephen Zander
  • Date: 2001-09-21 10:20:34 UTC
  • Revision ID: james.westby@ubuntu.com-20010921102034-tohkprbnz4n1aua0
Tags: upstream-2.04
ImportĀ upstreamĀ versionĀ 2.04

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
=head1 NAME
 
2
 
 
3
Tangram - Guided Tour
 
4
 
 
5
=head1 INTRODUCTION
 
6
 
 
7
In this tour, we add persistence to a simple Person design.
 
8
 
 
9
A Person is either a NaturalPerson or a LegalPerson. Persons (in
 
10
general) have a collection of addresses.
 
11
 
 
12
An address consists in a type (a string) and a city (also a string).
 
13
 
 
14
NaturalPerson - a subclass of Person - represents persons of flesh and
 
15
blood. NaturalPersons have a name and a firstName (both strings) and
 
16
an age (an integer). NaturalPersons sometimes have a partner (another
 
17
NaturalPerson) and even children (a collection of NaturalPersons).
 
18
 
 
19
LegalPerson - another subclass of Person - represents companies and
 
20
other entities that the law regards as 'persons'. A LegalPerson has a
 
21
name (a string) and a manager (a NaturalPerson).
 
22
 
 
23
All this is expressed in the following UML diagram:
 
24
 
 
25
 
 
26
                       +---------------------+        +--------------+ 
 
27
                       |       Person        |        |    Address   |
 
28
                       |     { abstract }    |1<>-->-*|--------------|
 
29
                       |---------------------|        | kind: string |
 
30
                       +---------------------+        | city: string |
 
31
                                   |                  +--------------+
 
32
                                   |
 
33
                    +--------------A--------------+
 
34
                    |                             |             
 
35
          +-------------------+           +---------------+          
 
36
      +--*|   NaturalPerson   |           |  LegalPerson  |        
 
37
      |   |-------------------|manager    |---------------|
 
38
      V   | firstName: string |1---<-----1| name: string  |        
 
39
      |   | name: string      |           +---------------+        
 
40
      +--*| age: integer      |
 
41
 children +-------------------+
 
42
                1       1 
 
43
                |    partner
 
44
                |       |
 
45
                +--->---+
 
46
 
 
47
B<Note that Tangram does I<not> create the corresponding Perl
 
48
packages!>. That's up to the user. However, to facilitate
 
49
experimentation, Tangram comes with a module that implements the
 
50
necessary classes. For more information see L<Tangram::Springfield>.
 
51
 
 
52
Before we can actually store objects we must complete two steps:
 
53
 
 
54
=over 4
 
55
 
 
56
=item 1
 
57
 
 
58
Create a Schema
 
59
 
 
60
=item 2
 
61
 
 
62
Create a database
 
63
 
 
64
=back
 
65
 
 
66
=head2 Creating a Schema
 
67
 
 
68
A Schema object contains information about the persistent
 
69
aspects of a system of classes.
 
70
 
 
71
It also gives a degree of control over the way Tangram performs the
 
72
object-relational mapping, but in this tour we will use all the defaults.
 
73
 
 
74
Here is the Schema for Springfield:
 
75
 
 
76
   $schema = Tangram::Relational->schema( {
 
77
 
 
78
      classes => [
 
79
 
 
80
       Person => {
 
81
          abstract => 1,
 
82
      
 
83
          fields => {
 
84
              iarray => {
 
85
                 addresses => { class => 'Address', aggreg => 1 } }
 
86
          }
 
87
       },
 
88
 
 
89
      Address => {
 
90
         fields => {
 
91
            string => [ qw( kind city ) ],
 
92
         },
 
93
      },
 
94
 
 
95
      NaturalPerson => {
 
96
 
 
97
         bases => [ qw( Person ) ],
 
98
 
 
99
         fields => {
 
100
            string   => [ qw( firstName name ) ],
 
101
            int      => [ qw( age ) ],
 
102
            ref      => [ qw( partner ) ],
 
103
            array    => { children => 'NaturalPerson' },
 
104
         }
 
105
      },
 
106
 
 
107
      LegalPerson => {
 
108
         bases => [ qw( Person ) ],
 
109
 
 
110
         fields => {
 
111
            string   => [ qw( name ) ],
 
112
            ref      => [ qw( manager ) ],
 
113
            }
 
114
         },
 
115
   ] } );
 
116
 
 
117
The Schema lists all the classes that need persistence, along with
 
118
their attributes and the inheritance relationships.  We must provide
 
119
type information for the attributes, because SQL is more typed than
 
120
Perl.  We also tell Tangram that C<Person> is an abstract class, so it
 
121
wastes no time attempting to retrieve objects of that exact class.
 
122
 
 
123
Note that Tangram cannot deduce this information by itself. While Perl
 
124
makes it possible to extract the list of all the classes in an
 
125
application, in general not all classes will need to persist. A class
 
126
may have both persistent and non-persistent bases.  As for attributes,
 
127
Perl's most typical representation for objects - a hash - even allows
 
128
two objects of the same class to have a different set of attributes.
 
129
 
 
130
For more information on creating Schemas, see L<Tangram::Relational>
 
131
and  L<Tangram::Schema>.
 
132
 
 
133
=head2 Setting up a database
 
134
 
 
135
Now we create a database. The simplest way is to create an
 
136
empty database and let Tangram initialize it:
 
137
    use Tangram;
 
138
 
 
139
    $dbh = DBI->connect(
 
140
        @cp );  
 
141
 
 
142
    Tangram::Relational->deploy($schema, $dbh );
 
143
 
 
144
    $dbh->disconnect();
 
145
 
 
146
Tangram::Relational is the vanilla object-relational backend. It
 
147
assumes that the database understands standard SQL, and that both the
 
148
database and the related DBI driver fully implements the DBI
 
149
specification.
 
150
 
 
151
Tangram also comes with vendor-specific backends for Mysql and
 
152
Sybase. When a vendor-specific backend exists, it should be used in
 
153
place of the vanilla backend.
 
154
 
 
155
For more information, see L<Tangram::Relational>, L<Tangram::Sybase>
 
156
and L<Tangram::mysql>.
 
157
 
 
158
=head2 Connecting to a database
 
159
 
 
160
We are now ready to store objects. First we connect to the database,
 
161
using the class method Tangram::Relational::connect (or
 
162
Tangram::mysql::connect for Mysql).
 
163
 
 
164
The first argument of connect() the schema object; the others are
 
165
passed directly to DBI::connect. The method returns a Tangram::Storage
 
166
object that will be used to communicate with the database.
 
167
 
 
168
For example:
 
169
 
 
170
    $storage = Tangram::Relational->connect( $schema,
 
171
        @cp );
 
172
 
 
173
connects to a database named Springfield via the vanilla Relational
 
174
backend, using a specific account and password.
 
175
 
 
176
For more information on connecting to databases, see  L<Tangram::Relational> and
 
177
L<Tangram::Storage>.
 
178
 
 
179
=head2 Inserting objects
 
180
 
 
181
Now we can populate the database:
 
182
 
 
183
   $storage->insert( NaturalPerson->new(
 
184
      firstName => 'Montgomery', name => 'Burns' ) );
 
185
 
 
186
This inserts a single NaturalPerson object into the database. We can
 
187
insert several objects in one call:
 
188
 
 
189
   $storage->insert(
 
190
      NaturalPerson->new( firstName => 'Patty', name => 'Bouvier' ),
 
191
      NaturalPerson->new( firstName => 'Selma', name => 'Bouvier' ) );
 
192
 
 
193
Sometimes Tangram saves objects implicitly:
 
194
 
 
195
    @kids = (
 
196
        NaturalPerson->new( firstName => 'Bart', name => 'Simpson' ),
 
197
        NaturalPerson->new( firstName => 'Lisa', name => 'Simpson' ) );
 
198
 
 
199
    $marge = NaturalPerson->new(
 
200
        firstName => 'Marge', name => 'Simpson',
 
201
        addresses => [
 
202
            Address->new(
 
203
                kind => 'residence', city => 'Springfield' ) ],
 
204
        children => [ @kids ] );
 
205
 
 
206
    $homer = NaturalPerson->new( firstName => 'Homer', name => 'Simpson',
 
207
        addresses => [
 
208
            Address->new(
 
209
                kind => 'residence', city => 'Springfield' ),
 
210
            Address->new(
 
211
                kind => 'work', city => 'Springfield' ) ],
 
212
        children => [ @kids ] );
 
213
 
 
214
    $homer->{partner} = $marge;
 
215
    $marge->{partner} = $homer;
 
216
   
 
217
    $homer_id = $storage->insert( $homer );
 
218
 
 
219
In the process of saving Homer, Tangram detects that it contains
 
220
references to objects that are not persistent yet (Marge, the
 
221
addresses and the kids), and inserts them automatically. Note that
 
222
Tangram can handle cycles: Homer and Marge refer to each other.
 
223
 
 
224
insert() returns an object id, or a list of object ids, that uniquely
 
225
identify the object(s) that have been inserted.
 
226
 
 
227
For more information on inserting objects, see L<Tangram::Storage>.
 
228
 
 
229
=head2 Updating objects
 
230
 
 
231
Updating works pretty much the same as inserting:
 
232
 
 
233
    my $maggie = NaturalPerson->new(
 
234
      firstName => 'Maggie', name => 'Simpson' );
 
235
 
 
236
    push @{ $homer->{children} }, $maggie;
 
237
    push @{ $marge->{children} }, $maggie;
 
238
 
 
239
    $storage->update( $homer, $marge );
 
240
 
 
241
Here again Tangram detects that Maggie is not already persistent in
 
242
$storage and automatically inserts it. Note that we need to update
 
243
Marge explicitly because she was already persistent.
 
244
 
 
245
For more information on updating objects, see L<Tangram::Storage>.
 
246
 
 
247
=head2 Memory management
 
248
 
 
249
...is still up to you. Tangram won't break in-memory cycles, it's a
 
250
persistence tool, not a memory management tool. Let's make sure we
 
251
don't leak objects:
 
252
 
 
253
   $homer->{partner} = undef; # do this before $homer goes out of scope
 
254
 
 
255
Also, when we're finished with a storage, we can explicitly disconnect it:
 
256
 
 
257
   $storage->disconnect();
 
258
 
 
259
Whether it's important or not to disconnect the Storage depends on
 
260
what version of Perl you use. If it's prior to 5.6, you I<must>
 
261
disconnect the storage explicitly (or at least call unload())
 
262
otherwise the Storage will prevent the objects it controls from being
 
263
reclaimed by Perl. For more information see see L<Tangram::Storage>.
 
264
 
 
265
=head2 Finding objects
 
266
 
 
267
After reconnecting to Springfield, we now want to retrieve some objects.
 
268
But how do we find them? Basically there are three options
 
269
 
 
270
=over 4
 
271
 
 
272
=item *
 
273
 
 
274
We know their IDs.
 
275
 
 
276
=item *
 
277
 
 
278
We obtain them from another object.
 
279
 
 
280
=item *
 
281
 
 
282
We use a query.
 
283
 
 
284
=back
 
285
 
 
286
=head2 Loading by ID
 
287
 
 
288
When an object is inserted, Tangram assigns an identifier to it.
 
289
IDs are numbers that uniquely identify objects in the database.
 
290
C<insert> returns the ID(s) of the object(s) it was passed:
 
291
 
 
292
    $storage = Tangram::Relational->connect( $schema,
 
293
        @cp );
 
294
 
 
295
    $ned_id = $storage->insert( NaturalPerson->new(
 
296
        firstNname => 'Ned', name => 'Flanders' ) );
 
297
 
 
298
    @sisters_id = $storage->insert(
 
299
        NaturalPerson->new( firstName => 'Patty', name => 'Bouvier' ),
 
300
        NaturalPerson->new( firstName => 'Selma', name => 'Bouvier' ) );
 
301
 
 
302
This enables us to retrieve the objects:
 
303
 
 
304
    $ned = $storage->load( $ned_id );
 
305
    @sisters = $storage->load( @sisters_id );
 
306
 
 
307
For more information on loading objects by id, see L<Tangram::Storage>.
 
308
 
 
309
=head2 Obtaining objects from other objects
 
310
 
 
311
Once Homer has been restored to his previous state, including his relations
 
312
with his family. Thus we can say:
 
313
 
 
314
    $storage = Tangram::Relational->connect( $schema,
 
315
        @cp );
 
316
 
 
317
    $homer = $storage->load( $homer_id ); # load by id
 
318
 
 
319
    $marge = $homer->{partner};
 
320
    @kids = @{ $homer->{children} };
 
321
 
 
322
Actually, when Tangram loads an object that contains references to
 
323
other persistent objects, it doesn't retrieve the referenced objects
 
324
immediately. Marge is retrieved only when Homer's 'partner' field is
 
325
accessed.  This mechanism is almost totally transparent, we'd have to
 
326
use C<tied> to observe a non-present collection or reference.
 
327
 
 
328
For more information on relationships, see L<Tangram::Schema>,
 
329
L<Tangram::Ref>, L<Tangram::Array>, L<Tangram::IntrArray>,
 
330
L<Tangram::Set> and L<Tangram::IntrSet>.
 
331
 
 
332
=head2 select
 
333
 
 
334
To retrieve all the objects of a given class, we use C<select>:
 
335
 
 
336
    $storage = Tangram::Relational->connect( $schema,
 
337
        @cp );
 
338
 
 
339
    my @people = $storage->select( 'NaturalPerson' );
 
340
 
 
341
Tangram supports polymorphic retrieval. Let's first insert a
 
342
LegalPerson:
 
343
 
 
344
    $storage->insert( LegalPerson->new(
 
345
        name => 'Springfield Nuclear Power Plant', manager => $burns ) );
 
346
 
 
347
 
 
348
Now we can retrieve all the Persons - Natural or Legal - by making a
 
349
single call to select(), passing it the base class name:
 
350
 
 
351
    my @all = $storage->select( 'Person' );
 
352
 
 
353
For more information on select(), see L<Tangram::Storage>.
 
354
 
 
355
=head2 Filtering
 
356
 
 
357
Usually we won't want to load I<all> the NaturalPersons, only those
 
358
objects that satisfy some condition. Say, for example, that we want to
 
359
load only the NaturalPersons whose name field is 'Simpson'. Here's how
 
360
this can be done:
 
361
 
 
362
    my $person = $storage->remote( 'NaturalPerson' );
 
363
    my @simpsons = $storage->select( $person, $person->{name} eq 'Simpson' );
 
364
 
 
365
This will bring in memory only the Simpsons; Burns or the Bouvier
 
366
sisters won't turn up.  The filtering happens on the database server
 
367
side, not in Perl space. Internally, Tangram translates the
 
368
C<$person->{name} eq 'Simpson'> clause into a piece of SQL code that
 
369
is passed down to the database.
 
370
 
 
371
The above example only begins to scratch the surface of Tangram's
 
372
filtering capabilities. The following examples are all legal and working code:
 
373
 
 
374
    # find all the persons *not* named Simpson
 
375
 
 
376
    my $person = $storage->remote( 'NaturalPerson' );
 
377
    my @others = $storage->select( $person, $person->{name} ne 'Simpson' );
 
378
 
 
379
    # same thing in a different way
 
380
 
 
381
    my $person = $storage->remote( 'NaturalPerson' );
 
382
    my @others = $storage->select( $person, !($person->{name} eq 'Simpson') );
 
383
 
 
384
    # find all the persons who are older than me
 
385
 
 
386
    my $person = $storage->remote( 'NaturalPerson' );
 
387
    my @elders = $storage->select( $person, $person->{age} > 35 );
 
388
 
 
389
    # find all the Simpsons older than me
 
390
 
 
391
    my $person = $storage->remote( 'NaturalPerson' );
 
392
    my @simpsons = $storage->select( $person,
 
393
        $person->{name} eq 'Simpson' & $person->{age} > 35 );
 
394
 
 
395
    # find Homer's wife - note that select *must* be called in list context
 
396
 
 
397
    my ($person1, $person2) = $storage->remote(
 
398
        qw( NaturalPerson NaturalPerson ));
 
399
 
 
400
    my ($marge) = $storage->select( $person1,
 
401
        $person1->{partner} == $person2
 
402
        & $person2->{firstName} eq 'Homer' & $person2->{name} eq 'Simpson' );
 
403
 
 
404
    # find Homer's wife - this time Homer is already in memory
 
405
 
 
406
    my $homer = $storage->load( $homer_id );
 
407
    my $person = $storage->remote( 'NaturalPerson' );
 
408
 
 
409
    my ($marge) = $storage->select( $person,
 
410
        $person->{partner} == $homer );
 
411
 
 
412
    # find everybody who works in Springfield
 
413
 
 
414
    my $address = $storage->remote( 'Address' );
 
415
 
 
416
    my @population = $storage->select( $person,
 
417
        $person->{addresses}->includes( $address )
 
418
        & $address->{kind} eq 'work'
 
419
        & $address->{city} eq 'Springfield');
 
420
 
 
421
    # find the parents of Bart Simpson
 
422
 
 
423
    my ($person1, $person2) = $storage->remote(
 
424
        qw( NaturalPerson NaturalPerson ));
 
425
 
 
426
    my @parents = $storage->select( $person1,
 
427
        $person1->{children}->includes( $person2 )
 
428
           & $person2->{firstName} eq 'Bart'
 
429
           & $person2->{name} eq 'Simpson' );
 
430
 
 
431
    # load Bart
 
432
    my ($bart) = $storage->select( $person1, $person1->{firstName} eq 'Bart');
 
433
 
 
434
    # find the parents of Bart, this time given an object already loaded
 
435
    my $person = $storage->remote( 'NaturalPerson' );
 
436
 
 
437
    @parents = $storage->select( $person,
 
438
        $person->{children}->includes( $bart ) );
 
439
 
 
440
Note that Tangram uses a single ampersand (&) or vertical bar (|) to
 
441
represent logical conjunction or disjunction, not the usual && or
 
442
||. This is due to a limitation in Perl's operator overloading
 
443
mechanism. Make sure you never forget this, because, unfortunately,
 
444
using && or || in place of & or | is not even a syntax error :(
 
445
 
 
446
Finally, Tangram make it possible to retrieve tuples of related objects:
 
447
 
 
448
    my ($parent, $child) = $storage->remote('NaturalPerson', 'NaturalPerson');
 
449
 
 
450
    @pairs = $storage->select( [ $parent, $child ],
 
451
        $parent->{children}->includes($child) );
 
452
 
 
453
@pairs contains a list of references to arrays of size two; each array
 
454
contains a pair of parent and child.
 
455
 
 
456
For more information on filters, see L<Tangram::Expr> and L<Tangram::Remote>.
 
457
 
 
458
=head2 Cursors
 
459
 
 
460
Cursors provide a way of retrieving objects one at a time.  This is
 
461
important is the result set is potentially large.  cursor() takes the
 
462
same arguments as select() and returns a Cursor objects that can be
 
463
used to iterate over the result set via methods current() and next():
 
464
 
 
465
    $storage = Tangram::Relational->connect( $schema,
 
466
        @cp );
 
467
 
 
468
    # iterate over all the NaturalPersons in storage
 
469
 
 
470
    my $cursor = $storage->cursor( 'NaturalPerson' );
 
471
 
 
472
    while (my $person = $cursor->current())
 
473
    {
 
474
        # process $person
 
475
        $cursor->next();
 
476
    }
 
477
 
 
478
    $cursor->close();
 
479
 
 
480
The Cursor will be automatically closed when $cursor is garbage-collected,
 
481
but Perl doesn't define just when that may happen :( Thus it's a good idea to
 
482
explicitly close the cursor.
 
483
 
 
484
Each Cursor uses a separate connection to the database. Consequently you can
 
485
have several cursors open at the same, all with pending results. Of course,
 
486
mixing reads and writes to the same tables can result in deadlocks.
 
487
 
 
488
For more information on cursors, see L<Tangram::Storage> and
 
489
L<Tangram::Cursor>.
 
490
 
 
491
=head2 Remote objects
 
492
 
 
493
At this point, most people wonder what $person I<exactly> is and how
 
494
it all works.  This section attempts to give an idea of the mechanisms
 
495
that are used.
 
496
 
 
497
In Tangram terminology, $person a I<remote> object. Its Perl class is
 
498
Tangram::Remote, but it's really a placeholder for an object of class
 
499
C<NaturalPerson> I<in the database>, much like a table alias in
 
500
SQL-speak.
 
501
 
 
502
When you request a remote object of a given class, Tangram arranges
 
503
that the remote object I<looks like> an object of the said class. It
 
504
I<seems> to have the same fields as a regular object, but don't be
 
505
misled, it's not the real thing, it's just a way of providing a nice
 
506
syntax.
 
507
 
 
508
If you dig it, you'll find out that a Remote is just a hash of
 
509
Tangram::Expr objects.  When you say $homer->{name}, an Expr is
 
510
returned, which, most of the time, can be used like any ordinary Perl
 
511
scalar. However, an Expr represents a value I<in the database>, it's
 
512
the equivalent of Remote, only for expressions, not for objects.
 
513
 
 
514
Expr objects that represent scalar values (e.g. ints, floats, strings)
 
515
can be compared between them, or compared with straight Perl
 
516
scalars. Reference-like Exprs can be compared between themselves and
 
517
with references
 
518
 
 
519
Expr objects that represent collections have an C<include> methods
 
520
that take a persistent object, a Remote object or an ID.
 
521
 
 
522
The result of comparing Exprs (or calling C<include>) is a
 
523
Tangram::Filter that will translate into part of the SQL where-clause
 
524
that will be passed to the RDBMS.
 
525
 
 
526
For more information on remote objects, see L<Tangram::Remote>.
 
527
 
 
528
=head2 Multiple loads
 
529
 
 
530
What happens when we load the same object twice? Consider:
 
531
 
 
532
    my $person = $storage->remote( 'NaturalPerson' );
 
533
    my @simpsons = $storage->select( $person, $person->{name} eq 'Simpson' );
 
534
 
 
535
    my @people = $storage->select( 'NaturalPerson' );
 
536
 
 
537
Obviously Homer Simpson will be retrieved by both selects. Are there
 
538
two Homers in memory now? Fortunately not. There is only one copy of
 
539
Homer in memory. When Tangram load an object, it checks whether an
 
540
object with the same ID is alredy present. If yes, it keeps the old
 
541
copy, which is desirable, since we may have changed it already.
 
542
 
 
543
Incidentally, this explains why a Storage will hold objects in memory
 
544
- until disconnected (again, this will change when Perl supports weak
 
545
references).
 
546
 
 
547
=head2 Transactions
 
548
 
 
549
Tangram wraps database transactions in a object-oriented interface:
 
550
 
 
551
    $storage->tx_start();
 
552
    $homer->{partner} = $marge;
 
553
    $marge->{partner} = $homer;
 
554
    $storage->update( $homer, $marge );
 
555
    $storage->tx_commit();
 
556
 
 
557
Both Marge and Homer will be updated, or none will. tx_rollback() drops
 
558
the changes.
 
559
 
 
560
Tangram does not emulate transactions for databases that do not
 
561
support them (like earlier versions of mySql).
 
562
 
 
563
Unlike DBI, Tangram allows the nested transactions:
 
564
 
 
565
    $storage->tx_start();
 
566
 
 
567
    {
 
568
        $storage->tx_start();
 
569
        $patty->{partner} = $selma;
 
570
        $selma->{partner} = $patty;
 
571
        $storage->tx_commit();
 
572
    }
 
573
 
 
574
    $homer->{partner} = $marge;
 
575
    $marge->{partner} = $homer;
 
576
    $storage->update( $homer, $marge );
 
577
 
 
578
    $storage->tx_commit();
 
579
 
 
580
Tangram uses a single database transaction, but commits it only when
 
581
the tx_commit()s exactly balance the tx_start()s. Thanks to this
 
582
feature any piece of code can open all the transactions it needs and
 
583
still cooperate smoothly with the rest of the application.  If a DBI
 
584
transaction is already active, it will be reused; otherwise a new one
 
585
will be started.
 
586
 
 
587
Tangram offer a more robust alternative to the start/commit code
 
588
sandwich.  tx_do() calls CODEREF in a transaction. If the CODEREF
 
589
dies, the transaction is rolled back; otherwise it's committed.  The
 
590
first example can be rewritten:
 
591
 
 
592
    $storage->tx_do( sub {
 
593
        $homer->{partner} = $marge;
 
594
        $marge->{partner} = $homer;
 
595
        $storage->update( $homer, $marge };
 
596
        } );
 
597
 
 
598
For more information on transactions, see L<Tangram::Storage>.
 
599
 
 
600
=cut