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

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.40

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