/[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.3 by joko, Thu Oct 17 03:56:55 2002 UTC revision 1.37 by jonen, Sat May 10 17:37:39 2003 UTC
# Line 1  Line 1 
1  #################################  ############################################
2  #  #
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
112    #  - sub getNewPerlObjectByPkgName (moved to libp.pm)
113    #  + sub getMetaInfo
114    #  - sub existsChildNode (moved to Abstract.pm)
115    #  + sub getListUnfiltered
116    #  + sub getListFiltered
117    #  + sub createCursor
118    #  + sub createSet
119    #  + sub sendQuery
120    #
121    #  Revision 1.5  2002/11/17 06:35:18  joko
122    #  + locator metadata can now be reached via ->{locator}
123    #  - getChildNodes is now wrapped via COREHANDLE
124    #
125    #  Revision 1.4  2002/10/25 11:44:44  joko
126    #  + sub _initSchema
127    #  + sub existsChildNode
128    #  + sub testIntegrity
129    #  + sub rebuildDbAndSchema
130    #
131  #  Revision 1.3  2002/10/17 03:56:55  joko  #  Revision 1.3  2002/10/17 03:56:55  joko
132  #  + bugfix: trapped eval error  #  + bugfix: trapped eval error
133  #  #
# Line 15  Line 140 
140  #  Revision 1.1  2002/10/10 03:44:07  cvsjoko  #  Revision 1.1  2002/10/10 03:44:07  cvsjoko
141  #  + new  #  + new
142  #  #
143  #  ############################################
144  #################################  
145    
146  package Data::Storage::Handler::Tangram;  package Data::Storage::Handler::Tangram;
147    
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 Tangram;
157    
158    use DesignPattern::Object;
159    use Data::Storage::Result::Tangram;
160    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  our $metainfo = {  # this holds the complete instantiated schema from tangram
168    'disconnectMethod' => 'disconnect',  my $schema_tangram;
 };  
169    
170  sub getNewPerlObjectByPkgName {  sub getMetaInfo {
171    my $pkgname = shift;    my $self = shift;
172    my $args = shift;    $logger->debug( __PACKAGE__ . "->getMetaInfo()"  );
173    $logger->debug( __PACKAGE__ . "->getNewPerlObjectByPkgName( pkgname $pkgname args $args )" );    return {
174    my $evstring = "use $pkgname;";      'disconnectMethod' => 'disconnect',
175    eval($evstring);    };
176    $@ && $logger->error( __PACKAGE__ . ':' . __LINE__ . " Error in eval: " .  $@ );  }
177    return $pkgname->new($args);  
178    sub _initSchema {
179      my $self = shift;
180      $logger->debug( __PACKAGE__ . "->_initSchema()" );
181      #if (!$schema_tangram) {
182        #my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } );
183        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 (!$schema_tangram) {
187        $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{schema}" );
188        return 0;
189      }
190      #$self->_patchSchema();
191      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 {
# Line 51  sub connect { Line 213  sub connect {
213      my $self = shift;      my $self = shift;
214            
215      my $dsn = shift;      my $dsn = shift;
216      $dsn ||= $self->{dbi}->{dsn};  
217        #print Dumper($self);
218    #exit;
219    
220        # TODO: re-enable
221        $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 64  sub connect { Line 230  sub connect {
230  #      return;  #      return;
231  #    }  #    }
232    
233      my $obj = getNewPerlObjectByPkgName($self->{schema}, { EXPORT_OBJECTS => $self->{classnames} } );      #return unless $self->_initSchema();
234      $self->{schema_tangram} = $obj->getSchema();      $self->_initSchema();
235        
236        # 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.....
245      #$self->{STORAGEHANDLE_UNDERLYING} = $self->getUnderlyingStorage();      #$self->{STORAGEHANDLE_UNDERLYING} = $self->getUnderlyingStorage();
246      #$self->{STORAGEHANDLE_UNDERLYING}->_configureCOREHANDLE();      #$self->{STORAGEHANDLE_UNDERLYING}->_configureCOREHANDLE();
247      #$self->_configureUnderlyingStorage;      #$self->_configureUnderlyingStorage;
248        
249        # ..... encapsulation wins!
250      $self->configureCOREHANDLE();      $self->configureCOREHANDLE();
251    
252      $self->{locator}->{status}->{connected} = 1;
253    
254      return 1;
255    
256  }  }
257    
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    # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE    if ($mode eq 'core') {
270    #my $loc = new Data::Storage::Locator( type => "DBI", dbi => { db => $self->{COREHANDLE}->{db} });  
271    #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );      my @nodes;
272    my $storage = $self->_getSubLayerHandle();      
273    #$storage->_configureCOREHANDLE();      # 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        #my $loc = new Data::Storage::Locator( type => "DBI", COREHANDLE => $self->{COREHANDLE}->{db} );
276        
277        # todo: should we retrieve information from the schema here
278        # rather than poorly getting table names from underlying dbi?
279        my $storage = $self->_getSubLayerHandle();
280        @nodes = @{$storage->getChildNodes()};
281        #$storage->_configureCOREHANDLE();
282      #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    #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) {      return \@nodes;
292    if (my $result = $storage->sendCommand( 'SHOW TABLES;' ) ) {    
293      while ( my $row = $result->_getNextEntry() ) {    } elsif ($mode eq 'root') {
294        push @nodes, $row;      
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    $storage->disconnect();    }
315        
316    return \@nodes;  
317    }
318    
319    sub testIntegrity {
320    
321      my $self = shift;
322    
323      $logger->debug( __PACKAGE__ . "->testIntegrity()" );
324    
325      # 1st test: are there tables?
326      if (!$self->getChildNodes()) {
327        $logger->warning( __PACKAGE__ . "->testIntegrity no childnodes exist" );
328        return;
329      }
330    
331      # 2nd test: is there a table named "Tangram"?
332      if (!$self->existsChildNode("Tangram")) {
333        $logger->warning( __PACKAGE__ . "->testIntegrity childnode \"Tangram\" doesn't exist" );
334        return;
335      }
336    
337      $self->{locator}->{status}->{integrity} = 1;
338      return 1;
339    
340  }  }
341    
# Line 106  sub _getSubLayerHandle { Line 344  sub _getSubLayerHandle {
344        
345    my $self = shift;    my $self = shift;
346        
347    use Data::Dumper;    $logger->debug( __PACKAGE__ . "->_getSubLayerHandle()" );
348    
349    #print Dumper($self);    #print Dumper($self);
350      
351    # hack, make more generic!    # hack, make more generic!
352    if (!$self->{STORAGE_SUBLAYER}) {    if (!$self->{dataStorageLayer}) {
353      my $loc = Data::Storage::Locator->new( type => "DBI", dbi => $self->{dbi}, COREHANDLE => $self->{COREHANDLE}->{db} );      $logger->debug( __PACKAGE__ . "->_getSubLayerHandle() creating new dataStorageLayer" );
354      $self->{STORAGE_SUBLAYER} = Data::Storage->new( $loc, { protected => 1 } );      #my $loc = Data::Storage::Locator->new( type => "DBI", dbi => $self->{dbi}, COREHANDLE => $self->{COREHANDLE}->{db} );
355        my $loc = Data::Storage::Locator->new( { type => "DBI", dbi => $self->{locator}->{dbi} } );
356        $self->{dataStorageLayer} = Data::Storage->new( $loc, { protected => 1 } );
357      #$self->{STORAGE_UNDER_THE_HOOD}->{STORAGEHANDLE}->_configureCOREHANDLE();      #$self->{STORAGE_UNDER_THE_HOOD}->{STORAGEHANDLE}->_configureCOREHANDLE();
358      #$self->{STORAGE_UNDER_THE_HOOD}->_configureCOREHANDLE();      #$self->{STORAGE_UNDER_THE_HOOD}->_configureCOREHANDLE();
359    }    }
360        
361    #print Dumper($self->{STORAGE_UNDER_THE_HOOD});    #print Dumper($self->{STORAGE_UNDER_THE_HOOD});
362        
363    return $self->{STORAGE_SUBLAYER};    return $self->{dataStorageLayer};
364        
365  }  }
366    
367  sub _configureUnderlyingStorage {  sub _configureUnderlyingStorage {
368        
369    my $self = shift;    my $self = shift;
370    
371      $logger->debug( __PACKAGE__ . "->_configureUnderlyingStorage" );
372    
373    $self->_configureCOREHANDLE_DBI();    $self->_configureCOREHANDLE_DBI();
374    return;    return;
375        
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 142  sub configureCOREHANDLE { Line 386  sub configureCOREHANDLE {
386    
387    my $self = shift;    my $self = shift;
388    
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  }  }
410    
411  sub deploySchema {  sub deploySchema {
412    my $self = shift;    my $self = shift;
413    #my $dsn = $self->{locator}->{dbi}->{dsn};    my $args = shift;
414    my $dsn = $self->{dbi}->{dsn};    
415      my $dsn = $self->{locator}->{dbi}->{dsn};
416    
417      $logger->debug( __PACKAGE__ . "->deploySchema( dsn $dsn )" );
418    
419    my $ok;    my $ok;
420    if ( my $dbh = DBI->connect($dsn, '', '', {    if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) {
421                                                        PrintError => 0,      return unless $self->_initSchema();
422                                                      } ) ) {      $ok = Tangram::Relational->deploy($schema_tangram, $dbh );
     $ok = Tangram::Relational->deploy($self->{schema}, $dbh );  
423      $dbh->disconnect();      $dbh->disconnect();
424    }    }
425    return $ok;    return $ok;
426  }  }
427    
428  sub retreatSchema {  sub retreatSchema {
429    print "retreat\n";  
430    my $self = shift;    my $self = shift;
431    #my $dsn = $self->{locator}->{dbi}->{dsn};    my $dsn = $self->{locator}->{dbi}->{dsn};
432    my $dsn = $self->{dbi}->{dsn};  
433      $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} ) ) {
437                                                        PrintError => 0,  
438                                                      } ) ) {      return unless $self->_initSchema();
439      $ok = Tangram::Relational->retreat($self->{schema}, $dbh );      
440        #use Data::Dumper; print Dumper($self);
441        $self->{dataStorageLayer}->removeLogDispatchHandler("Tangram11");
442        
443        $ok = Tangram::Relational->retreat($schema_tangram, $dbh );
444    
445        # answer "$ok=2" means "maybe" for now - we have to patch this to a constant here because...
446        # - ... 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 rebuildDb {
460      my $self = shift;
461      $logger->info( __PACKAGE__ . "->rebuildDb()" );
462      my @results;
463    
464      # sum up results (bool (0/1)) in array
465      push @results, $self->retreatSchema();
466      push @results, $self->{dataStorageLayer}->dropDb();
467      push @results, $self->{dataStorageLayer}->createDb();
468      push @results, $self->deploySchema();
469    
470      # scan array for "bad ones"
471      my $res = 1;
472      map {
473        $res = 0 if (!$_);
474      } @results;
475      
476      return $res;
477    }
478    
479    sub getListUnfiltered {
480      my $self = shift;
481      my $nodename = shift;
482      my @results;
483      $logger->debug( __PACKAGE__ . "->getListUnfiltered( nodename => '" . $nodename . "' )" );
484      # get set of objects from odbms by object name
485      my $object_set = $self->{_COREHANDLE}->remote($nodename);
486      @results = $self->{_COREHANDLE}->select($object_set);
487      return \@results;
488    }
489    
490    sub getListFiltered {
491      my $self = shift;
492    
493      # redirect to unfiltered mode
494      #return $self->getListUnfiltered(@_);
495    
496      my $nodename = shift;
497      my $filters = shift;
498      my @results;
499      $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $nodename . "' )" );
500    
501    #print Dumper($filters);
502      
503      my @tfilters;
504      
505      foreach my $filter (@$filters) {
506      
507        # get filter - TODO: for each filter
508        #my $filter = $filters->[0];
509      
510        # build filter
511        my $lexpr = $filter->{key};
512        #my $op = $filter->{op};
513        my $op = '=';
514        my $rexpr = $filter->{val};
515        my $tight = 100;
516        
517      #  my $tfilter = Tangram::Filter->new(
518      #    expr => "t1.$lexpr $op '$rexpr'",
519      #    tight => $tight,
520      #    objects => $objects,
521      #  );
522      
523        # TODO: is_op?
524        # 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);
535    
536      # get set of objects from odbms by object name
537      my $remote = $self->{_COREHANDLE}->remote($nodename);
538      
539      # was:
540      #@results = $self->{COREHANDLE}->select($object_set, $tfilter);
541    
542      # is:
543      # HACK: build eval-string (sorry) to get filtered list - please give advice here
544      my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . ');';
545      
546      #print "eval: $evalstring", "\n";
547      
548      # get filtered list/set
549      @results = eval($evalstring);
550      die $@ if $@;
551      
552      return \@results;
553    }
554    
555    sub createCursor {
556      my $self = shift;
557      my $node = shift;
558      my $cmdHandle = $self->{_COREHANDLE}->cursor($node);
559      my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $cmdHandle );
560      return $result;
561    }
562    
563    sub createSet {
564      my $self = shift;
565    #print "-" x 80, "\n";
566    #print Dumper(@_);
567      my @objects = @_;
568      my $rh = Set::Object->new();
569      foreach (@objects) {
570        if (!isEmpty($_)) {
571    #print Dumper($_);
572          $rh->insert($_);
573        }
574      }
575      #print Dumper($rh->members());
576      my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh );
577      return $result;
578    }
579    
580    sub sendQuery {
581      my $self = shift;
582      my $query = shift;
583    
584      #print Dumper($query);
585    
586      # type = ITEM|LIST|TRANSPARENT
587      my $type = '';
588      # mode = OID|SPECIAL
589      my $mode = '';
590      my $ident = '';
591      my $crud = '';
592      
593      
594      # dispatch type and mode
595      
596        # defaults - 1
597        if ($query->{options}) {
598          $crud = $query->{options}->{crud};
599          $crud ||= $query->{options}->{action};
600        }
601    
602        # defaults - 2
603        $type ||= 'TRANSPARENT';
604        $crud ||= 'RETRIEVE';
605    
606        if ($query->{options}->{OID}) {
607          $type = 'ITEM';
608          $mode = 'OID';
609          $ident = $query->{options}->{OID};
610        
611        } elsif (my $guid = $query->{options}->{GUID}) {
612          $type = 'TRANSPARENT';
613          $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ];    
614    
615        # if operator is different (dispatcher for 'getListFiltered')
616        } elsif (my $op = $query->{options}->{op}) {
617          $type = 'TRANSPARENT';
618          $query->{criterias} = [ { key => $query->{options}->{meta_label}, op => $op, val => $query->{options}->{meta_value} } ];    
619    
620        }
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.3  
changed lines
  Added in v.1.37

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