--- nfo/perl/libs/Data/Storage/Handler/Tangram.pm 2002/10/17 03:56:55 1.3 +++ nfo/perl/libs/Data/Storage/Handler/Tangram.pm 2003/07/02 11:07:12 1.43 @@ -1,8 +1,152 @@ -################################# +############################################ # -# $Id: Tangram.pm,v 1.3 2002/10/17 03:56:55 joko Exp $ +# $Id: Tangram.pm,v 1.43 2003/07/02 11:07:12 jonen Exp $ # # $Log: Tangram.pm,v $ +# Revision 1.43 2003/07/02 11:07:12 jonen +# re-activate filtering of results *after* results are fetched from tangram +# (needed for e.g. UserManagment) +# +# Revision 1.42 2003/07/01 23:24:17 joko +# now using package before using function +# +# Revision 1.41 2003/06/29 02:03:45 joko +# fix:? initialize schema on startup +# +# Revision 1.40 2003/06/25 22:57:54 joko +# major rework of "sub sendQuery / sub getListFiltered": now should be capable of "sorting" +# +# Revision 1.39 2003/06/06 11:40:40 jonen +# fixed bug at 'getFilteredList' +# +# Revision 1.38 2003/05/13 16:38:38 joko +# problems with "tied" on 5.6.1/win32 +# +# Revision 1.37 2003/05/10 17:37:39 jonen +# corrected last commit +# +# Revision 1.36 2003/05/10 17:31:18 jonen +# + added new functions related to 'create' item +# - createNode() +# # creates non-persistent 'deep dummy filled' object +# - insertChildNode() +# # inserts child node at given parent (child node haven't to exists, +# createNode will be injected transparently) +# +# Revision 1.35 2003/04/19 16:09:48 jonen +# + added operator dispatching (currently for getting ref-type) at 'getListFiltered' +# +# Revision 1.34 2003/04/11 01:18:53 joko +# sendQuery: +# + introduced crud action 'DELETE' +# +# Revision 1.33 2003/04/09 06:07:43 joko +# revamped 'sub sendQuery' +# +# Revision 1.32 2003/04/08 22:52:22 joko +# modified 'querySchema': better behaviour regarding filtering result +# +# Revision 1.31 2003/04/05 21:24:09 joko +# modified 'sub getChildNodes': now contains code from 'querySchema' +# +# Revision 1.30 2003/03/27 15:31:14 joko +# fixes to modules regarding new namespace(s) below Data::Mungle::* +# +# Revision 1.29 2003/02/21 01:47:18 joko +# purged old code +# minor cosmetics +# +# Revision 1.28 2003/02/20 20:20:26 joko +# tried to get auto-disconnect working again - failed with that +# +# Revision 1.27 2003/01/31 06:30:59 joko +# + enabled 'sendQuery' +# +# Revision 1.26 2003/01/30 22:29:47 joko +# + fixed module usage (removed dependency on 'libp.pm') +# +# Revision 1.25 2003/01/19 02:30:05 joko +# + fix: modified call to '_initSchema' +# +# Revision 1.24 2002/12/22 14:13:01 joko +# + sub dropDb +# +# Revision 1.23 2002/12/19 16:31:53 joko +# +- renamed sub to 'rebuildDb' +# +# Revision 1.22 2002/12/18 22:28:16 jonen +# + added extended logging at 'getObjectByGuid()' +# +# Revision 1.21 2002/12/16 22:20:49 jonen +# + fixed bug at 'getObjectByGuid()' +# +# Revision 1.20 2002/12/16 20:49:17 jonen +# + added sub 'getObjectByGuid()' +# + added functionality to use 'getObjectByGuid' at 'getObjectAsHash()' +# +# Revision 1.19 2002/12/16 06:46:09 joko +# + attempt to introduce a generic '_patchSchema' - cancelled! +# +# Revision 1.18 2002/12/13 21:48:07 joko +# + fix to 'sub sendQuery' +# +# Revision 1.17 2002/12/12 02:51:09 joko +# + cosmetics +# +# Revision 1.16 2002/12/11 06:54:10 joko +# + fix: encapsulated object-loading inside an 'eval' +# +# Revision 1.15 2002/12/05 13:55:21 joko +# + now utilizing 'expand' instead of 'var_deref' +# + played around with having fresh-objects - no progress.... +# +# Revision 1.14 2002/12/05 09:40:30 jonen +# + added option->{destroy} at getObject for unloading all instance +# +# Revision 1.13 2002/12/05 07:59:04 joko +# + now using Tie::SecureHash as a base for the COREHANDLE +# + former public COREHANDLE becomes private _COREHANDLE now +# + sub getCOREHANDLE +# +# Revision 1.12 2002/12/04 11:34:49 joko +# - $schema_tangram doesn't have to be in class? +# +# Revision 1.11 2002/12/04 08:54:08 jonen +# + untested bugfix: undef($object) after transform to hash at getObjectAsHash +# +# Revision 1.10 2002/12/03 15:53:23 joko +# + small bugfix regarding object hierarchy +# +# Revision 1.9 2002/12/03 05:29:40 joko +# + sub getObject +# + sub getObjectAsHash +# +# Revision 1.8 2002/12/01 22:25:51 joko +# + now utilizing metadata from storage locator when connecting to DBI in "raw"-mode +# +# Revision 1.7 2002/12/01 04:46:19 joko +# + sub eraseAll +# +# Revision 1.6 2002/11/29 05:02:30 joko +# - sub getNewPerlObjectByPkgName (moved to libp.pm) +# + sub getMetaInfo +# - sub existsChildNode (moved to Abstract.pm) +# + sub getListUnfiltered +# + sub getListFiltered +# + sub createCursor +# + sub createSet +# + sub sendQuery +# +# Revision 1.5 2002/11/17 06:35:18 joko +# + locator metadata can now be reached via ->{locator} +# - getChildNodes is now wrapped via COREHANDLE +# +# Revision 1.4 2002/10/25 11:44:44 joko +# + sub _initSchema +# + sub existsChildNode +# + sub testIntegrity +# + sub rebuildDbAndSchema +# # Revision 1.3 2002/10/17 03:56:55 joko # + bugfix: trapped eval error # @@ -15,35 +159,73 @@ # Revision 1.1 2002/10/10 03:44:07 cvsjoko # + new # -# -################################# +############################################ + package Data::Storage::Handler::Tangram; use strict; use warnings; +use base ("Data::Storage::Handler"); use base ("Data::Storage::Handler::Abstract"); -use Tangram; + use Data::Dumper; +use Tangram; +use Class::Tangram; + +use DesignPattern::Object; +use Data::Storage::Result::Tangram; +use Data::Mungle::Compare::Struct qw( isEmpty ); +use Data::Mungle::Transform::Deep qw( expand deep_copy merge_to ); # get logger instance my $logger = Log::Dispatch::Config->instance; -our $metainfo = { - 'disconnectMethod' => 'disconnect', -}; +# this holds the complete instantiated schema from tangram +my $schema_tangram; -sub getNewPerlObjectByPkgName { - my $pkgname = shift; - my $args = shift; - $logger->debug( __PACKAGE__ . "->getNewPerlObjectByPkgName( pkgname $pkgname args $args )" ); - my $evstring = "use $pkgname;"; - eval($evstring); - $@ && $logger->error( __PACKAGE__ . ':' . __LINE__ . " Error in eval: " . $@ ); - return $pkgname->new($args); +sub getMetaInfo { + my $self = shift; + $logger->debug( __PACKAGE__ . "->getMetaInfo()" ); + return { + 'disconnectMethod' => 'disconnect', + }; +} + +sub _initSchema { + my $self = shift; + $logger->debug( __PACKAGE__ . "->_initSchema()" ); + #if (!$schema_tangram) { + #my $obj = getNewPerlObjectByPkgName($self->{locator}->{schema}, { EXPORT_OBJECTS => $self->{locator}->{classnames}, want_transactions => $self->{locator}->{want_transactions} } ); + my $obj = DesignPattern::Object->fromPackage($self->{locator}->{schema}, { 'EXPORT_OBJECTS' => $self->{locator}->{classnames}, 'want_transactions' => $self->{locator}->{want_transactions} } ); + $schema_tangram = $obj->getSchema() if $obj; + #} + if (!$schema_tangram) { + $logger->error( __PACKAGE__ . "->_initSchema: No Schema available for $self->{locator}->{schema}." ); + return 0; + } + #$self->_patchSchema(); + return 1; +} + +sub _patchSchema { + my $self = shift; + foreach (keys %{$schema_tangram->{classes}}) { + next if $schema_tangram->{classes}->{$_}->{abstract}; + #next if ($_ ne 'TsBankAccount'); + #$_ ne 'AbstractAccount' && + print "class: $_", "\n"; +#print Dumper($schema_tangram->{classes}->{$_}); + # create new string property named 'guid' + my $tstring = Tangram::String->new(); + $tstring->{name} = $tstring->{col} = 'guid'; + # inject property into schema + #$schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields}->{string}->{$tstring->{name}} = $tstring; + print Dumper($schema_tangram->{classes}->{$_}->{root}->{SPECS}->[0]->{fields}); + } } sub connect { @@ -51,8 +233,12 @@ my $self = shift; my $dsn = shift; - $dsn ||= $self->{dbi}->{dsn}; - + +#print Dumper($self); +#exit; + + # TODO: re-enable + $dsn ||= $self->{locator}->{dbi}->{dsn}; $logger->debug( __PACKAGE__ . "->connect( dsn $dsn )" ); #my $storage = Tangram::Relational->connect( $schema, $dsn ); @@ -64,40 +250,112 @@ # return; # } - my $obj = getNewPerlObjectByPkgName($self->{schema}, { EXPORT_OBJECTS => $self->{classnames} } ); - $self->{schema_tangram} = $obj->getSchema(); - + return unless $self->_initSchema(); + #$self->_initSchema(); + + # create the main tangram storage object #$self->{COREHANDLE} = Tangram::Relational->connect( $schema, $dsn ); - $self->{COREHANDLE} = Tangram::Relational->connect( $self->{schema_tangram}, $dsn ); + $self->{_COREHANDLE} = Tangram::Relational->connect( $schema_tangram, $dsn ); + +#print "connect", "\n"; +#my $core = $self->{_COREHANDLE}; +#print Dumper($core); + # some attempts for configuring the wrapped underlying dbi..... #$self->{STORAGEHANDLE_UNDERLYING} = $self->getUnderlyingStorage(); #$self->{STORAGEHANDLE_UNDERLYING}->_configureCOREHANDLE(); #$self->_configureUnderlyingStorage; + + # ..... encapsulation wins! $self->configureCOREHANDLE(); + $self->{locator}->{status}->{connected} = 1; + + return 1; + } sub getChildNodes { my $self = shift; - my @nodes; + my $mode = shift; + my $filter = shift; + + $mode ||= 'core'; + $filter ||= 'all'; + + $logger->debug( __PACKAGE__ . "->getChildNodes($mode)" ); - # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE - #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(); + if ($mode eq 'core') { - #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) { - if (my $result = $storage->sendCommand( 'SHOW TABLES;' ) ) { - while ( my $row = $result->_getNextEntry() ) { - push @nodes, $row; + my @nodes; + + # create new DBI - Data::Storage - object from already connected DBI::db - handle inside the current COREHANDLE + #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} ); + + # todo: should we retrieve information from the schema here + # rather than poorly getting table names from underlying dbi? + my $storage = $self->_getSubLayerHandle(); + @nodes = @{$storage->getChildNodes()}; + #$storage->_configureCOREHANDLE(); + #print "getchildnodes\n"; + #print Dumper($self); + #if (my $result = $self->sendCommand( 'SHOW TABLES;' ) ) { + + # TODO: REVIEW + #$storage->disconnect(); + + $self->{meta}->{childnodes} = \@nodes; + + return \@nodes; + + } elsif ($mode eq 'root') { + + # FIXME: this will return *all* known classes to 'Class::Tangram', + # which might not be what you expect since more than one instance + # of Tangram may be in memory and Class::Tangram seems to + # offer no methods to determine this or filter its result(s) according + # to a specific database. + my @object_names = Class::Tangram::known_classes(); + my @concret_names; + my $o_cnt; + foreach (sort @object_names) { + push @concret_names, $_ if (!Class::Tangram::class_is_abstract($_)); + $o_cnt++; + } + + if ($filter eq 'all') { + return \@object_names; + } elsif ($filter eq 'concrete') { + return \@concret_names; } - } - $storage->disconnect(); + } - return \@nodes; + +} + +sub testIntegrity { + + my $self = shift; + + $logger->debug( __PACKAGE__ . "->testIntegrity()" ); + + # 1st test: are there tables? + if (!$self->getChildNodes()) { + $logger->warning( __PACKAGE__ . "->testIntegrity no childnodes exist" ); + return; + } + + # 2nd test: is there a table named "Tangram"? + if (!$self->existsChildNode("Tangram")) { + $logger->warning( __PACKAGE__ . "->testIntegrity childnode \"Tangram\" doesn't exist" ); + return; + } + + $self->{locator}->{status}->{integrity} = 1; + return 1; } @@ -106,33 +364,39 @@ my $self = shift; - use Data::Dumper; + $logger->debug( __PACKAGE__ . "->_getSubLayerHandle()" ); + #print Dumper($self); - + # hack, make more generic! - if (!$self->{STORAGE_SUBLAYER}) { - my $loc = Data::Storage::Locator->new( type => "DBI", dbi => $self->{dbi}, COREHANDLE => $self->{COREHANDLE}->{db} ); - $self->{STORAGE_SUBLAYER} = Data::Storage->new( $loc, { protected => 1 } ); + if (!$self->{dataStorageLayer}) { + $logger->debug( __PACKAGE__ . "->_getSubLayerHandle() creating new dataStorageLayer" ); + #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->{locator}->{dbi} } ); + $self->{dataStorageLayer} = Data::Storage->new( $loc, { protected => 1 } ); #$self->{STORAGE_UNDER_THE_HOOD}->{STORAGEHANDLE}->_configureCOREHANDLE(); #$self->{STORAGE_UNDER_THE_HOOD}->_configureCOREHANDLE(); } #print Dumper($self->{STORAGE_UNDER_THE_HOOD}); - return $self->{STORAGE_SUBLAYER}; + return $self->{dataStorageLayer}; } sub _configureUnderlyingStorage { my $self = shift; + + $logger->debug( __PACKAGE__ . "->_configureUnderlyingStorage" ); + $self->_configureCOREHANDLE_DBI(); return; foreach my $key (keys %{$self->{dbi}}) { my $val = $self->{dbi}->{$key}; print "entry: $key; $val", "\n"; - $self->{COREHANDLE}->{db}->{$key} = $val; + $self->{_COREHANDLE}->{db}->{$key} = $val; } #print Dumper($self->{COREHANDLE}->{db}); } @@ -142,53 +406,715 @@ my $self = shift; - $logger->debug( __PACKAGE__ . "->_configureCOREHANDLE" ); + $logger->debug( __PACKAGE__ . "->configureCOREHANDLE" ); #my $subLayer = $self->_getSubLayerHandle(); + #print Dumper($self); + #exit; # apply configured modifications if (exists $self->{dbi}->{trace_level} && exists $self->{dbi}->{trace_file}) { - $self->{COREHANDLE}->{db}->trace($self->{dbi}->{trace_level}, $self->{dbi}->{trace_file}); + $self->{_COREHANDLE}->{db}->trace($self->{dbi}->{trace_level}, $self->{dbi}->{trace_file}); } if (exists $self->{dbi}->{RaiseError}) { - $self->{COREHANDLE}->{db}->{RaiseError} = $self->{dbi}->{RaiseError}; + $self->{_COREHANDLE}->{db}->{RaiseError} = $self->{dbi}->{RaiseError}; } if (exists $self->{dbi}->{PrintError}) { - $self->{COREHANDLE}->{db}->{PrintError} = $self->{dbi}->{PrintError}; + $self->{_COREHANDLE}->{db}->{PrintError} = $self->{dbi}->{PrintError}; } if (exists $self->{dbi}->{HandleError}) { - $self->{COREHANDLE}->{db}->{HandleError} = $self->{dbi}->{HandleError}; + $self->{_COREHANDLE}->{db}->{HandleError} = $self->{dbi}->{HandleError}; } } sub deploySchema { my $self = shift; - #my $dsn = $self->{locator}->{dbi}->{dsn}; - my $dsn = $self->{dbi}->{dsn}; + my $args = shift; + + my $dsn = $self->{locator}->{dbi}->{dsn}; + + $logger->debug( __PACKAGE__ . "->deploySchema( dsn $dsn )" ); + my $ok; - if ( my $dbh = DBI->connect($dsn, '', '', { - PrintError => 0, - } ) ) { - $ok = Tangram::Relational->deploy($self->{schema}, $dbh ); + if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) { + return unless $self->_initSchema(); + $ok = Tangram::Relational->deploy($schema_tangram, $dbh ); $dbh->disconnect(); } return $ok; } sub retreatSchema { - print "retreat\n"; + my $self = shift; - #my $dsn = $self->{locator}->{dbi}->{dsn}; - my $dsn = $self->{dbi}->{dsn}; + my $dsn = $self->{locator}->{dbi}->{dsn}; + + $logger->debug( __PACKAGE__ . "->retreatSchema( dsn $dsn )" ); + my $ok; - if ( my $dbh = DBI->connect($dsn, '', '', { - PrintError => 0, - } ) ) { - $ok = Tangram::Relational->retreat($self->{schema}, $dbh ); + if ( my $dbh = DBI->connect($dsn, '', '', $self->{locator}->{dbi} ) ) { + + return unless $self->_initSchema(); + + #use Data::Dumper; print Dumper($self); + $self->{dataStorageLayer}->removeLogDispatchHandler("Tangram11"); + + $ok = Tangram::Relational->retreat($schema_tangram, $dbh ); + + # answer "$ok=2" means "maybe" for now - we have to patch this to a constant here because... + # - ... Tangram::Relational->retreat doesn't seem to return a valid status + # - possible improvement: + # - test this by checking for count of tables in database + # - problem with this: there may be some left not having been included to the schema + # - maybe better: use "->getChildNodes"? + $ok = 2; + $dbh->disconnect(); + } return $ok; } +sub rebuildDb { + my $self = shift; + $logger->info( __PACKAGE__ . "->rebuildDb()" ); + my @results; + + # sum up results (bool (0/1)) in array + push @results, $self->retreatSchema(); + push @results, $self->{dataStorageLayer}->dropDb(); + push @results, $self->{dataStorageLayer}->createDb(); + push @results, $self->deploySchema(); + + # scan array for "bad ones" + my $res = 1; + map { + $res = 0 if (!$_); + } @results; + + return $res; +} + +sub getListUnfiltered { + my $self = shift; + my $nodename = shift; + my @results; + $logger->debug( __PACKAGE__ . "->getListUnfiltered( nodename => '" . $nodename . "' )" ); + # get set of objects from odbms by object name + my $object_set = $self->{_COREHANDLE}->remote($nodename); + @results = $self->{_COREHANDLE}->select($object_set); + return \@results; +} + +sub getListFiltered { + my $self = shift; + + # redirect to unfiltered mode + #return $self->getListUnfiltered(@_); + + my $in = {}; + $in->{nodename} = shift; + $in->{filters} = shift; + $in->{sorting} = shift; + + my @results; + $logger->debug( __PACKAGE__ . "->getListFiltered( nodename => '" . $in->{nodename} . "' )" ); + + #print Dumper($filters); + + # 1. "Remote Object Handle" - get set of objects from odbms by object name + my $remote = $self->{_COREHANDLE}->remote($in->{nodename}); + + # 2. Transfer $in to $orm_query + my $orm_query = {}; + + # 2.a. Filters + my @tfilters; + my $orm_filter = undef; + + foreach my $filter (@{$in->{filters}}) { + + # get filter - TODO: for each filter + #my $filter = $filters->[0]; + + # 1. The parts of a filter source entry + my $lexpr = $filter->{key}; + #my $op = $filter->{op}; + my $op = '='; + my $rexpr = $filter->{val}; + my $tight = 100; + + # 2. Build filter target entry + + # Test 1 - didn't work out! + # my $tfilter = Tangram::Filter->new( + # expr => "t1.$lexpr $op '$rexpr'", + # tight => $tight, + # objects => $objects, + # ); + + my $orm_filter_tmp = undef; + # was: + # TODO: is_op? + # dispatch un-common operators if exists + if ($filter->{op} eq "ref") { + # do nothing, results will be filtered later cause 'tangram-filter' doesn't support 'ref' query + #print "Filter->op eq 'ref'.\n"; + #push @tfilters, 'ref($remote->{' . $filter->{key} . '})' . " eq '$filter->{val}'"; + } else { + # HACK: build eval-string (sorry) to get filtered list - please give advice here + #push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'"; + # better: calculate expression right here! + #push @tfilters, '$remote->{' . $filter->{key} . '}' . " $filter->{op} '$filter->{val}'"; + + #print "key: ", $filter->{key}, "\n"; + + my $left = $remote->{$filter->{key}}; + #my $r = Tangram::Expr->new( 'string' => "'" . $filter->{val} . "'" ); + my $right = $filter->{val}; + my $op = $filter->{op}; + $orm_filter_tmp = $left->$op($right); + } + + if (not $orm_filter) { + $orm_filter = $orm_filter_tmp; + } else { + $orm_filter = $orm_filter->and($orm_filter_tmp); + } + + } + + $orm_query->{filter} = $orm_filter; + + # was: + + # 2.b. sorting [new as of 2003-06-17] + if ($in->{sorting}) { + my $sorting_rules = []; + my $sorting_order = 'ASC'; + foreach my $sorting_column (keys %{$in->{sorting}}) { + $sorting_order = $in->{sorting}->{$sorting_column} if $in->{sorting}->{$sorting_column}; + push @$sorting_rules, Tangram::Expr->new( 'string' => $sorting_column ); + } + $orm_query->{order} = $sorting_rules; + if ($sorting_order eq 'DESC') { + $orm_query->{desc} = 1; + } + } + + + # 3. build and issue query - return result as Tangram::Cursor + + # coerce hash into array (This is valid in Perl) + my @orm_query_args = %$orm_query; + # send query (arguments) to orm + @results = $self->{_COREHANDLE}->select($remote, @orm_query_args); + + #my $cursor = $self->{_COREHANDLE}->cursor($remote, @orm_query_args); + #return $cursor; + #print Dumper(@results); + + # is: + # HACK: build eval-string (sorry) to get filtered list - please give advice here + #my $evalstring = 'return $self->{_COREHANDLE}->select($remote, ' . $tfilter . $sorting . ');'; + #print "eval: $evalstring", "\n"; + # get filtered list/set + #@results = eval($evalstring); + #die $@ if $@; + + # filter results - NEEDED for e.g. UserManagment !! + if ($in->{filters}->[0]->{op} && ($in->{filters}->[0]->{op} eq "ref")) { + #print "Filter->op eq 'ref'.\n"; + my $att_name = $in->{filters}->[0]->{key}; + my $att_val = $in->{filters}->[0]->{val}; + my @filtered; + foreach(@results) { + if(ref($_->{$att_name}) eq $att_val) { + push @filtered, $_; + } + } + @results = @filtered; + } + + #print "results: " . Dumper(\@results); + + return \@results; +} + +sub createCursor { + my $self = shift; + my $node = shift; + my $cmdHandle = $self->{_COREHANDLE}->cursor($node); + my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $cmdHandle ); + return $result; +} + +sub createSet { + my $self = shift; +#print "-" x 80, "\n"; +#print Dumper(@_); + my @objects = @_; + my $rh = Set::Object->new(); + foreach (@objects) { + if (!isEmpty($_)) { +#print Dumper($_); + $rh->insert($_); + } + } + #print Dumper($rh->members()); + my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh ); + return $result; +} + +sub createResult { + my $self = shift; + my $rh = shift; + my $result = Data::Storage::Result::Tangram->new( RESULTHANDLE => $rh ); + return $result; +} + +sub sendQuery { + my $self = shift; + my $query = shift; + + #print Dumper($query); + + # type = ITEM|LIST|TRANSPARENT + my $type = ''; + # mode = OID|SPECIAL + my $mode = ''; + my $ident = ''; + my $crud = ''; + + + # dispatch type and mode + + # defaults - 1 + if ($query->{options}) { + $crud = $query->{options}->{crud}; + $crud ||= $query->{options}->{action}; + } + + # defaults - 2 + $type ||= 'TRANSPARENT'; + $crud ||= 'RETRIEVE'; + + if ($query->{options}->{OID}) { + $type = 'ITEM'; + $mode = 'OID'; + $ident = $query->{options}->{OID}; + + } elsif (my $guid = $query->{options}->{GUID}) { + $type = 'TRANSPARENT'; + $query->{criterias} = [ { key => 'guid', op => 'eq', val => $guid } ]; + + # if operator is different (dispatcher for 'getListFiltered') + } elsif (my $op = $query->{options}->{op}) { + $type = 'TRANSPARENT'; + $query->{criterias} = [ { key => $query->{options}->{meta_label}, op => $op, val => $query->{options}->{meta_value} } ]; + + } + + # HACK: special case: querying by id does not translate into a common tangram query + # just load the object by given identifier (OID) named 'id' - this is required by Data::Transfer::Sync! + if ($query->{criterias} && ($query->{criterias}->[0]->{key} eq 'id' && $query->{criterias}->[0]->{op} eq 'eq')) { + $type = 'ITEM'; + $mode = 'SPECIAL.SYNC'; + $ident = $query->{criterias}->[0]->{val}; + } + + + # execute query + my $result; + + if ($type eq 'ITEM' && $ident) { + + if ($mode eq 'OID') { + # TODO: review this case! + $result = $self->getObject($ident, $query->{options}); + + } elsif ($mode eq 'SPECIAL.SYNC') { + + # V1 - failed + #return Set::Object->new( $self->{COREHANDLE}->load($query->{criterias}->[0]->{val}) ); + + # hmm.... + #return $self->createSet() if $ident == 5; + + # Unload single object before doing any further operations to + # expect a "fresh" object from orm when performing the next calls. + $self->{_COREHANDLE}->unload($ident); + + # Load object from orm. + my $object = $self->{_COREHANDLE}->load($ident); + + # determine object identifier (OID) + my $oid = $self->{_COREHANDLE}->id($object); + + # encapsulate into result/response container and return this one + $result = $self->createSet($object); + + # debugging + #$result = $self->createSet( $self->{COREHANDLE}->load('300090018') ); + + } + + + } elsif ($type eq 'TRANSPARENT') { + + if ($crud eq 'RETRIEVE') { + + my $list = $self->getListFiltered($query->{node}, $query->{criterias}, $query->{sorting}); + #return $list; + return $self->createResult($list); + + #return $self->createSet($object); + #return $self->createSet($list); + return $self->createSet(@$list); + + #die("This should not be reached for now - redirect to \$self->getListFiltered() here!"); + + # try a generic tangram query here + # TODO: try to place an oql on top of that (search.cpan.org!) + my @crits; + foreach (@{$query->{criterias}}) { + my $op = ''; + $op = '=' if lc $_->{op} eq 'eq'; + push @crits, "$_->{key}$op'$_->{val}'"; + } + my $subnodes = {}; + map { $subnodes->{$_}++ } @{$query->{subnodes}}; + # HACK: this is hardcoded ;( expand possibilities! + #my $crit = join(' AND ', @crits); + #my $sql = hash2Sql($query->{node}, $subnodes, 'SELECT', $crit); + #return $self->sendCommand($sql); + #my $h = $self->{COREHANDLE}->remote($query->{node}); + #my $res = $self->{COREHANDLE}->select($h, $h->{); + $result = $self->createCursor($query->{node}); + + } elsif ($crud eq 'UPDATE') { + + # Patch current query to be a loader (e.g. change action, remove payload) ... + my $childquery = deep_copy($query); + $childquery->{options}->{crud} = 'RETRIEVE'; + delete $childquery->{payload}; + + # ... to use it to fetch a fresh object using ourselves (sendQuery). + my $cursor = $self->sendQuery($childquery); + my $status = $cursor->getStatus(); + my $object = $cursor->getNextEntry(); + + # Merge values and apply value modifiers. + my $options = { utf8 => 1, php => 1 }; + merge_to($object, $query->{payload}, $options); + + # Execute update operation at orm. + $self->update($object); + + } elsif ($crud eq 'DELETE') { + + # Patch current query to be a loader (e.g. change action) ... + my $childquery = deep_copy($query); + $childquery->{options}->{crud} = 'RETRIEVE'; + + # ... to use it to fetch a fresh object using ourselves (sendQuery). + my $cursor = $self->sendQuery($childquery); + my $status = $cursor->getStatus(); + my $object = $cursor->getNextEntry(); + + $self->erase($object); + + } elsif ($crud eq 'CREATE') { + + my $nodename = $query->{node}; + my $newnode = $self->createNode($nodename); + my $id = $self->{_COREHANDLE}->insert($newnode); + + print "Saved new node $nodename with GUID $newnode->{guid}, OID '$id': " . Dumper($newnode) . "\n"; + + return $newnode; + + } + + } + + return $result; + +} + +sub eraseAll { + my $self = shift; + my $classname = shift; + my $remote = $self->{_COREHANDLE}->remote($classname); + my @objs = $self->{_COREHANDLE}->select($remote); + $self->{_COREHANDLE}->erase(@objs); +} + +sub createDb { + my $self = shift; + my $storage = $self->_getSubLayerHandle(); + return $storage->createDb(); +} + +sub getObject { + my $self = shift; + my $oid = shift; + my $options = shift; + + # TODO: create a deep_unload method (currently _all_ objects are unloaded) + # unload($oid) will only unload object, not deep object hashes + $self->{_COREHANDLE}->unload() if ($options->{destroy}); + + # TODO: review this + #if (!$self->{COREHANDLE}) { return; } + + # TODO: review this + my $object = eval('$self->{_COREHANDLE}->load($oid);'); + print $@, "\n" if $@; + + return $object if $object; +} + +sub getObjectByGuid_old { + my $self = shift; + my $guid = shift; + my $options = shift; + + # Guid and Classname is needed + if(!$guid || !$options->{classname}) { + $logger->error( __PACKAGE__ . "->getObjectByGuid: No 'guid' OR no Classname in options hash was given but needed!" ); + return; + } + + # TODO: create a deep_unload method (currently _all_ objects are unloaded) + # unload($oid) will only unload object, not deep object hashes + $self->{_COREHANDLE}->unload() if ($options->{destroy}); + + # search for object with given Classname and Guid + my $obj_tmp = $self->{_COREHANDLE}->remote($options->{classname}); + my @result = $self->{_COREHANDLE}->select($obj_tmp, $obj_tmp->{guid} eq $guid); + + # we searched for global unique identifer of some object, + # so I think we can trust there would be only one result + if($result[0]) { + return $result[0]; + } else { + $logger->error( __PACKAGE__ . "->getObjectByGuid: No Object with Classname $options->{classname} and GUID $guid found!" ); + return; + } + +} + +sub getObjectAsHash_old { + my $self = shift; + my $oid = shift; + my $options = shift; + my $obj; + + if($options->{guid}) { + $obj = $self->getObjectByGuid($oid, $options); + } else { + $obj = $self->getObject($oid, $options); + } + + # build options (a callback to unload autovivified objects) for 'expand' + # TODO: use $logger to write to debug here! + my $cb; # = sub {}; + + # deactivated way to get rid of used instances, if requested +=pod + if ($options->{destroy}) { + $options->{cb}->{destroy} = sub { + print "================ DESTROY", "\n"; + my $object = shift; + #print Dumper($object); + $self->{_COREHANDLE}->unload($object); + #undef($object); + }; + } +=cut + + my $hash = expand($obj, $options); + + # old (unsuccessful) attempts to get rid of used instances, if requested + + # V1: + #$options->{cb}->{destroy}->($obj); + #$self->{_COREHANDLE}->unload($obj); + + # V2: + #$obj->clear_refs; + #$self->{COREHANDLE}->unload($obj) if($options->{destroy}); + #$obj->DESTROY; + #undef($obj) if($options->{destroy}); + + return $hash; +} + +sub getSchema { + return $schema_tangram; +} + +sub getCOREHANDLE { + my $self = shift; + return $self->{_COREHANDLE}; +} + +sub dropDb { + my $self = shift; + my $storage = $self->_getSubLayerHandle(); + return $storage->dropDb(); +} + +sub testAvailability { + my $self = shift; + my $storage = $self->_getSubLayerHandle(); + return $storage->testAvailability(); +} + +sub disconnect2 { + my $self = shift; + my $storage = $self->_getSubLayerHandle(); + print "DISC!", "\n"; + + my $storage_ll = $storage->{_COREHANDLE}; + $storage_ll->disconnect(); + + print Dumper($storage); + exit; + + #$self->{_COREHANDLE} + #$storage->disconnect(); + $self->{dataStorageLayer}->disconnect(); +} + + +sub createNode { + my $self = shift; + my $classname = shift; + + my $obj = $classname->new(); + + my $attr_options = Class::Tangram::attribute_options($classname); + #print "Attribute Options: " . Dumper($attr_options); + + my $attr_types = Class::Tangram::attribute_types($classname); + #print "Attribute Types: " . Dumper($attr_types); + + foreach(keys %{$attr_types}) { + if($attr_types->{$_} eq 'string') { + $obj->{$_} = ''; + } elsif($attr_types->{$_} eq 'int') { + $obj->{$_} = 0; + } elsif($attr_types->{$_} eq 'real') { + $obj->{$_} = 0; + } elsif($attr_types->{$_} eq 'rawdatetime') { + $obj->{$_} = '0000-00-00 00:00:00'; + } elsif($attr_types->{$_} eq 'ref') { + if($attr_options->{$_}->{class}) { + $obj->{$_} = $self->createNode($attr_options->{$_}->{class}); + } else { + #$obj->{$_} = undef(); + } + } elsif($attr_types->{$_} eq 'iarray') { + $obj->{$_} = [ ]; + } elsif($attr_types->{$_} eq 'hash') { + $obj->{$_} = { }; + } elsif($attr_types->{$_} eq 'flat_hash') { + $obj->{$_} = { }; + } + } + + #print "New Object: " . Dumper($obj); + + return $obj; +} + + + sub insertChildNode { + my $self = shift; + my $child_entry = shift; + my $query_args = shift; + + my $core = $self->{_COREHANDLE}; + my $nodename = $query_args->{nodename}; + + # get parent object + my $query = { + node => $query_args->{parent}->{nodename}, + options => { GUID => $query_args->{parent}->{guid}, }, + }; + my $cursor = $self->sendQuery($query); + my $parent = $cursor->getNextEntry(); + + # debug + #print "Parent_org: " . Dumper($parent); + + # Create child node object if isn't already done + # ($child_entry have to be the class name then...) + if(!ref($child_entry)) { + $child_entry = $self->createNode($child_entry); + # it could be insert 'manually' or will be insert 'transparent' if parent will be updated + #$core->insert($child_entry); + #print "Create child object [$nodename]: " . Dumper($child_entry); + } + + # get reference of tied node (seems, only on Linux node's are tied!!) + my $tied_node = tied $parent->{$nodename}; + + # insert/change child entry at parent + #print "reference: " . ref($parent->{$nodename}) . "\n"; + if(ref($parent->{$nodename}) eq 'ARRAY') { + # (seems, only on Linux node's are tied!!) + if($tied_node) { + # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type, + # so a 'PUSH' is not implemented (which could be then done transparently) + my $array = $tied_node->FETCH; + push @$array, $child_entry; + $tied_node->STORE($array); + # node will be normaly untied at 'STORE' + if(tied $parent->{$nodename}) { print "already tied !!\n"; } + else { undef $tied_node; } + } else { + push @{$parent->{$nodename}}, $child_entry; + } + } + elsif(ref($parent->{$nodename}) eq 'HASH') { + if(my $key = $query_args->{hash_key}) { + # (seems, only on Linux node's are tied!!) + if($tied_node) { + # same problem as with 'ARRAY': + # all tangram types are tied as 'SCALAR' with special 'FETCH', 'STORE' methods per type. + my $hash = $tied_node->FETCH; + $hash->{$key} = $child_entry; + $tied_node->STORE($hash); + # node will be normaly untied at 'STORE' + if(tied $parent->{$nodename}) { print "already tied !!\n"; } + else { undef $tied_node; } + } else { + $parent->{$nodename}->{$key} = $child_entry; + } + } else { + print "ERROR: No HASH KEY given, so not able to insert hash entry!"; + } + } + else { + $parent->{$nodename} = $child_entry; + } + + # debug + #print "Parent_new: " . Dumper($parent); + + # save parent + $core->update($parent); + + # debug + #print "Saved Parent: ". Dumper($parent); + + return $child_entry; + } + + 1; +__END__