/[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.47 - (show annotations)
Tue Aug 31 14:26:08 2004 UTC (19 years, 10 months ago) by jonen
Branch: MAIN
Changes since 1.46: +5 -2 lines
updated

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

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