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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.40 - (show annotations)
Wed Jun 25 22:57:54 2003 UTC (21 years ago) by joko
Branch: MAIN
Changes since 1.39: +97 -31 lines
major rework of "sub sendQuery / sub getListFiltered": now should be capable of "sorting"

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

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