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

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.38

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