/[cvs]/nfo/perl/libs/Data/Storage.pm
ViewVC logotype

Diff of /nfo/perl/libs/Data/Storage.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.5 by joko, Tue Oct 29 19:24:18 2002 UTC revision 1.11 by joko, Wed Dec 11 06:53:19 2002 UTC
# Line 4  Line 4 
4  #  #
5  # See COPYRIGHT section in pod text below for usage and distribution rights.  # See COPYRIGHT section in pod text below for usage and distribution rights.
6  #  #
7  #################################  ############################################
8  #  #
9  #  $Log$  #  $Log$
10    #  Revision 1.11  2002/12/11 06:53:19  joko
11    #  + updated pod
12    #
13    #  Revision 1.10  2002/12/07 03:37:23  joko
14    #  + updated pod
15    #
16    #  Revision 1.9  2002/12/01 22:15:45  joko
17    #  - sub createDb: moved to handler
18    #
19    #  Revision 1.8  2002/11/29 04:48:23  joko
20    #  + updated pod
21    #
22    #  Revision 1.7  2002/11/17 06:07:18  joko
23    #  + creating the handler is easier than proposed first - for now :-)
24    #  + sub testAvailability
25    #
26    #  Revision 1.6  2002/11/09 01:04:58  joko
27    #  + updated pod
28    #
29  #  Revision 1.5  2002/10/29 19:24:18  joko  #  Revision 1.5  2002/10/29 19:24:18  joko
30  #  - reduced logging  #  - reduced logging
31  #  + added some pod  #  + added some pod
# Line 27  Line 46 
46  #  Revision 1.1  2002/10/10 03:43:12  cvsjoko  #  Revision 1.1  2002/10/10 03:43:12  cvsjoko
47  #  + new  #  + new
48  #  #
49  #################################  ############################################
50    
 # aim_V1: should encapsulate Tangram, DBI, DBD::CSV and LWP:: to access them in an unordinary way ;)  
 # aim_V2: introduce a generic layered structure, refactor *SUBLAYER*-stuff, make (e.g.) this possible:  
 #               - Perl Data::Storage[DBD::CSV]  ->  Perl LWP::  ->  Internet HTTP/FTP/*  ->  Host Daemon  ->  csv-file  
51    
52  BEGIN {  BEGIN {
53  $Data::Storage::VERSION = 0.01;    $Data::Storage::VERSION = 0.02;
54  }  }
55    
56    
57  =head1 NAME  =head1 NAME
58    
59  Data::Storage - Interface for accessing various Storage implementations for Perl in an independent way    Data::Storage - Interface for accessing various Storage implementations for Perl in an independent way
60    
61    
62    =head1 AIMS
63    
64      - should encapsulate Tangram, DBI, DBD::CSV and LWP:: to access them in an unordinary (more convenient) way ;)
65      - introduce a generic layered structure, refactor *SUBLAYER*-stuff, make (e.g.) this possible:
66        Perl Data::Storage[DBD::CSV]  ->  Perl LWP::  ->  Internet HTTP/FTP/*  ->  Host Daemon  ->  csv-file
67      - provide generic synchronization mechanisms across arbitrary/multiple storages based on ident/checksum
68        maybe it's possible to have schema-, structural- and semantical modifications synchronized???
69    
70    
71  =head1 SYNOPSIS  =head1 SYNOPSIS
72    
73    ... the basic way:  =head2 BASIC ACCESS
74    
75    =head2 ADVANCED ACCESS
76    
77    ... via inheritance:    ... via inheritance:
78        
# Line 63  Data::Storage - Interface for accessing Line 90  Data::Storage - Interface for accessing
90      $self->{storage}->insert($proxyObj);      $self->{storage}->insert($proxyObj);
91    
92    
93    =head2 SYNCHRONIZATION
94    
95      my $nodemapping = {
96        'LangText' => 'langtexts.csv',
97        'Currency' => 'currencies.csv',
98        'Country'  => 'countries.csv',
99      };
100    
101      my $propmapping = {
102        'LangText' => [
103          [ 'source:lcountrykey'  =>  'target:country' ],
104          [ 'source:lkey'         =>  'target:key' ],
105          [ 'source:lvalue'       =>  'target:text' ],
106        ],
107        'Currency' => [
108          [ 'source:ckey'         =>  'target:key' ],
109          [ 'source:cname'        =>  'target:text' ],
110        ],
111        'Country' => [
112          [ 'source:ckey'         =>  'target:key' ],
113          [ 'source:cname'        =>  'target:text' ],
114        ],
115      };
116    
117      sub syncResource {
118    
119        my $self = shift;
120        my $node_source = shift;
121        my $mode = shift;
122        my $opts = shift;
123        
124        $mode ||= '';
125        $opts->{erase} ||= 0;
126        
127        $logger->info( __PACKAGE__ . "->syncResource( node_source $node_source mode $mode erase $opts->{erase} )");
128      
129        # resolve metadata for syncing requested resource
130        my $node_target = $nodemapping->{$node_source};
131        my $mapping = $propmapping->{$node_source};
132        
133        if (!$node_target || !$mapping) {
134          # loggger.... "no target, sorry!"
135          print "error while resolving resource metadata", "\n";
136          return;
137        }
138        
139        if ($opts->{erase}) {
140          $self->_erase_all($node_source);
141        }
142      
143        # create new sync object
144        my $sync = Data::Transfer::Sync->new(
145          storages => {
146            L => $self->{bizWorks}->{backend},
147            R => $self->{bizWorks}->{resources},
148          },
149          id_authorities        =>  [qw( L ) ],
150          checksum_authorities  =>  [qw( L ) ],
151          write_protected       =>  [qw( R ) ],
152          verbose               =>  1,
153        );
154        
155        # sync
156        # todo: filter!?
157        $sync->syncNodes( {
158          direction       =>  $mode,                 # | +PUSH | +PULL | -FULL | +IMPORT | -EXPORT
159          method          =>  'checksum',            # | -timestamp | -manual
160          source          =>  "L:$node_source",
161          source_ident    =>  'storage_method:id',
162          source_exclude  =>  [qw( id cs )],
163          target          =>  "R:$node_target",
164          target_ident    =>  'property:oid',
165          mapping         =>  $mapping,
166        } );
167    
168      }
169    
170    
171  =head2 NOTE  =head2 NOTE
172    
173  This module heavily relies on DBI and Tangram, but adds a lot of additional bugs and quirks.    This module heavily relies on DBI and Tangram, but adds a lot of additional bugs and quirks.
174  Please look at their documentation and this code for additional information.    Please look at their documentation and/or this code for additional information.
175    
176    
177    =head1 REQUIREMENTS
178    
179      For full functionality:
180        DBI              from CPAN
181        DBD::mysql       from CPAN
182        Tangram 2.04     from CPAN         (hmmm, 2.04 won't do in some cases)
183        Tangram 2.05     from http://...   (2.05 seems okay but there are also additional patches from our side)
184        Class::Tangram   from CPAN
185        DBD::CSV         from CPAN
186        MySQL::Diff      from http://adamspiers.org/computing/mysqldiff/
187        ... and all their dependencies
188    
189  =cut  =cut
190    
# Line 80  use strict; Line 197  use strict;
197  use warnings;  use warnings;
198    
199  use Data::Storage::Locator;  use Data::Storage::Locator;
200    use Data::Dumper;
201    
202    # TODO: actually implement level (integrate with Log::Dispatch)
203  my $TRACELEVEL = 0;  my $TRACELEVEL = 0;
204    
205  # get logger instance  # get logger instance
# Line 90  sub new { Line 209  sub new {
209    my $invocant = shift;    my $invocant = shift;
210    my $class = ref($invocant) || $invocant;    my $class = ref($invocant) || $invocant;
211    #my @args = normalizeArgs(@_);    #my @args = normalizeArgs(@_);
212      
213    my $arg_locator = shift;    my $arg_locator = shift;
214    my $arg_options = shift;    my $arg_options = shift;
215      
216    #my $self = { STORAGEHANDLE => undef, @_ };    #my $self = { STORAGEHANDLE => undef, @_ };
217    my $self = { STORAGEHANDLE => undef, locator => $arg_locator, options => $arg_options };    my $self = { STORAGEHANDLE => undef, locator => $arg_locator, options => $arg_options };
218    $logger->debug( __PACKAGE__ . "[$self->{locator}->{type}]" . "->new(@_)" );    #$logger->debug( __PACKAGE__ . "[$self->{locator}->{type}]" . "->new(@_)" );
219      $logger->debug( __PACKAGE__ . "[$arg_locator->{type}]" . "->new(@_)" );
220    return bless $self, $class;    return bless $self, $class;
221  }  }
222    
# Line 107  sub AUTOLOAD { Line 227  sub AUTOLOAD {
227    #     - Deep recursion on subroutine "Data::Storage::AUTOLOAD"    #     - Deep recursion on subroutine "Data::Storage::AUTOLOAD"
228    #     - Deep recursion on subroutine "Data::Storage::Handler::Abstract::AUTOLOAD"    #     - Deep recursion on subroutine "Data::Storage::Handler::Abstract::AUTOLOAD"
229    #     - Deep recursion on anonymous subroutine at [...]    #     - Deep recursion on anonymous subroutine at [...]
230    # we also might filter log messages caused by logging itself in "advanced logging of AUTOLOAD calls"    # we also might filter log messages caused by logging to itself in "advanced logging of AUTOLOAD calls"
231        
232    my $self = shift;    my $self = shift;
233    our $AUTOLOAD;    our $AUTOLOAD;
# Line 129  sub AUTOLOAD { Line 249  sub AUTOLOAD {
249        $logstring .= "\t" x $tabcount . "(AUTOLOAD)";        $logstring .= "\t" x $tabcount . "(AUTOLOAD)";
250        # TODO: only ok if logstring doesn't contain        # TODO: only ok if logstring doesn't contain
251        #            e.g. "Data::Storage[Tangram]->insert(SystemEvent=HASH(0x5c0034c))          (AUTOLOAD)"        #            e.g. "Data::Storage[Tangram]->insert(SystemEvent=HASH(0x5c0034c))          (AUTOLOAD)"
252        # but that would be way too specific as long as we don't have an abstract handler for this  ;)        # but that would be _way_ too specific as long as we don't have an abstract handler for this  ;)
253        $logger->debug( $logstring );        $logger->debug( $logstring );
254          #print join('; ', @_);
255      }      }
256            
257    # filtering AUTOLOAD calls    # filtering AUTOLOAD calls and first-time-touch of the actual storage impl
258    if ($self->_filter_AUTOLOAD($method)) {    if ($self->_filter_AUTOLOAD($method)) {
259        #print "_accessStorage\n";
260      $self->_accessStorage();      $self->_accessStorage();
261      $self->{STORAGEHANDLE}->$method(@_);      $self->{STORAGEHANDLE}->$method(@_);
262    }    }
# Line 175  sub _accessStorage { Line 297  sub _accessStorage {
297    
298  sub _createStorageHandle {  sub _createStorageHandle {
299    my $self = shift;    my $self = shift;
   
300    my $type = $self->{locator}->{type};    my $type = $self->{locator}->{type};
301    $logger->debug( __PACKAGE__ .  "[$type]" . "->_createStorageHandle()" );    $logger->debug( __PACKAGE__ .  "[$type]" . "->_createStorageHandle()" );
302    
303    my $pkg = "Data::Storage::Handler::" . $type . "";    my $pkg = "Data::Storage::Handler::" . $type . "";
304        
305    # propagate args to handler    # try to load perl module at runtime
306    # needs some more thoughts! (not only "dbi" to Tangram, when (in future) db is not more the common case)    my $evalstr = "use $pkg;";
307    if ($type eq 'DBI') {    eval($evalstr);
308      use Data::Storage::Handler::DBI;    if ($@) {
309      #my @args = %{$self->{locator}->{dbi}};      $logger->error( __PACKAGE__ .  "[$type]" . "->_createStorageHandle(): $@" );
310      my @args = %{$self->{locator}};      return;
     # create new storage handle  
     $self->{STORAGEHANDLE} = $pkg->new( @args );  
   }  
   if ($type eq 'Tangram') {  
     use Data::Storage::Handler::Tangram;  
     #$self->{STORAGEHANDLE} = $pkg->new( dsn => $self->{locator}->{dbi}->{dsn} );  
     #my @args = %{$self->{locator}->{dbi}};  
     my @args = %{$self->{locator}};  
     # create new storage handle  
     $self->{STORAGEHANDLE} = $pkg->new( @args );  
   
     #$self->{STORAGEHANDLE_UNDERLYING} = $self->{STORAGEHANDLE}->getUnderlyingStorage();  
     #$self->{STORAGEHANDLE_UNDERLYING}->_configureCOREHANDLE();  
311    }    }
312        
313      # build up some additional arguments to pass on
314      #my @args = %{$self->{locator}};
315      my @args = ();
316    
317      # - create new storage handle object
318      # - propagate arguments to handler
319      # - pass locator by reference to be able to store status- or meta-information in it
320      $self->{STORAGEHANDLE} = $pkg->new( locator => $self->{locator}, @args );
321    
322  }  }
323    
324  sub addLogDispatchHandler {  sub addLogDispatchHandler {
# Line 233  sub addLogDispatchHandler { Line 350  sub addLogDispatchHandler {
350  }  }
351    
352  sub removeLogDispatchHandler {  sub removeLogDispatchHandler {
353      my $self = shift;
354        my $self = shift;    my $name = shift;
355        my $name = shift;    #my $logger = shift;
356        #my $logger = shift;    $logger->remove($name);
   
       $logger->remove($name);  
   
357  }  }
358    
359  sub getDbName {  sub getDbName {
# Line 257  sub testDsn { Line 371  sub testDsn {
371    if ( my $dbh = DBI->connect($dsn, '', '', {    if ( my $dbh = DBI->connect($dsn, '', '', {
372                                                        PrintError => 0,                                                        PrintError => 0,
373                                                        } ) ) {                                                        } ) ) {
374        
375        # TODO: REVIEW
376      $dbh->disconnect();      $dbh->disconnect();
377        
378      return 1;      return 1;
379    } else {    } else {
380      $logger->error( __PACKAGE__ .  "[$self->{locator}->{type}]" . "->testDsn(): " . "DBI-error: " . $DBI::errstr );      $logger->warning( __PACKAGE__ .  "[$self->{locator}->{type}]" . "->testDsn(): " . "DBI-error: " . $DBI::errstr );
381    }    }
382  }  }
383    
384  sub createDb {  sub testAvailability {
385    my $self = shift;    my $self = shift;
386    my $dsn = $self->{locator}->{dbi}->{dsn};    my $status = $self->testDsn();
387      $self->{locator}->{status}->{available} = $status;
388    $logger->debug( __PACKAGE__ .  "->createDb( dsn $dsn )" );    return $status;
   
   $dsn =~ s/database=(.+?);//;  
   my $database_name = $1;  
   
   my $ok;  
     
   if ( my $dbh = DBI->connect($dsn, '', '', {  
                                                       PrintError => 0,  
                                                       } ) ) {  
     if ($database_name) {  
       if ($dbh->do("CREATE DATABASE $database_name;")) {  
         $ok = 1;  
       }  
     }  
     $dbh->disconnect();  
   }  
     
   return $ok;  
     
389  }  }
390    
391    
392  sub dropDb {  sub dropDb {
393    my $self = shift;    my $self = shift;
394    my $dsn = $self->{locator}->{dbi}->{dsn};    my $dsn = $self->{locator}->{dbi}->{dsn};
# Line 309  sub dropDb { Line 408  sub dropDb {
408          $ok = 1;          $ok = 1;
409        }        }
410      }      }
411    
412      $dbh->disconnect();      $dbh->disconnect();
413    
414    }    }
415        
416    return $ok;    return $ok;
# Line 326  __END__ Line 427  __END__
427    
428  =head1 DESCRIPTION  =head1 DESCRIPTION
429    
430  Data::Storage is module for a accessing various "data structures" stored inside  =head2 Data::Storage
 various "data containers". It sits on top of DBI and/or Tangram.  
431    
432      Data::Storage is a module for accessing various "data structures / kinds of structured data" stored inside
433      various "data containers".
434      We tried to use the AdapterPattern (http://c2.com/cgi/wiki?AdapterPattern) to implement a wrapper-layer
435      around core CPAN modules (Tangram, DBI).
436    
437    =head2 Why?
438    
439      You will get a better code-structure (not bad for later maintenance) in growing Perl code projects,
440      especially when using multiple database connections at the same time.
441      You will be able to switch between different _kinds_ of implementations used for storing data.
442      Your code will use the very same API to access these storage layers.
443          ... implementation has to be changed for now
444      Maybe you will be able to switch "on-the-fly" without changing any bits in code in the future....
445          ... but that's not the focus
446    
447  =head1 AUTHORS / COPYRIGHT  =head2 What else?
448    
449  The Data::Storage module is Copyright (c) 2002 Andreas Motl.    Having this, we were able to do implement a generic data synchronization module more easy,
450  All rights reserved.    please look at Data::Transfer.
451    
452  You may distribute it under the terms of either the GNU General Public  
453  License or the Artistic License, as specified in the Perl README file.  =head1 AUTHORS / COPYRIGHT
454    
455      The Data::Storage module is Copyright (c) 2002 Andreas Motl.
456      All rights reserved.
457      You may distribute it under the terms of either the GNU General Public
458      License or the Artistic License, as specified in the Perl README file.
459    
460    
461  =head1 ACKNOWLEDGEMENTS  =head1 ACKNOWLEDGEMENTS
462    
463  Larry Wall and the C<perl5-porters> for Perl,    Larry Wall for Perl, Tim Bunce for DBI, Jean-Louis Leroy for Tangram and Set::Object,
464  Tim Bunce for DBI, Jean-Louis Leroy for Tangram and Set::Object,    Sam Vilain for Class::Tangram, Jochen Wiedmann and Jeff Zucker for DBD::CSV & Co.,
465  Sam Vilain for Class::Tangram.    Adam Spiers for MySQL::Diff and all contributors.
466    
467    
468  =head1 SUPPORT / WARRANTY  =head1 SUPPORT / WARRANTY
469    
470  Data::Storage is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.    Data::Storage is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
471    
472    
473  =head1 TODO  =head1 TODO
474    
475    
476  =head2 Handle the following errors/cases:  =head2 BUGS
477    
478  =head3 "DBI-Error [Tangram]: DBD::mysql::st execute failed: Unknown column 't1.requestdump' in 'field list'"  "DBI-Error [Tangram]: DBD::mysql::st execute failed: Unknown column 't1.requestdump' in 'field list'"
479    
480      ... occours when operating on object-attributes not introduced yet:    ... occours when operating on object-attributes not introduced yet:
481      this should be detected and appended/replaced through:    this should be detected and appended/replaced through:
482      "Schema-Error detected, maybe (just) an inconsistency.    "Schema-Error detected, maybe (just) an inconsistency.
483      Please check if your declaration in schema-module "a" matches structure in database "b" or try to run"    Please check if your declaration in schema-module "a" matches structure in database "b" or try to run"
484      db_setup.pl --dbkey=import --action=deploy    db_setup.pl --dbkey=import --action=deploy
485    
486  =head3 Compare schema (structure diff) with database ...  
487    Compare schema (structure diff) with database ...
488    
489    ... when issuing "db_setup.pl --dbkey=import --action=deploy"    ... when issuing "db_setup.pl --dbkey=import --action=deploy"
490    on a database with an already deployed schema, use an additional "--update" then    on a database with an already deployed schema, use an additional "--update" then
# Line 393  Data::Storage is free software. IT COMES Line 513  Data::Storage is free software. IT COMES
513    automatically and this is believed to be the most common case under normal circumstances.    automatically and this is believed to be the most common case under normal circumstances.
514    
515    
516  =head2 Introduce some features:  =head2 FEATURES
517    
518    - Get this stuff together with UML (Unified Modeling Language) and/or standards from ODMG.    - Get this stuff together with UML (Unified Modeling Language) and/or standards from ODMG.
519    - Make it possible to load/save schemas in XMI (XML Metadata Interchange),    - Make it possible to load/save schemas in XMI (XML Metadata Interchange),
# Line 401  Data::Storage is free software. IT COMES Line 521  Data::Storage is free software. IT COMES
521      Integrate/bundle this with a web-/html-based UML modeling tool or      Integrate/bundle this with a web-/html-based UML modeling tool or
522      some other interesting stuff like the "Co-operative UML Editor" from Uni Darmstadt. (web-/java-based)      some other interesting stuff like the "Co-operative UML Editor" from Uni Darmstadt. (web-/java-based)
523    - Enable Round Trip Engineering. Keep code and diagrams in sync. Don't annoy/bother the programmers.    - Enable Round Trip Engineering. Keep code and diagrams in sync. Don't annoy/bother the programmers.
524    - Add some more handlers:    - Add support for some more handlers/locators to be able to
525      - look at DBD::CSV, Text::CSV, XML::CSV, XML::Excel       access the following standards/protocols/interfaces/programs/apis transparently:
526    - Add some more locations/locators:      +  DBD::CSV (via Data::Storage::Handler::DBI)
527      - PerlDAV: http://www.webdav.org/perldav/     (-) Text::CSV, XML::CSV, XML::Excel
528    - Move to t3, use InCASE      -  MAPI
529        -  LDAP
530        -  DAV (look at PerlDAV: http://www.webdav.org/perldav/)
531        -  Mbox (use formail for seperating/splitting entries/nodes)
532        -  Cyrus (cyrdeliver - what about cyrretrieve (export)???)
533        -  use File::DiffTree, use File::Compare
534        -  Hibernate
535        -  "Win32::UserAccountDb"
536        -  "*nix::UserAccountDb"
537        -  .wab - files (Windows Address Book)
538        -  .pst - files (Outlook Post Storage?)
539        -  XML (e.g. via XML::Simple?)
540      - Move to t3, look at InCASE
541      - some kind of security layer for methods/objects
542        - acls (stored via tangram/ldap?) for functions, methods and objects (entity- & data!?)
543        - where are the hooks needed then?
544          - is Data::Storage & Co. okay, or do we have to touch the innards of DBI and/or Tangram?
545          - an attempt to start could be:
546             - 'sub getACLByObjectId($id, $context)'
547             - 'sub getACLByMethodname($id, $context)'
548             - 'sub getACLByName($id, $context)'
549                ( would require a kinda registry to look up these very names pointing to arbitrary locations (code, data, ...) )
550    
551    
552    
553  =head3 Links:  =head3 LINKS / REFERENCES
554    
555    Specs:    Specs:
556      UML 1.3 Spec: http://cgi.omg.org/cgi-bin/doc?ad/99-06-08.pdf      UML 1.3 Spec: http://cgi.omg.org/cgi-bin/doc?ad/99-06-08.pdf
# Line 434  Data::Storage is free software. IT COMES Line 576  Data::Storage is free software. IT COMES
576      (Dia (free): http://www.lysator.liu.se/~alla/dia/)      (Dia (free): http://www.lysator.liu.se/~alla/dia/)
577      UMLet (free, university): http://www.swt.tuwien.ac.at/umlet/index.html      UMLet (free, university): http://www.swt.tuwien.ac.at/umlet/index.html
578      Voodoo (free): http://voodoo.sourceforge.net/      Voodoo (free): http://voodoo.sourceforge.net/
579        Umbrello UML Modeller: http://uml.sourceforge.net/
580    
581    UML Tools:    UML Tools:
582      http://www.objectsbydesign.com/tools/umltools_byPrice.html      http://www.objectsbydesign.com/tools/umltools_byPrice.html

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.11

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed