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

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

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

revision 1.7 by joko, Sun Dec 1 04:46:19 2002 UTC revision 1.39 by jonen, Fri Jun 6 11:40:40 2003 UTC
# Line 3  Line 3 
3  #  $Id$  #  $Id$
4  #  #
5  #  $Log$  #  $Log$
6    #  Revision 1.39  2003/06/06 11:40:40  jonen
7    #  fixed bug at 'getFilteredList'
8    #
9    #  Revision 1.38  2003/05/13 16:38:38  joko
10    #  problems with "tied" on 5.6.1/win32
11    #
12    #  Revision 1.37  2003/05/10 17:37:39  jonen
13    #  corrected last commit
14    #
15    #  Revision 1.36  2003/05/10 17:31:18  jonen
16    #  + added new functions related to 'create' item
17    #   - createNode()
18    #     # creates non-persistent 'deep dummy filled' object
19    #   - insertChildNode()
20    #     # inserts child node at given parent (child node haven't to exists,
21    #         createNode will be injected transparently)
22    #
23    #  Revision 1.35  2003/04/19 16:09:48  jonen
24    #  + added operator dispatching (currently for getting ref-type) at 'getListFiltered'
25    #
26    #  Revision 1.34  2003/04/11 01:18:53  joko
27    #  sendQuery:
28    #  + introduced crud action 'DELETE'
29    #
30    #  Revision 1.33  2003/04/09 06:07:43  joko
31    #  revamped 'sub sendQuery'
32    #
33    #  Revision 1.32  2003/04/08 22:52:22  joko
34    #  modified 'querySchema': better behaviour regarding filtering result
35    #
36    #  Revision 1.31  2003/04/05 21:24:09  joko
37    #  modified 'sub getChildNodes': now contains code from 'querySchema'
38    #
39    #  Revision 1.30  2003/03/27 15:31:14  joko
40    #  fixes to modules regarding new namespace(s) below Data::Mungle::*
41    #
42    #  Revision 1.29  2003/02/21 01:47:18  joko
43    #  purged old code
44    #  minor cosmetics
45    #
46    #  Revision 1.28  2003/02/20 20:20:26  joko
47    #  tried to get auto-disconnect working again - failed with that
48    #
49    #  Revision 1.27  2003/01/31 06:30:59  joko
50    #  + enabled 'sendQuery'
51    #
52    #  Revision 1.26  2003/01/30 22:29:47  joko
53    #  + fixed module usage (removed dependency on 'libp.pm')
54    #
55    #  Revision 1.25  2003/01/19 02:30:05  joko
56    #  + fix: modified call to '_initSchema'
57    #
58    #  Revision 1.24  2002/12/22 14:13:01  joko
59    #  + sub dropDb
60    #
61    #  Revision 1.23  2002/12/19 16:31:53  joko
62    #  +- renamed sub to 'rebuildDb'
63    #
64    #  Revision 1.22  2002/12/18 22:28:16  jonen
65    #  + added extended logging at 'getObjectByGuid()'
66    #
67    #  Revision 1.21  2002/12/16 22:20:49  jonen
68    #  + fixed bug at 'getObjectByGuid()'
69    #
70    #  Revision 1.20  2002/12/16 20:49:17  jonen
71    #  + added sub 'getObjectByGuid()'
72    #  + added functionality to use 'getObjectByGuid' at 'getObjectAsHash()'
73    #
74    #  Revision 1.19  2002/12/16 06:46:09  joko
75    #  + attempt to introduce a generic '_patchSchema' - cancelled!
76    #
77    #  Revision 1.18  2002/12/13 21:48:07  joko
78    #  + fix to 'sub sendQuery'
79    #
80    #  Revision 1.17  2002/12/12 02:51:09  joko
81    #  + cosmetics
82    #
83    #  Revision 1.16  2002/12/11 06:54:10  joko
84    #  + fix: encapsulated object-loading inside an 'eval'
85    #
86    #  Revision 1.15  2002/12/05 13:55:21  joko
87    #  + now utilizing 'expand' instead of 'var_deref'
88    #  + played around with having fresh-objects - no progress....
89    #
90    #  Revision 1.14  2002/12/05 09:40:30  jonen
91    #  + added option->{destroy} at getObject for unloading all instance
92    #
93    #  Revision 1.13  2002/12/05 07:59:04  joko
94    #  + now using Tie::SecureHash as a base for the COREHANDLE
95    #  + former public COREHANDLE becomes private _COREHANDLE now
96    #  + sub getCOREHANDLE
97    #
98    #  Revision 1.12  2002/12/04 11:34:49  joko
99    #  - $schema_tangram doesn't have to be in class?
100    #
101    #  Revision 1.11  2002/12/04 08:54:08  jonen
102    #  + untested bugfix: undef($object) after transform to hash at getObjectAsHash
103    #
104    #  Revision 1.10  2002/12/03 15:53:23  joko
105    #  + small bugfix regarding object hierarchy
106    #
107    #  Revision 1.9  2002/12/03 05:29:40  joko
108    #  + sub getObject
109    #  + sub getObjectAsHash
110    #
111    #  Revision 1.8  2002/12/01 22:25:51  joko
112    #  + now utilizing metadata from storage locator when connecting to DBI in "raw"-mode
113    #
114  #  Revision 1.7  2002/12/01 04:46:19  joko  #  Revision 1.7  2002/12/01 04:46:19  joko
115  #  + sub eraseAll  #  + sub eraseAll
116  #  #
# Line 46  package Data::Storage::Handler::Tangram; Line 154  package Data::Storage::Handler::Tangram;
154  use strict;  use strict;
155  use warnings;  use warnings;
156    
157    use base ("Data::Storage::Handler");
158  use base ("Data::Storage::Handler::Abstract");  use base ("Data::Storage::Handler::Abstract");
159    
160  use Tangram;  
161  use Data::Dumper;  use Data::Dumper;
162  use libp qw( getNewPerlObjectByPkgName );  use Tangram;
163    
164    use DesignPattern::Object;
165  use Data::Storage::Result::Tangram;  use Data::Storage::Result::Tangram;
166  use Data::Compare::Struct qw( isEmpty );  use Data::Mungle::Compare::Struct qw( isEmpty );
167    use Data::Mungle::Transform::Deep qw( expand deep_copy merge_to );
168    
169  # get logger instance  # get logger instance
170  my $logger = Log::Dispatch::Config->instance;  my $logger = Log::Dispatch::Config->instance;
171    
172    
173    # this holds the complete instantiated schema from tangram
174    my $schema_tangram;
175    
176  sub getMetaInfo {  sub getMetaInfo {
177    my $self = shift;    my $self = shift;
178    $logger->debug( __PACKAGE__ . "->getMetaInfo()"  );    $logger->debug( __PACKAGE__ . "->getMetaInfo()"  );
# Line 69  sub getMetaInfo { Line 184  sub getMetaInfo {
184  sub _initSchema {  sub _initSchema {
185    my $self = shift;    my $self = shift;
186    $logger->debug( __PACKAGE__ . "->_initSchema()" );    $logger->debug( __PACKAGE__ . "->_initSchema()" );
187    #if (!$self->{schema_tangram}) {    #if (!$schema_tangram) {
188      my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } );      #my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } );
189      $self->{schema_tangram} = $obj->getSchema();      my $obj = DesignPattern::Object->fromPackage($self->{locator}->{schema}, { 'EXPORT_OBJECTS' => $self->{locator}->{classnames}, 'want_transactions' => $self->{locator}->{want_transactions} } );
190        $schema_tangram = $obj->getSchema();
191    #}    #}
192    if (!$self->{schema_tangram}) {    if (!$schema_tangram) {
193      $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{schema}" );      $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{schema}" );
194      return 0;      return 0;
195    }    }
196      #$self->_patchSchema();
197    return 1;    return 1;
198  }  }
199    
200    sub _patchSchema {
201      my $self = shift;
202      foreach (keys %{$schema_tangram->{classes}}) {
203        next if $schema_tangram->{classes}->{$_}->{abstract};
204        #next if ($_ ne 'TsBankAccount');
205        #$_ ne 'AbstractAccount' &&
206        print "class: $_", "\n";
207    #print Dumper($schema_tangram->{classes}->{$_});
208        # create new string property named 'guid'
209        my $tstring = Tangram::String->new();
210        $tstring->{name} = $tstring->{col} = 'guid';
211        # inject property into schema
212        #$schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields}->{string}->{$tstring->{name}} = $tstring;
213        print Dumper($schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields});
214      }
215    }
216    
217  sub connect {  sub connect {
218    
219      my $self = shift;      my $self = shift;
220            
221      my $dsn = shift;      my $dsn = shift;
222    
223    #print Dumper($self);
224    #exit;
225    
226        # TODO: re-enable
227      $dsn ||= $self->{locator}->{dbi}->{dsn};      $dsn ||= $self->{locator}->{dbi}->{dsn};
       
228      $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" );      $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" );
229            
230      #my $storage = Tangram::Relational->connect( $schema, $dsn );      #my $storage = Tangram::Relational->connect( $schema, $dsn );
# Line 98  sub connect { Line 236  sub connect {
236  #      return;  #      return;
237  #    }  #    }
238    
239      return unless $self->_initSchema();      #return unless $self->_initSchema();
240        $self->_initSchema();
241    
242      # create the main tangram storage object      # create the main tangram storage object
243      #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn );      #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn );
244      $self->{COREHANDLE} = Tangram::Relational->connect( $self->{schema_tangram}, $dsn );      $self->{_COREHANDLE} = Tangram::Relational->connect( $schema_tangram, $dsn );
245    
246    #print "connect", "\n";
247    #my $core = $self->{_COREHANDLE};
248    #print Dumper($core);
249        
250      # some attempts for configuring the wrapped underlying dbi.....      # some attempts for configuring the wrapped underlying dbi.....
251      #$self->{STORAGEHANDLE_UNDERLYING} = $self->getUnderlyingStorage();      #$self->{STORAGEHANDLE_UNDERLYING} = $self->getUnderlyingStorage();
# Line 121  sub connect { Line 264  sub connect {
264  sub getChildNodes {  sub getChildNodes {
265    
266    my $self = shift;    my $self = shift;
267    my @nodes;    my $mode = shift;
268      my $filter = shift;
269      
270      $mode ||= 'core';
271      $filter ||= 'all';
272      
273      $logger->debug( __PACKAGE__ . "->getChildNodes($mode)" );
274    
275    $logger->debug( __PACKAGE__ . "->getChildNodes()" );    if ($mode eq 'core') {
276    
277    # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE      my @nodes;
278    #my $loc = new Data::Storage::Locator( type => "DBI", dbi => { db => $self->{COREHANDLE}->{db} });      
279    #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );      # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE
280          #my $loc = new Data::Storage::Locator( type => "DBI", dbi => { db => $self->{COREHANDLE}->{db} });
281    # todo: should we retrieve information from the schema here      #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );
282    # rather than poorly getting table names from underlying dbi?      
283    my $storage = $self->_getSubLayerHandle();      # todo: should we retrieve information from the schema here
284    @nodes = @{$storage->getChildNodes()};      # rather than poorly getting table names from underlying dbi?
285    #$storage->_configureCOREHANDLE();      my $storage = $self->_getSubLayerHandle();
286  #print "getchildnodes\n";      @nodes = @{$storage->getChildNodes()};
287  #print Dumper($self);      #$storage->_configureCOREHANDLE();
288    #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {    #print "getchildnodes\n";
289      #print Dumper($self);
290        #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {
291        
292        # TODO: REVIEW
293        #$storage->disconnect();
294        
295        $self->{meta}->{childnodes} = \@nodes;
296    
297        return \@nodes;
298        
299    $storage->disconnect();    } elsif ($mode eq 'root') {
300        
301        # FIXME: this will return *all* known classes to 'Class::Tangram',
302        # which might not be what you expect since more than one instance
303        # of Tangram may be in memory and Class::Tangram seems to
304        # offer no methods to determine this or filter its result(s) according
305        # to a specific database.
306        my @object_names = Class::Tangram::known_classes();
307        my @concret_names;
308        my $o_cnt;
309        foreach (sort @object_names) {
310          push @concret_names, $_  if (!Class::Tangram::class_is_abstract($_));
311          $o_cnt++;
312        }
313    
314        if ($filter eq 'all') {
315          return \@object_names;
316        } elsif ($filter eq 'concrete') {
317          return \@concret_names;
318        }
319        
320    $self->{meta}->{childnodes} = \@nodes;    }
321        
   return \@nodes;  
322    
323  }  }
324    
   
325  sub testIntegrity {  sub testIntegrity {
326    
327    my $self = shift;    my $self = shift;
# Line 207  sub _configureUnderlyingStorage { Line 382  sub _configureUnderlyingStorage {
382    foreach my $key (keys %{$self->{dbi}}) {    foreach my $key (keys %{$self->{dbi}}) {
383      my $val = $self->{dbi}->{$key};      my $val = $self->{dbi}->{$key};
384      print "entry: $key; $val", "\n";      print "entry: $key; $val", "\n";
385      $self->{COREHANDLE}->{db}->{$key} = $val;      $self->{_COREHANDLE}->{db}->{$key} = $val;
386    }    }
387    #print Dumper($self->{COREHANDLE}->{db});    #print Dumper($self->{COREHANDLE}->{db});
388  }  }
# Line 220  sub configureCOREHANDLE { Line 395  sub configureCOREHANDLE {
395    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );    $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" );
396    
397    #my $subLayer = $self->_getSubLayerHandle();    #my $subLayer = $self->_getSubLayerHandle();
398      #print Dumper($self);
399      #exit;
400    
401    # apply configured modifications    # apply configured modifications
402      if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) {      if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) {
403        $self->{COREHANDLE}->{db}->trace($self->{dbi}->{trace_level}, $self->{dbi}->{trace_file});        $self->{_COREHANDLE}->{db}->trace($self->{dbi}->{trace_level}, $self->{dbi}->{trace_file});
404      }      }
405      if (exists $self->{dbi}->{RaiseError}) {      if (exists $self->{dbi}->{RaiseError}) {
406        $self->{COREHANDLE}->{db}->{RaiseError} = $self->{dbi}->{RaiseError};        $self->{_COREHANDLE}->{db}->{RaiseError} = $self->{dbi}->{RaiseError};
407      }      }
408      if (exists $self->{dbi}->{PrintError}) {      if (exists $self->{dbi}->{PrintError}) {
409        $self->{COREHANDLE}->{db}->{PrintError} = $self->{dbi}->{PrintError};        $self->{_COREHANDLE}->{db}->{PrintError} = $self->{dbi}->{PrintError};
410      }      }
411      if (exists $self->{dbi}->{HandleError}) {      if (exists $self->{dbi}->{HandleError}) {
412        $self->{COREHANDLE}->{db}->{HandleError} = $self->{dbi}->{HandleError};        $self->{_COREHANDLE}->{db}->{HandleError} = $self->{dbi}->{HandleError};
413      }      }
414    
415  }  }
# Line 242  sub deploySchema { Line 419  sub deploySchema {
419    my $args = shift;    my $args = shift;
420        
421    my $dsn = $self->{locator}->{dbi}->{dsn};    my $dsn = $self->{locator}->{dbi}->{dsn};
   #my $dsn = $self->{dbi}->{dsn};  
422    
423    $logger->debug( __PACKAGE__ . "->deploySchema( dsn $dsn )" );    $logger->debug( __PACKAGE__ . "->deploySchema( dsn $dsn )" );
424    
425    my $ok;    my $ok;
426    # TODO: is this DBI->connect okay here like it is? regarding errors.....???    if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
   if ( my $dbh = DBI->connect($dsn, '', '', {  
                                                       PrintError => 0,  
                                                     } ) ) {  
   
427      return unless $self->_initSchema();      return unless $self->_initSchema();
428            $ok = Tangram::Relational->deploy($schema_tangram, $dbh );
     $ok = Tangram::Relational->deploy($self->{schema_tangram}, $dbh );  
429      $dbh->disconnect();      $dbh->disconnect();
430    }    }
431    return $ok;    return $ok;
# Line 264  sub retreatSchema { Line 435  sub retreatSchema {
435    
436    my $self = shift;    my $self = shift;
437    my $dsn = $self->{locator}->{dbi}->{dsn};    my $dsn = $self->{locator}->{dbi}->{dsn};
   #my $dsn = $self->{dbi}->{dsn};  
438    
439    $logger->debug( __PACKAGE__ . "->retreatSchema( dsn $dsn )" );    $logger->debug( __PACKAGE__ . "->retreatSchema( dsn $dsn )" );
440    
441    my $ok;    my $ok;
442    if ( my $dbh = DBI->connect($dsn, '', '', {    if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
                                                       #PrintError => 0,  
                                                       #RaiseError => 0,  
                                                     } ) ) {  
443    
444      return unless $self->_initSchema();      return unless $self->_initSchema();
445            
446      #use Data::Dumper; print Dumper($self);      #use Data::Dumper; print Dumper($self);
447      $self->{dataStorageLayer}->removeLogDispatchHandler("Tangram11");      $self->{dataStorageLayer}->removeLogDispatchHandler("Tangram11");
448            
449      $ok = Tangram::Relational->retreat($self->{schema_tangram}, $dbh );      $ok = Tangram::Relational->retreat($schema_tangram, $dbh );
450      $ok = 2;    # answer is "maybe" for now since Tangram::Relational->retreat doesn't seem to return a valid status  
451                      # idea: test this by checking for count of tables in database -      # answer "$ok=2" means "maybe" for now - we have to patch this to a constant here because...
452                      #          problem with this: there may be some left not having been included to the schema      # - ... Tangram::Relational->retreat doesn't seem to return a valid status
453        # - possible improvement:
454        #   - test this by checking for count of tables in database
455        #   - problem with this: there may be some left not having been included to the schema
456        #   - maybe better: use "->getChildNodes"?
457        $ok = 2;
458    
459      $dbh->disconnect();      $dbh->disconnect();
460    
461    }    }
462    return $ok;    return $ok;
463  }  }
464    
465  sub rebuildDbAndSchema {  sub rebuildDb {
466    my $self = shift;    my $self = shift;
467    $logger->info( __PACKAGE__ . "->rebuildDbAndSchema()" );    $logger->info( __PACKAGE__ . "->rebuildDb()" );
468    my @results;    my @results;
469    
470    # sum up results (bool (0/1)) in array    # sum up results (bool (0/1)) in array
# Line 314  sub getListUnfiltered { Line 488  sub getListUnfiltered {
488    my @results;    my @results;
489    $logger->debug( __PACKAGE__ . "->getListUnfiltered( nodename => '" . $nodename . "' )" );    $logger->debug( __PACKAGE__ . "->getListUnfiltered( nodename => '" . $nodename . "' )" );
490    # get set of objects from odbms by object name    # get set of objects from odbms by object name
491    my $object_set = $self->{COREHANDLE}->remote($nodename);    my $object_set = $self->{_COREHANDLE}->remote($nodename);
492    @results = $self->{COREHANDLE}->select($object_set);    @results = $self->{_COREHANDLE}->select($object_set);
493    return \@results;    return \@results;
494  }  }
495    
# Line 330  sub getListFiltered { Line 504  sub getListFiltered {
504    my @results;    my @results;
505    $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $nodename . "' )" );    $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $nodename . "' )" );
506    
507    #print Dumper($filters);  #print Dumper($filters);
508        
509    my @tfilters;    my @tfilters;
510        
# Line 352  sub getListFiltered { Line 526  sub getListFiltered {
526    #    objects => $objects,    #    objects => $objects,
527    #  );    #  );
528        
529      # HACK: build eval-string (sorry) to get filtered list - please give advice here      # TODO: is_op?
530      push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'";      # dispatch un-common operators if exists
531        if($filter->{op} eq "ref") {
532          # do nothing, results will be filtered later cause 'tangram-filter' doesn't support 'ref' query
533          #print "Filter->op eq 'ref'.\n";
534          #push @tfilters, 'ref($remote->{' . $filter->{key} . '})' . " eq '$filter->{val}'";
535        } else {
536          # HACK: build eval-string (sorry) to get filtered list - please give advice here
537          push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'";
538        }
539    
540    }    }
541    
542    my $tfilter = join(' & ', @tfilters);    my $tfilter = join(' & ', @tfilters);
543    
544    # get set of objects from odbms by object name    # get set of objects from odbms by object name
545    my $remote = $self->{COREHANDLE}->remote($nodename);    my $remote = $self->{_COREHANDLE}->remote($nodename);
546        
547    # was:    # was:
548    #@results = $self->{COREHANDLE}->select($object_set, $tfilter);    #@results = $self->{COREHANDLE}->select($object_set, $tfilter);
549    
550    # is:    # is:
551    # HACK: build eval-string (sorry) to get filtered list - please give advice here    # HACK: build eval-string (sorry) to get filtered list - please give advice here
552    my $evalstring = 'return $self->{COREHANDLE}->select($remote, ' . $tfilter . ');';    my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . ');';
553      
554      #print "eval: $evalstring", "\n";
555        
556    # get filtered list/set    # get filtered list/set
557    @results = eval($evalstring);    @results = eval($evalstring);
558    die $@ if $@;    die $@ if $@;
559        
560    
561      # filter results
562      if($filters->[0]->{op} eq "ref") {
563          #print "Filter->op eq 'ref'.\n";
564          my $att_name = $filters->[0]->{key};
565          my $att_val = $filters->[0]->{val};
566          my @filtered;
567          foreach(@results) {
568            if(ref($_->{$att_name}) eq $att_val) {
569              push @filtered, $_;
570            }
571          }
572          @results = @filtered;
573      }
574    
575      #print "results: " . Dumper(\@results);
576      
577    return \@results;    return \@results;
578  }  }
579    
580  sub createCursor {  sub createCursor {
581    my $self = shift;    my $self = shift;
582    my $node = shift;    my $node = shift;
583    my $cmdHandle = $self->{COREHANDLE}->cursor($node);    my $cmdHandle = $self->{_COREHANDLE}->cursor($node);
584    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $cmdHandle );    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $cmdHandle );
585    return $result;    return $result;
586  }  }
587    
588  sub createSet {  sub createSet {
589    my $self = shift;    my $self = shift;
590    #print "-" x 80, "\n";
591    #print Dumper(@_);
592    my @objects = @_;    my @objects = @_;
593    my $rh = Set::Object->new();    my $rh = Set::Object->new();
594    foreach (@objects) {    foreach (@objects) {
595      #print Dumper($_);      if (!isEmpty($_)) {
596      $rh->insert($_) if !isEmpty($_);  #print Dumper($_);
597          $rh->insert($_);
598        }
599    }    }
600    #print Dumper($rh->members());    #print Dumper($rh->members());
601    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );    my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
# Line 400  sub createSet { Line 605  sub createSet {
605  sub sendQuery {  sub sendQuery {
606    my $self = shift;    my $self = shift;
607    my $query = shift;    my $query = shift;
   #my $sql = "SELECT cs FROM $self->{metainfo}->{$descent}->{node} WHERE $self->{metainfo}->{$descent}->{IdentProvider}->{arg}='$self->{entry}->{source}->{ident}';";  
   #my $result = $self->{metainfo}->{$descent}->{storage}->sendCommand($sql);  
608    
609    #print Dumper($query);    #print Dumper($query);
610    
611    # HACK: special case: querying by id does not translate into a common tangram query    # type = ITEM|LIST|TRANSPARENT
612    # just load the object by given id(ent)    my $type = '';
613    if ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq') {    # mode = OID|SPECIAL
614      #print "LOAD!!!", "\n";    my $mode = '';
615      #exit;    my $ident = '';
616      #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) );    my $crud = '';
617      my $ident = $query->{criterias}->[0]->{val};    
618  #print "load obj", "\n";    
619      #return $self->createSet() if $ident == 5;    # dispatch type and mode
620      my $object = $self->{COREHANDLE}->load($ident);    
621  #print "get id", "\n";      # defaults - 1
622      my $oid = $self->{COREHANDLE}->id($object);      if ($query->{options}) {
623      return $self->createSet($object);        $crud = $query->{options}->{crud};
624      #return $self->createSet( $self->{COREHANDLE}->load('300090018') );        $crud ||= $query->{options}->{action};
625    }      }
626    
627    die("This should not be reached for now - redirect to \$self->getListFiltered() here!");      # defaults - 2
628        $type ||= 'TRANSPARENT';
629    # TODO: do a common tangram query here      $crud ||= 'RETRIEVE';
630    
631    my @crits;      if ($query->{options}->{OID}) {
632    foreach (@{$query->{criterias}}) {        $type = 'ITEM';
633      my $op = '';        $mode = 'OID';
634      $op = '=' if lc $_->{op} eq 'eq';        $ident = $query->{options}->{OID};
635      push @crits, "$_->{key}$op'$_->{val}'";      
636    }      } elsif (my $guid = $query->{options}->{GUID}) {
637    my $subnodes = {};        $type = 'TRANSPARENT';
638    map { $subnodes->{$_}++ } @{$query->{subnodes}};        $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ];    
639    # HACK: this is hardcoded ;(    expand possibilities!  
640    #my $crit = join(' AND ', @crits);      # if operator is different (dispatcher for 'getListFiltered')
641    #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit);      } elsif (my $op = $query->{options}->{op}) {
642    #return $self->sendCommand($sql);        $type = 'TRANSPARENT';
643    #my $h = $self->{COREHANDLE}->remote($query->{node});        $query->{criterias} = [ { key => $query->{options}->{meta_label}, op => $op, val => $query->{options}->{meta_value} } ];    
644    #my $res = $self->{COREHANDLE}->select($h, $h->{);  
645    return $self->createCursor($query->{node});      }
646      
647        # HACK: special case: querying by id does not translate into a common tangram query
648        # just load the object by given identifier (OID) named 'id' - this is required by Data::Transfer::Sync!
649        if ($query->{criterias} && ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq')) {
650          $type = 'ITEM';
651          $mode = 'SPECIAL.SYNC';
652          $ident = $query->{criterias}->[0]->{val};
653        }
654      
655    
656      # execute query
657      my $result;
658    
659      if ($type eq 'ITEM' && $ident) {
660    
661        if ($mode eq 'OID') {    
662          # TODO: review this case!
663          $result = $self->getObject($ident, $query->{options});
664        
665        } elsif ($mode eq 'SPECIAL.SYNC') {
666    
667          # V1 - failed
668          #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) );
669      
670          # hmm....
671          #return $self->createSet() if $ident == 5;
672          
673          # Unload single object before doing any further operations to
674          # expect a "fresh" object from orm when performing the next calls.
675          $self->{_COREHANDLE}->unload($ident);
676          
677          # Load object from orm.
678          my $object = $self->{_COREHANDLE}->load($ident);
679      
680          # determine object identifier (OID)
681          my $oid = $self->{_COREHANDLE}->id($object);
682          
683          # encapsulate into result/response container and return this one
684          $result = $self->createSet($object);
685          
686          # debugging
687          #$result = $self->createSet( $self->{COREHANDLE}->load('300090018') );
688    
689        }
690        
691      
692      } elsif ($type eq 'TRANSPARENT') {
693    
694        if ($crud eq 'RETRIEVE') {
695    
696          my $list = $self->getListFiltered($query->{node}, $query->{criterias});
697          #return $self->createSet($object);
698          #return $self->createSet($list);
699          return $self->createSet(@$list);
700        
701          #die("This should not be reached for now - redirect to \$self->getListFiltered() here!");
702        
703          # try a generic tangram query here
704          # TODO: try to place an oql on top of that (search.cpan.org!)
705          my @crits;
706          foreach (@{$query->{criterias}}) {
707            my $op = '';
708            $op = '=' if lc $_->{op} eq 'eq';
709            push @crits, "$_->{key}$op'$_->{val}'";
710          }
711          my $subnodes = {};
712          map { $subnodes->{$_}++ } @{$query->{subnodes}};
713          # HACK: this is hardcoded ;(    expand possibilities!
714          #my $crit = join(' AND ', @crits);
715          #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit);
716          #return $self->sendCommand($sql);
717          #my $h = $self->{COREHANDLE}->remote($query->{node});
718          #my $res = $self->{COREHANDLE}->select($h, $h->{);
719          $result = $self->createCursor($query->{node});
720    
721        } elsif ($crud eq 'UPDATE') {
722    
723          # Patch current query to be a loader (e.g. change action, remove payload) ...
724          my $childquery = deep_copy($query);
725          $childquery->{options}->{crud} = 'RETRIEVE';
726          delete $childquery->{payload};
727    
728          # ... to use it to fetch a fresh object using ourselves (sendQuery).
729          my $cursor = $self->sendQuery($childquery);
730          my $status = $cursor->getStatus();
731          my $object = $cursor->getNextEntry();
732    
733          # Merge values and apply value modifiers.
734          my $options = { utf8 => 1, php => 1 };
735          merge_to($object, $query->{payload}, $options);
736    
737          # Execute update operation at orm.
738          $self->update($object);
739        
740        } elsif ($crud eq 'DELETE') {
741    
742          # Patch current query to be a loader (e.g. change action) ...
743          my $childquery = deep_copy($query);
744          $childquery->{options}->{crud} = 'RETRIEVE';
745    
746          # ... to use it to fetch a fresh object using ourselves (sendQuery).
747          my $cursor = $self->sendQuery($childquery);
748          my $status = $cursor->getStatus();
749          my $object = $cursor->getNextEntry();
750    
751          $self->erase($object);
752    
753        } elsif ($crud eq 'CREATE') {
754          
755          my $nodename = $query->{node};      
756          my $newnode = $self->createNode($nodename);
757          my $id = $self->{_COREHANDLE}->insert($newnode);
758      
759          print "Saved new node $nodename with GUID $newnode->{guid}, OID '$id': " . Dumper($newnode) . "\n";
760          
761          return $newnode;
762    
763        }
764    
765      }
766    
767      return $result;
768    
769  }  }
770    
771  sub eraseAll {  sub eraseAll {
772    my $self = shift;    my $self = shift;
773    my $classname = shift;    my $classname = shift;
774    my $remote = $self->{storage}->remote($classname);    my $remote = $self->{_COREHANDLE}->remote($classname);
775    my @objs = $self->{storage}->select($remote);    my @objs = $self->{_COREHANDLE}->select($remote);
776    $self->{COREHANDLE}->erase(@objs);    $self->{_COREHANDLE}->erase(@objs);
777    }
778    
779    sub createDb {
780      my $self = shift;
781      my $storage = $self->_getSubLayerHandle();
782      return $storage->createDb();
783    }
784    
785    sub getObject {
786      my $self = shift;
787      my $oid = shift;
788      my $options = shift;
789    
790      # TODO: create a deep_unload method (currently _all_ objects are unloaded)
791      # unload($oid) will only unload object, not deep object hashes
792      $self->{_COREHANDLE}->unload() if ($options->{destroy});
793    
794      # TODO: review this
795      #if (!$self->{COREHANDLE}) { return; }
796    
797      # TODO: review this
798      my $object = eval('$self->{_COREHANDLE}->load($oid);');
799      print $@, "\n" if $@;
800    
801      return $object if $object;
802    }
803    
804    sub getObjectByGuid_old {
805      my $self = shift;
806      my $guid = shift;
807      my $options = shift;
808      
809      # Guid and Classname is needed
810      if(!$guid || !$options->{classname}) {
811       $logger->error( __PACKAGE__ . "->getObjectByGuid: No 'guid' OR no Classname in options hash was given but needed!" );
812        return;
813      }
814      
815      # TODO: create a deep_unload method (currently _all_ objects are unloaded)
816      # unload($oid) will only unload object, not deep object hashes
817      $self->{_COREHANDLE}->unload() if ($options->{destroy});
818    
819      # search for object with given Classname and Guid
820      my $obj_tmp = $self->{_COREHANDLE}->remote($options->{classname});
821      my @result = $self->{_COREHANDLE}->select($obj_tmp, $obj_tmp->{guid} eq $guid);
822      
823      # we searched for global unique identifer of some object,
824      # so I think we can trust there would be only one result
825      if($result[0]) {
826        return $result[0];
827      } else {
828        $logger->error( __PACKAGE__ . "->getObjectByGuid: No Object with Classname $options->{classname} and GUID $guid found!" );
829        return;
830      }
831      
832    }
833    
834    sub getObjectAsHash_old {
835      my $self = shift;
836      my $oid = shift;
837      my $options = shift;  
838      my $obj;
839      
840      if($options->{guid}) {
841        $obj = $self->getObjectByGuid($oid, $options);
842      } else {
843        $obj = $self->getObject($oid, $options);
844      }
845      
846      # build options (a callback to unload autovivified objects) for 'expand'
847      # TODO: use $logger to write to debug here!
848      my $cb; # = sub {};
849    
850      # deactivated way to get rid of used instances, if requested
851    =pod
852        if ($options->{destroy}) {
853          $options->{cb}->{destroy} = sub {
854            print "================ DESTROY", "\n";
855            my $object = shift;
856            #print Dumper($object);
857            $self->{_COREHANDLE}->unload($object);
858            #undef($object);
859          };
860        }
861    =cut
862    
863      my $hash = expand($obj, $options);
864    
865      # old (unsuccessful) attempts to get rid of used instances, if requested
866    
867        # V1:
868        #$options->{cb}->{destroy}->($obj);
869        #$self->{_COREHANDLE}->unload($obj);
870      
871        # V2:
872        #$obj->clear_refs;
873        #$self->{COREHANDLE}->unload($obj) if($options->{destroy});
874        #$obj->DESTROY;
875        #undef($obj) if($options->{destroy});
876      
877      return $hash;
878    }
879    
880    sub getSchema {
881      return $schema_tangram;
882    }
883    
884    sub getCOREHANDLE {
885      my $self = shift;
886      return $self->{_COREHANDLE};
887    }
888    
889    sub dropDb {
890      my $self = shift;
891      my $storage = $self->_getSubLayerHandle();
892      return $storage->dropDb();
893    }
894    
895    sub testAvailability {
896      my $self = shift;
897      my $storage = $self->_getSubLayerHandle();
898      return $storage->testAvailability();
899    }
900    
901    sub disconnect2 {
902      my $self = shift;
903      my $storage = $self->_getSubLayerHandle();
904      print "DISC!", "\n";
905    
906      my $storage_ll = $storage->{_COREHANDLE};
907      $storage_ll->disconnect();
908      
909      print Dumper($storage);
910      exit;
911      
912      #$self->{_COREHANDLE}
913      #$storage->disconnect();
914      $self->{dataStorageLayer}->disconnect();
915    }
916    
917    
918    sub createNode {
919      my $self = shift;
920      my $classname = shift;
921    
922      my $obj = $classname->new();
923      
924      my $attr_options = Class::Tangram::attribute_options($classname);
925      #print "Attribute Options: " . Dumper($attr_options);
926    
927      my $attr_types = Class::Tangram::attribute_types($classname);
928      #print "Attribute Types: " . Dumper($attr_types);
929      
930      foreach(keys %{$attr_types}) {
931        if($attr_types->{$_} eq 'string') {
932          $obj->{$_} = '';
933        } elsif($attr_types->{$_} eq 'int') {
934          $obj->{$_} = 0;
935        } elsif($attr_types->{$_} eq 'real') {
936          $obj->{$_} = 0;
937        } elsif($attr_types->{$_} eq 'rawdatetime') {
938          $obj->{$_} = '0000-00-00 00:00:00';
939        } elsif($attr_types->{$_} eq 'ref') {
940          if($attr_options->{$_}->{class}) {
941            $obj->{$_} = $self->createNode($attr_options->{$_}->{class});
942          } else {
943            #$obj->{$_} = undef();
944          }
945        } elsif($attr_types->{$_} eq 'iarray') {
946            $obj->{$_} = [ ];
947        } elsif($attr_types->{$_} eq 'hash') {
948            $obj->{$_} = {  };
949        } elsif($attr_types->{$_} eq 'flat_hash') {
950            $obj->{$_} = { };
951        }
952      }
953      
954      #print "New Object: " . Dumper($obj);
955      
956      return $obj;
957  }  }
958    
959    
960      sub insertChildNode {
961        my $self = shift;
962        my $child_entry = shift;
963        my $query_args = shift;
964        
965        my $core = $self->{_COREHANDLE};
966        my $nodename = $query_args->{nodename};
967        
968        # get parent object
969        my $query = {
970              node => $query_args->{parent}->{nodename},
971              options => { GUID => $query_args->{parent}->{guid}, },
972              };
973        my $cursor = $self->sendQuery($query);
974        my $parent = $cursor->getNextEntry();
975    
976        # debug
977        #print "Parent_org: " . Dumper($parent);
978            
979        # Create child node object if isn't already done
980        # ($child_entry have to be the class name then...)
981        if(!ref($child_entry)) {
982          $child_entry = $self->createNode($child_entry);
983          # it could be insert 'manually' or will be insert 'transparent' if parent will be updated
984          #$core->insert($child_entry);
985          #print "Create child object [$nodename]: " . Dumper($child_entry);
986        }
987    
988        # get reference of tied node (seems, only on Linux node's are tied!!)
989        my $tied_node = tied $parent->{$nodename};
990    
991        # insert/change child entry at parent
992        #print "reference: " . ref($parent->{$nodename}) . "\n";
993        if(ref($parent->{$nodename}) eq 'ARRAY') {
994          # (seems, only on Linux node's are tied!!)
995          if($tied_node) {
996            # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type,
997            # so a 'PUSH' is not implemented (which could be then done transparently)
998            my $array = $tied_node->FETCH;
999            push @$array, $child_entry;
1000            $tied_node->STORE($array);
1001            # node will be normaly untied at 'STORE'
1002            if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1003            else { undef $tied_node; }
1004          } else {
1005            push @{$parent->{$nodename}}, $child_entry;
1006          }
1007        }
1008        elsif(ref($parent->{$nodename}) eq 'HASH') {
1009          if(my $key = $query_args->{hash_key}) {
1010            # (seems, only on Linux node's are tied!!)
1011            if($tied_node) {
1012              # same problem as with 'ARRAY':
1013              # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type.
1014              my $hash = $tied_node->FETCH;
1015              $hash->{$key} = $child_entry;
1016              $tied_node->STORE($hash);
1017              # node will be normaly untied at 'STORE'
1018              if(tied $parent->{$nodename}) { print "already tied !!\n"; }
1019              else { undef $tied_node; }
1020            } else {
1021              $parent->{$nodename}->{$key} = $child_entry;
1022            }
1023          } else {
1024           print "ERROR: No HASH KEY given, so not able to insert hash entry!";
1025          }
1026        }
1027        else {
1028          $parent->{$nodename} = $child_entry;
1029        }
1030    
1031        # debug
1032        #print "Parent_new: " . Dumper($parent);
1033        
1034        # save parent
1035        $core->update($parent);
1036        
1037        # debug
1038        #print "Saved Parent: ". Dumper($parent);
1039        
1040        return $child_entry;
1041      }
1042    
1043    
1044  1;  1;
1045    __END__

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.39

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