/[cvs]/nfo/perl/libs/Data/Storage/Handler/Tangram.pm
ViewVC logotype

Diff of /nfo/perl/libs/Data/Storage/Handler/Tangram.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

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

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