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

Legend:
Removed from v.1.4  
changed lines
  Added in v.1.47

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