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

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.36

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