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

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

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