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

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.37

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