| 1 | ## @file | ||
| 2 | # (Enter your file info here) | ||
| 3 | # | ||
| 4 | # @copy 2007 MailerMailer LLC | ||
| 5 | # $Id: Record.pm 498 2008-08-22 15:35:28Z kamelkev $ | ||
| 6 | |||
| 7 | ## @class RWDE::DB::Record | ||
| 8 | # (Enter RWDE::DB::Record info here) | ||
| 9 | package RWDE::DB::Record; | ||
| 10 | |||
| 11 | use strict; | ||
| 12 | use warnings; | ||
| 13 | |||
| 14 | use Crypt::CBC; | ||
| 15 | use Crypt::Rijndael; # aka the AES | ||
| 16 | use Error qw(:try); | ||
| 17 | use MIME::Base64; | ||
| 18 | use Storable qw(nfreeze thaw); | ||
| 19 | |||
| 20 | use RWDE::Exceptions; | ||
| 21 | use RWDE::DB::DbRegistry; | ||
| 22 | |||
| 23 | use base qw(RWDE::RObject RWDE::DB::Items Exporter); | ||
| 24 | |||
| 25 | @RWDE::DB::Record::EXPORT = qw(transaction prepare_transaction); | ||
| 26 | |||
| 27 | use vars qw($VERSION); | ||
| 28 | $VERSION = sprintf "%d", q$Revision: 555 $ =~ /(\d+)/; | ||
| 29 | |||
| 30 | ## @cmethod object new() | ||
| 31 | # (Enter new info here) | ||
| 32 | # @return (Enter explanation for return value here) | ||
| 33 | sub new() { | ||
| 34 | my ($proto, $params) = @_; | ||
| 35 | |||
| 36 | my $class = ref($proto) || $proto; | ||
| 37 | |||
| 38 | my $self = { _data => {}, }; | ||
| 39 | |||
| 40 | bless($self, $class); | ||
| 41 | |||
| 42 | no strict 'refs'; | ||
| 43 | $self->{_db} = ${ $class . "::db" }; | ||
| 44 | $self->{_table} = ${ $class . "::table" }; | ||
| 45 | $self->{_id} = ${ $class . "::id" }; | ||
| 46 | $self->{_index} = ${ $class . "::index" }; | ||
| 47 | $self->{_index_fields} = \%{ $class . "::index_fields" }; | ||
| 48 | $self->{_modifiable_fields} = \%{ $class . "::modifiable_fields" }; | ||
| 49 | $self->{_modifiable_fieldnames} = \@{ $class . "::modifiable_fieldnames" }; | ||
| 50 | $self->{_static_fields} = \%{ $class . "::static_fields" }; | ||
| 51 | $self->{_static_fieldnames} = \@{ $class . "::static_fieldnames" }; | ||
| 52 | $self->{_fieldnames} = \@{ $class . "::fieldnames" }; | ||
| 53 | $self->{_fields} = \%{ $class . "::fields" }; | ||
| 54 | $self->{_ccrcontext} = ${ $class . "::ccrcontext" }; | ||
| 55 | $self->{_email} = ${ $class . "::email" }; | ||
| 56 | |||
| 57 | # Moving static initializers | ||
| 58 | # my %fields_temp = (%{$self->{_static_fields}}, %{$self->{_modifiable_fields}}); | ||
| 59 | # $self->{_fields} = \%fields_temp; | ||
| 60 | # | ||
| 61 | # @static_fieldnames = sort keys %static_fields; | ||
| 62 | # @modifiable_fieldnames = sort keys %modifiable_fields; | ||
| 63 | # @fieldnames = sort keys %fields; | ||
| 64 | # | ||
| 65 | |||
| 66 | $self->initialize($params); | ||
| 67 | |||
| 68 | return $self; | ||
| 69 | } | ||
| 70 | |||
| 71 | sub Create { | ||
| 72 | my ($self, $params) = @_; | ||
| 73 | |||
| 74 | my $term = $self->new; | ||
| 75 | |||
| 76 | #copy over all modifiable field names from params | ||
| 77 | foreach my $f (@{ $term->{_modifiable_fieldnames} }) { | ||
| 78 | if (defined($$params{$f})) { | ||
| 79 | $term->$f($$params{$f}); | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | $term->create_record(); | ||
| 84 | |||
| 85 | return $term; | ||
| 86 | } | ||
| 87 | |||
| 88 | sub Force_create { | ||
| 89 | my ($self, $params) = @_; | ||
| 90 | |||
| 91 | my $term = $self->new; | ||
| 92 | |||
| 93 | #copy over _all_ field names from params | ||
| 94 | foreach my $field (@{ $term->{_fieldnames} }) { | ||
| 95 | next unless defined($$params{$field}); | ||
| 96 | #this circumvents the accessor and hence the check | ||
| 97 | #whether the field should be allowed to be modified | ||
| 98 | $term->{_data}->{$field} = $$params{$field}; | ||
| 99 | } | ||
| 100 | |||
| 101 | $term->insert_all(); | ||
| 102 | |||
| 103 | return $term; | ||
| 104 | } | ||
| 105 | |||
| 106 | |||
| 107 | ## @method void initialize() | ||
| 108 | # (Enter initialize info here) | ||
| 109 | sub initialize { | ||
| 110 | my ($self, $params) = @_; | ||
| 111 | return (); | ||
| 112 | } | ||
| 113 | |||
| 114 | =pod | ||
| 115 | |||
| 116 | =head2 normalize | ||
| 117 | |||
| 118 | "Normalize" the data to the data type for the database. Returns | ||
| 119 | value suitable for insertion into database, or undef on error. | ||
| 120 | field type 'crypt' stores data in DB encrypted but presents to object | ||
| 121 | as plain text. Specify it as "crypt:KEY" where KEY is used for the | ||
| 122 | encryption key. | ||
| 123 | |||
| 124 | =cut | ||
| 125 | |||
| 126 | ## @method object normalize() | ||
| 127 | # (Enter normalize info here) | ||
| 128 | # @return (Enter explanation for return value here) | ||
| 129 | sub normalize { | ||
| 130 | my $self = shift; | ||
| 131 | my $fn = shift; | ||
| 132 | my $value = shift; | ||
| 133 | |||
| 134 | my $dbh = $self->get_dbh(); | ||
| 135 | |||
| 136 | return | ||
| 137 | unless exists($self->{_fields}->{$fn}); | ||
| 138 | |||
| 139 | my $type = $self->field_type($fn); | ||
| 140 | |||
| 141 | # The value might be an object (i.e. exception), | ||
| 142 | # double quotes call stringify on the object and do not change the value of a plain scalar | ||
| 143 | if (!(defined($value)) || ("$value" eq 'NULL')) { | ||
| 144 | $value = 'NULL'; # exists but undef | ||
| 145 | } | ||
| 146 | elsif ($type eq 'char') { | ||
| 147 | $value = $dbh->quote($value); | ||
| 148 | } | ||
| 149 | elsif ($type eq 'char_lc') { | ||
| 150 | $value = $dbh->quote(lc($value)); | ||
| 151 | } | ||
| 152 | elsif ($type eq 'int') { | ||
| 153 | $value += 0; # make sure something there! | ||
| 154 | } | ||
| 155 | elsif ($type eq 'IP') { | ||
| 156 | $value = $dbh->quote($value); | ||
| 157 | } | ||
| 158 | elsif ($type eq 'email') { | ||
| 159 | $value = $dbh->quote(lc($value)); | ||
| 160 | } | ||
| 161 | elsif ($type eq 'float') { | ||
| 162 | $value += 0.0; # make sure something there! | ||
| 163 | } | ||
| 164 | elsif ($type eq 'array') { | ||
| 165 | $value = $dbh->quote(join($;, @$value)); | ||
| 166 | } | ||
| 167 | elsif ($type eq 'set') { | ||
| 168 | my @setfields = grep { defined $value->{$_} && $value->{$_} == 1 } keys %$value; | ||
| 169 | $value = $dbh->quote(join(',', @setfields)); | ||
| 170 | } | ||
| 171 | elsif ($type eq 'timestamp') { | ||
| 172 | |||
| 173 | if ($value =~ m/^[0-9]+$/) { | ||
| 174 | throw RWDE::DatabaseErrorException({ info => 'Record->' . $fn . 'of type ' . $type . ' cannot accept epoch stamp: ' . $value . ' for ' . caller() }); | ||
| 175 | } | ||
| 176 | if ($value =~ m/^([a-z]|[A_Z])+$/) { | ||
| 177 | throw RWDE::DatabaseErrorException({ info => 'Record->' . $fn . 'of type ' . $type . ' cannot accept epoch stamp: ' . $value . ' for ' . caller() }); | ||
| 178 | } | ||
| 179 | |||
| 180 | $value = $dbh->quote($value); | ||
| 181 | } | ||
| 182 | elsif ($type eq 'boolean') { | ||
| 183 | if (($value eq 'true') || ($value eq 't') || ($value eq '1')) { | ||
| 184 | $value = 'true'; | ||
| 185 | } | ||
| 186 | elsif (($value eq 'false') || ($value eq 'f') || ($value eq '0')) { | ||
| 187 | $value = 'false'; | ||
| 188 | } | ||
| 189 | } | ||
| 190 | elsif ($type =~ m/crypt:(\w+)/) { | ||
| 191 | |||
| 192 | # store string encrypted in DB, but present decrypted to object. | ||
| 193 | my $key = $1; | ||
| 194 | my $c = new Crypt::CBC( | ||
| 195 | -cipher => 'Crypt::Rijndael', | ||
| 196 | -key => $key | ||
| 197 | ); | ||
| 198 | $value = $dbh->quote($c->encrypt_hex($value)); | ||
| 199 | } | ||
| 200 | elsif ($type eq 'frozen') { | ||
| 201 | |||
| 202 | # store frozen hash data in DB | ||
| 203 | $value = $dbh->quote(encode_base64(nfreeze($value))); | ||
| 204 | } | ||
| 205 | elsif ($type eq 'hash') { | ||
| 206 | |||
| 207 | #convert the hash to a string | ||
| 208 | $value = $self->dehashify({ hash => $value }); | ||
| 209 | $value = $dbh->quote($value); | ||
| 210 | } | ||
| 211 | elsif ($type eq 'base64') { | ||
| 212 | |||
| 213 | #convert the data from base64 encoded value | ||
| 214 | $value = encode_base64($value); | ||
| 215 | $value = $dbh->quote($value); | ||
| 216 | } | ||
| 217 | else { | ||
| 218 | warn "Unknown field type for $fn"; # programmer error | ||
| 219 | $value = undef; | ||
| 220 | } | ||
| 221 | |||
| 222 | return $value; | ||
| 223 | } | ||
| 224 | |||
| 225 | =pod | ||
| 226 | |||
| 227 | =head2 denormalize | ||
| 228 | |||
| 229 | "Denormalize" the data based on the data type for the database. | ||
| 230 | Returns value suitable for display, or undef on error. Currently | ||
| 231 | only does stringified ARRAY to arrayref, SET to href of keys | ||
| 232 | indicating which fields are in the set, bitvectors, timestamps, and | ||
| 233 | encrypted fields. | ||
| 234 | Stringified ARRAYs can also be converted to postgres internal array | ||
| 235 | type which we call "list". | ||
| 236 | |||
| 237 | =cut | ||
| 238 | |||
| 239 | ## @method object denormalize() | ||
| 240 | # (Enter denormalize info here) | ||
| 241 | # @return (Enter explanation for return value here) | ||
| 242 | sub denormalize { | ||
| 243 | my $self = shift; | ||
| 244 | my $fn = shift; | ||
| 245 | my $value = shift; | ||
| 246 | |||
| 247 | return | ||
| 248 | unless exists($self->{_fields}->{$fn}); | ||
| 249 | |||
| 250 | my $type = $self->field_type($fn); | ||
| 251 | |||
| 252 | if ((not defined $value) and ($type eq 'boolean')) { | ||
| 253 | return 'NULL'; | ||
| 254 | } | ||
| 255 | elsif (not defined $value) { | ||
| 256 | return $value; | ||
| 257 | } | ||
| 258 | |||
| 259 | if ($type eq 'array') { | ||
| 260 | $value = [ split /$;/, $value ]; | ||
| 261 | } | ||
| 262 | elsif ($type eq 'set') { | ||
| 263 | my $h = {}; | ||
| 264 | foreach my $k (split(/,/, $value)) { | ||
| 265 | $h->{$k} = 1; | ||
| 266 | } | ||
| 267 | $value = $h; | ||
| 268 | } | ||
| 269 | elsif ($type eq 'hash') { | ||
| 270 | $value = $self->hashify({ string => $value }); | ||
| 271 | } | ||
| 272 | elsif ($type =~ m/crypt:(\w+)/) { | ||
| 273 | my $key = $1; | ||
| 274 | if (defined $value and not($value =~ m/^53616c7465645f5f/)) { # encryption sentinel: "RandomIV" | ||
| 275 | throw RWDE::DevelException({ info => "$value has incorrect sentinel: cannot be decrypted" }); | ||
| 276 | } | ||
| 277 | my $c = new Crypt::CBC(-cipher => 'Crypt::Rijndael', -key => $key, -blocksize => 16); | ||
| 278 | $value = $c->decrypt_hex($value); | ||
| 279 | } | ||
| 280 | elsif ($type eq 'frozen') { | ||
| 281 | $value = thaw(decode_base64($value)); | ||
| 282 | } | ||
| 283 | elsif ($type eq 'base64') { | ||
| 284 | |||
| 285 | #convert the data from base64 encoded value | ||
| 286 | $value = decode_base64($value); | ||
| 287 | } | ||
| 288 | |||
| 289 | return $value; | ||
| 290 | } | ||
| 291 | |||
| 292 | =pod | ||
| 293 | |||
| 294 | =head2 create_record | ||
| 295 | |||
| 296 | Create a record with values specified in the data fields of this object. | ||
| 297 | Returns the ID created on success, or throws an exception on failure. | ||
| 298 | Depending on the hash set up it may depend on the database to create a unique id. | ||
| 299 | |||
| 300 | Exceptions classes thrown are C<dberr> on database error or | ||
| 301 | C<data.duplicate> for a duplicate key specified. | ||
| 302 | |||
| 303 | =cut | ||
| 304 | |||
| 305 | ## @method void create_record() | ||
| 306 | # (Enter create_record info here) | ||
| 307 | sub create_record { | ||
| 308 | my ($self, $params) = @_; | ||
| 309 | |||
| 310 | local ($") = ","; #" | ||
| 311 | |||
| 312 | my @fields; # fields to insert | ||
| 313 | my @values; # corresponding values | ||
| 314 | my $table = $self->{_table}; # the table for the object | ||
| 315 | |||
| 316 | foreach my $fieldname (@{ $self->{_modifiable_fieldnames} }) { | ||
| 317 | next unless exists($self->{_data}->{$fieldname}); # no value specified for update | ||
| 318 | |||
| 319 | my $value = $self->normalize($fieldname, $self->{_data}->{$fieldname}); | ||
| 320 | next unless defined($value); | ||
| 321 | |||
| 322 | push(@fields, $fieldname); | ||
| 323 | push(@values, $value); | ||
| 324 | } | ||
| 325 | |||
| 326 | my $dbh = $self->get_dbh(); | ||
| 327 | |||
| 328 | my $sth; | ||
| 329 | if ((@fields > 0) && (@values > 0)) { | ||
| 330 | $sth = $dbh->prepare("INSERT INTO $table (@fields) VALUES (@values)"); | ||
| 331 | } | ||
| 332 | elsif ($self->{_id} && $self->{_index}) { | ||
| 333 | $sth = $dbh->prepare("INSERT INTO $table (" . $self->{_id} . ") VALUES (DEFAULT)"); | ||
| 334 | } | ||
| 335 | else { | ||
| 336 | throw RWDE::DevelException({ info => 'Attempt to create a record without any values (default or otherwise)' }); | ||
| 337 | } | ||
| 338 | |||
| 339 | if ($sth && $sth->execute) { | ||
| 340 | if ($self->{_index}) { | ||
| 341 | |||
| 342 | # we are using sequences, pull the sequence value we just assigned | ||
| 343 | my $sth_local = $dbh->prepare("SELECT currval(?)"); | ||
| 344 | $sth_local->execute($self->{_index}); | ||
| 345 | my $newid = scalar $sth_local->fetchrow_array; # we expect single column, single row here | ||
| 346 | |||
| 347 | # load to populate the fields with default values in the db | ||
| 348 | my $created = $self->fetch_by_id({ $self->{_id} => $newid }); | ||
| 349 | |||
| 350 | $self->copy_record($created); | ||
| 351 | } | ||
| 352 | } | ||
| 353 | else { | ||
| 354 | my $error = $dbh->errstr(); | ||
| 355 | |||
| 356 | # some error... | ||
| 357 | if ($error =~ m/duplicate/i) { | ||
| 358 | |||
| 359 | # duplicate ID | ||
| 360 | throw RWDE::DataDuplicateException({ info => 'Duplicate information requested for create' }); | ||
| 361 | } | ||
| 362 | else { | ||
| 363 | throw RWDE::DevelException({ info => $error }); | ||
| 364 | } | ||
| 365 | } | ||
| 366 | |||
| 367 | return $self->get_id(); | ||
| 368 | } | ||
| 369 | |||
| 370 | ## @method void refresh() | ||
| 371 | # Re-fetch the element from the db, trigger might have updated the record | ||
| 372 | sub refresh { | ||
| 373 | my ($self, $params) = @_; | ||
| 374 | |||
| 375 | my $fresh = $self->fetch_by_id({ $self->get_id_name() => $self->get_id() }); | ||
| 376 | |||
| 377 | $self->copy_record($fresh); | ||
| 378 | |||
| 379 | return (); | ||
| 380 | } | ||
| 381 | |||
| 382 | ## @method protected object _fetch_by_id() | ||
| 383 | # Private routine to fetch a record by class_id | ||
| 384 | # @return the populated object | ||
| 385 | sub _fetch_by_id { | ||
| 386 | my ($self, $params) = @_; | ||
| 387 | |||
| 388 | my $id = $$params{ $self->{_id} }; | ||
| 389 | |||
| 390 | throw RWDE::DataNotFoundException({ info => $self . ' No id was specified to lookup' }) | ||
| 391 | unless defined $id; | ||
| 392 | |||
| 393 | return $self->fetch_one( | ||
| 394 | { | ||
| 395 | query => $self->{_id} . " = ?", | ||
| 396 | query_params => [ $id ], | ||
| 397 | } | ||
| 398 | ); | ||
| 399 | } | ||
| 400 | |||
| 401 | sub fetch_one_by { | ||
| 402 | my ($self, $params) = @_; | ||
| 403 | |||
| 404 | throw RWDE::DevelException({ info => ' No params specified for lookup' }) | ||
| 405 | unless defined $params; | ||
| 406 | |||
| 407 | my @query; | ||
| 408 | my @query_params; | ||
| 409 | |||
| 410 | foreach my $key (keys %$params) { | ||
| 411 | push(@query, "$key =?"); | ||
| 412 | push(@query_params, $$params{$key}); | ||
| 413 | } | ||
| 414 | |||
| 415 | return $self->fetch_one({ query => join(' AND ', @query), query_params => \@query_params, }); | ||
| 416 | } | ||
| 417 | |||
| 418 | ## @method object fetch_random($query, $query_params) | ||
| 419 | # (Enter fetch_random info here) | ||
| 420 | # @param query_params (Enter explanation for param here) | ||
| 421 | # @param query (Enter explanation for param here) | ||
| 422 | # @return (Enter explanation for return value here) | ||
| 423 | sub fetch_random { | ||
| 424 | my ($self, $params) = @_; | ||
| 425 | |||
| 426 | #inject ordered by into the query | ||
| 427 | my $query = $$params{query} . ' ORDER BY random() '; | ||
| 428 | |||
| 429 | return $self->fetch_one({ query => $query, query_params => $$params{query_params} }); | ||
| 430 | } | ||
| 431 | |||
| 432 | ## @method object fetch_one() | ||
| 433 | # (Enter fetch_one info here) | ||
| 434 | # @return (Enter explanation for return value here) | ||
| 435 | sub fetch_one { | ||
| 436 | my ($self, $params) = @_; | ||
| 437 | |||
| 438 | my $items_ref = $self->fetch($params); | ||
| 439 | |||
| 440 | my $item = $$items_ref[0] | ||
| 441 | or throw RWDE::DataNotFoundException({ info => "No record found for the specified criteria: $self" }); | ||
| 442 | |||
| 443 | if (@$items_ref > 1) { | ||
| 444 | |||
| 445 | #TODO weed out calls the need one element, but ask for more | ||
| 446 | my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1); | ||
| 447 | warn "From $package on $line asked for more than one element from fetch one"; | ||
| 448 | |||
| 449 | # throw RWDE::DevelException({ info => "Fetch_one returned more than one item (" . scalar @$items_ref . ") -- check the criteria for search." }); | ||
| 450 | } | ||
| 451 | |||
| 452 | return $item; | ||
| 453 | } | ||
| 454 | |||
| 455 | sub Update_record { | ||
| 456 | my ($self, $params) = @_; | ||
| 457 | |||
| 458 | #pull up the current object | ||
| 459 | my $term = $self->fetch_by_id({ $self->get_id_name() => $$params{ $self->get_id_name } }); | ||
| 460 | |||
| 461 | #copy over all modifiable field names from params | ||
| 462 | foreach my $f (@{ $term->{_modifiable_fieldnames} }) { | ||
| 463 | if (defined($$params{$f})) { | ||
| 464 | $term->$f($$params{$f}); | ||
| 465 | } | ||
| 466 | } | ||
| 467 | |||
| 468 | #if we got this far we are good to update the record in the db | ||
| 469 | $term->update_record(); | ||
| 470 | |||
| 471 | return $term->get_id(); | ||
| 472 | } | ||
| 473 | |||
| 474 | ## @method void update_record() | ||
| 475 | # Update the record specified by the C<id> field with values | ||
| 476 | # specified in the data fields of this object. Only updates the fields | ||
| 477 | # specified -- other fields are left alone. Returns 1 on on success, or | ||
| 478 | # throws an exception on failure. | ||
| 479 | # | ||
| 480 | # Exceptions classes thrown are C<dberr> on database error or | ||
| 481 | # C<data.missing> for a missing ID. | ||
| 482 | |||
| 483 | sub update_record { | ||
| 484 | my ($self, $params) = @_; | ||
| 485 | |||
| 486 | my $id = $self->{_data}->{ $self->{_id} }; | ||
| 487 | |||
| 488 | throw RWDE::DevelException({ info => $self . 'Invalid ID specified for update' }) | ||
| 489 | unless (defined $id && $id > 0); | ||
| 490 | |||
| 491 | my @fields = (); # list of updates to perform | ||
| 492 | |||
| 493 | foreach my $field (@{ $self->{_modifiable_fieldnames} }) { | ||
| 494 | next unless exists($self->{_data}->{$field}); # no value specified for update | ||
| 495 | |||
| 496 | my $value = $self->normalize($field, $self->{_data}->{$field}); | ||
| 497 | |||
| 498 | next unless defined($value); | ||
| 499 | push @fields, "$field=$value"; | ||
| 500 | } | ||
| 501 | |||
| 502 | my $dbh = $self->get_dbh(); | ||
| 503 | |||
| 504 | local ($") = ','; #" | ||
| 505 | |||
| 506 | my $row_count = $dbh->do("UPDATE " . $self->{_table} . " SET @fields WHERE " . $self->{_id} . " =?", undef, $id); | ||
| 507 | |||
| 508 | # 0E0 means 0 rows affected, an error in single update instance | ||
| 509 | if ($row_count eq '0E0') { $row_count = 0; } | ||
| 510 | |||
| 511 | unless ($row_count) { | ||
| 512 | if ((defined($dbh->errstr)) && ($dbh->errstr =~ m/duplicate/i)) { | ||
| 513 | |||
| 514 | # duplicated a unique field | ||
| 515 | throw RWDE::DataDuplicateException({ info => 'Non-unique value detected in field: ' . $dbh->errstr }); | ||
| 516 | } | ||
| 517 | else { | ||
| 518 | throw RWDE::DevelException({ info => $dbh->errstr }); | ||
| 519 | } | ||
| 520 | } | ||
| 521 | |||
| 522 | return (); | ||
| 523 | } | ||
| 524 | |||
| 525 | ## @method void update_all() | ||
| 526 | # (Enter update_all info here) | ||
| 527 | sub update_all { | ||
| 528 | my ($self, $params) = @_; | ||
| 529 | |||
| 530 | my $id = $self->{_data}->{ $self->{_id} }; | ||
| 531 | |||
| 532 | throw RWDE::DevelException({ info => $self . 'Invalid ID specified for update' }) | ||
| 533 | unless (defined $id and $id > 0); | ||
| 534 | |||
| 535 | RWDE::DB::DbRegistry->db_check_transaction({ db => $self->{_db} }); | ||
| 536 | |||
| 537 | my @fields = (); # list of updates to perform | ||
| 538 | |||
| 539 | foreach my $field (@{ $self->{_fieldnames} }) { | ||
| 540 | next unless exists($self->{_data}->{$field}); # no value specified for update | ||
| 541 | |||
| 542 | my $value = $self->normalize($field, $self->{_data}->{$field}); | ||
| 543 | |||
| 544 | next unless defined($value); | ||
| 545 | push @fields, "$field=$value"; | ||
| 546 | } | ||
| 547 | |||
| 548 | my $dbh = $self->get_dbh(); | ||
| 549 | |||
| 550 | local ($") = ','; #" | ||
| 551 | |||
| 552 | unless ($dbh->do("UPDATE " . $self->{_table} . " SET @fields WHERE " . $self->{_id} . " =?", undef, $id)) { | ||
| 553 | if ($dbh->errstr =~ m/duplicate/i) { | ||
| 554 | |||
| 555 | # duplicated a unique field | ||
| 556 | throw RWDE::DataDuplicateException({ info => 'Non-unique value detected in field: ' . $dbh->errstr }); | ||
| 557 | } | ||
| 558 | else { | ||
| 559 | throw RWDE::DevelException({ info => $dbh->errstr }); | ||
| 560 | } | ||
| 561 | } | ||
| 562 | |||
| 563 | $self->delete_cache(); | ||
| 564 | |||
| 565 | return (); | ||
| 566 | } | ||
| 567 | |||
| 568 | |||
| 569 | |||
| 570 | sub insert_all { | ||
| 571 | my ($self, $params) = @_; | ||
| 572 | |||
| 573 | my @fields = (); # list of fields to insert | ||
| 574 | my @values; # corresponding values | ||
| 575 | my $table = $self->{_table}; # the table for the object | ||
| 576 | |||
| 577 | #RWDE::DB::DbRegistry->db_check_transaction({ db => $self->{_db} }); | ||
| 578 | |||
| 579 | local ($") = ","; #" | ||
| 580 | |||
| 581 | foreach my $field (@{ $self->{_fieldnames} }) { | ||
| 582 | next unless exists($self->{_data}->{$field}); | ||
| 583 | |||
| 584 | my $value = $self->normalize($field, $self->{_data}->{$field}); | ||
| 585 | |||
| 586 | next unless defined($value); | ||
| 587 | |||
| 588 | push(@fields, $field); | ||
| 589 | push(@values, $value); | ||
| 590 | } | ||
| 591 | |||
| 592 | my $dbh = $self->get_dbh(); | ||
| 593 | |||
| 594 | my $sth; | ||
| 595 | if ((@fields > 0) && (@values > 0)) { | ||
| 596 | $sth = $dbh->prepare("INSERT INTO $table (@fields) VALUES (@values)"); | ||
| 597 | } | ||
| 598 | elsif ($self->{_id} && $self->{_index}) { | ||
| 599 | $sth = $dbh->prepare("INSERT INTO $table (" . $self->{_id} . ") VALUES (DEFAULT)"); | ||
| 600 | } | ||
| 601 | else { | ||
| 602 | throw RWDE::DevelException({ info => 'Attempt to create a record without any values (default or otherwise)' }); | ||
| 603 | } | ||
| 604 | |||
| 605 | # Check if the id is present in the object, if not we'll get it from the autoincrement | ||
| 606 | my $id = $self->{_data}->{ $self->{_id} }; | ||
| 607 | |||
| 608 | if ($sth and $sth->execute) { | ||
| 609 | if ($self->{_index} and not defined $id) { | ||
| 610 | |||
| 611 | # we are using sequences, pull the sequence value we just assigned | ||
| 612 | my $sth_local = $dbh->prepare("SELECT currval(?)"); | ||
| 613 | $sth_local->execute($self->{_index}); | ||
| 614 | my $newid = scalar $sth_local->fetchrow_array; # we expect single column, single row here | ||
| 615 | |||
| 616 | # load to populate the fields with default values in the db | ||
| 617 | my $created = $self->fetch_by_id({ $self->{_id} => $newid }); | ||
| 618 | |||
| 619 | $self->copy_record($created); | ||
| 620 | } | ||
| 621 | elsif (defined $id){ | ||
| 622 | my $created = $self->fetch_by_id({ $self->{_id} => $id }); | ||
| 623 | |||
| 624 | $self->copy_record($created); | ||
| 625 | } | ||
| 626 | else{ | ||
| 627 | throw RWDE::DevelException({ info => 'Id not defined or composite id not defined properly. Unable to fetch the newly inserted row from the db.' }); | ||
| 628 | } | ||
| 629 | } | ||
| 630 | else { | ||
| 631 | my $error = $dbh->errstr(); | ||
| 632 | |||
| 633 | # some error... | ||
| 634 | if ($error =~ m/duplicate/i) { | ||
| 635 | |||
| 636 | # duplicate ID | ||
| 637 | throw RWDE::DataDuplicateException({ info => 'Duplicate information requested for create' }); | ||
| 638 | } | ||
| 639 | else { | ||
| 640 | throw RWDE::DevelException({ info => $error }); | ||
| 641 | } | ||
| 642 | } | ||
| 643 | |||
| 644 | return $self->get_id(); | ||
| 645 | } | ||
| 646 | |||
| 647 | ## @method object get_data() | ||
| 648 | # (Enter get_data info here) | ||
| 649 | # @return (Enter explanation for return value here) | ||
| 650 | sub get_data { | ||
| 651 | my ($self, $params) = @_; | ||
| 652 | |||
| 653 | my $term_data = (); | ||
| 654 | |||
| 655 | foreach my $fieldname (keys %{ $self->{_fields} }) { | ||
| 656 | $$term_data{$fieldname} = $self->{_data}->{$fieldname}; | ||
| 657 | } | ||
| 658 | |||
| 659 | return $term_data; | ||
| 660 | } | ||
| 661 | |||
| 662 | ## @method object fill_new($row) | ||
| 663 | # (Enter fill_new info here) | ||
| 664 | # @param row (Enter explanation for param here) | ||
| 665 | # @return (Enter explanation for return value here) | ||
| 666 | sub fill_new { | ||
| 667 | my ($self, $params) = @_; | ||
| 668 | |||
| 669 | RWDE::RObject->check_params({ required => ['row'], supplied => $params }); | ||
| 670 | |||
| 671 | my $term = $self->new(); | ||
| 672 | |||
| 673 | #map the values in the row to fieldnames | ||
| 674 | my %values; | ||
| 675 | foreach my $field (@{ $term->{_fieldnames} }) { | ||
| 676 | $values{$field} = shift @{ $$params{row} }; | ||
| 677 | } | ||
| 678 | |||
| 679 | $term->fill(\%values); | ||
| 680 | |||
| 681 | return $term; | ||
| 682 | } | ||
| 683 | |||
| 684 | ## @method object hashify($string) | ||
| 685 | # This function converts a string representing a hash into a hash reference and returns it | ||
| 686 | #TODO This should probably be turned into some fancy fast regex | ||
| 687 | # @param string (Enter explanation for param here) | ||
| 688 | # @return (Enter explanation for return value here) | ||
| 689 | sub hashify { | ||
| 690 | my ($self, $params) = @_; | ||
| 691 | |||
| 692 | my $string = $$params{string}; | ||
| 693 | |||
| 694 | #drop out curly brackets if they are present | ||
| 695 | $string =~ s/{//g; | ||
| 696 | $string =~ s/}//g; | ||
| 697 | |||
| 698 | my $hashref = {}; | ||
| 699 | |||
| 700 | my @elements = split /,/, $string; | ||
| 701 | |||
| 702 | foreach my $element (@elements) { | ||
| 703 | |||
| 704 | #eliminate quotes | ||
| 705 | $element =~ s/"//g; | ||
| 706 | |||
| 707 | if ($element ne '') { | ||
| 708 | my @parts = split / => /, $element; | ||
| 709 | $$hashref{ $parts[0] } = $parts[1]; | ||
| 710 | } | ||
| 711 | } | ||
| 712 | |||
| 713 | return $hashref; | ||
| 714 | } | ||
| 715 | |||
| 716 | ## @method object dehashify($hash) | ||
| 717 | # Convert a hash with elements strictly as values into a string | ||
| 718 | # so that it can be readable in the db by people | ||
| 719 | # @param hash (Enter explanation for param here) | ||
| 720 | # @return (Enter explanation for return value here) | ||
| 721 | sub dehashify { | ||
| 722 | my ($self, $params) = @_; | ||
| 723 | |||
| 724 | my $hash = $$params{hash}; | ||
| 725 | |||
| 726 | #add curly brackets | ||
| 727 | |||
| 728 | my $string = '{'; | ||
| 729 | |||
| 730 | foreach my $key (keys %{$hash}) { | ||
| 731 | $string = $string . $key . ' => ' . $hash->{$key} . ','; | ||
| 732 | } | ||
| 733 | |||
| 734 | $string = $string . '}'; | ||
| 735 | |||
| 736 | return $string; | ||
| 737 | } | ||
| 738 | |||
| 739 | ## @method object get_status() | ||
| 740 | # (Enter get_status info here) | ||
| 741 | # @return (Enter explanation for return value here) | ||
| 742 | sub get_status { | ||
| 743 | my ($self, $params) = @_; | ||
| 744 | |||
| 745 | return throw RWDE::DevelException({ info => "get_status is an abstract function in Record - the inherting class should implement it" }); | ||
| 746 | } | ||
| 747 | |||
| 748 | ## @method object get_password() | ||
| 749 | # (Enter get_password info here) | ||
| 750 | # @return (Enter explanation for return value here) | ||
| 751 | sub get_password { | ||
| 752 | my ($self, $params) = @_; | ||
| 753 | |||
| 754 | return throw RWDE::DevelException({ info => "get_password is an abstract function in Record - the inherting class should implement it" }); | ||
| 755 | } | ||
| 756 | |||
| 757 | ## @method void is_missing() | ||
| 758 | # (Enter is_missing info here) | ||
| 759 | sub is_missing { | ||
| 760 | my ($self, $params) = @_; | ||
| 761 | |||
| 762 | my $missing = $self->get_missing(); | ||
| 763 | |||
| 764 | if (scalar keys %{$missing}) { | ||
| 765 | throw RWDE::DataMissingException({ info => $self->dehashify({ hash => $missing }) }); | ||
| 766 | } | ||
| 767 | |||
| 768 | return (); | ||
| 769 | } | ||
| 770 | |||
| 771 | ## @method object get_missing() | ||
| 772 | # (Enter get_missing info here) | ||
| 773 | # @return (Enter explanation for return value here) | ||
| 774 | sub get_missing { | ||
| 775 | my ($self, $params) = @_; | ||
| 776 | |||
| 777 | if (!$self->{Missing}) { | ||
| 778 | $self->{Missing} = {}; | ||
| 779 | } | ||
| 780 | |||
| 781 | return $self->{Missing}; | ||
| 782 | } | ||
| 783 | |||
| 784 | ## @method void add_missing($key, $value) | ||
| 785 | # (Enter add_missing info here) | ||
| 786 | # @param value (Enter explanation for param here) | ||
| 787 | # @param key (Enter explanation for param here) | ||
| 788 | sub add_missing { | ||
| 789 | my ($self, $params) = @_; | ||
| 790 | |||
| 791 | my $missing = $self->get_missing(); | ||
| 792 | |||
| 793 | my $key = $$params{key}; | ||
| 794 | |||
| 795 | $key =~ s/ //g; | ||
| 796 | |||
| 797 | if (defined $$params{value}) { | ||
| 798 | $$missing{$key} = $$params{value}; | ||
| 799 | } | ||
| 800 | else { | ||
| 801 | $$missing{$key} = $self->field_desc($key); | ||
| 802 | } | ||
| 803 | |||
| 804 | return (); | ||
| 805 | } | ||
| 806 | |||
| 807 | ## @method object get_ceil() | ||
| 808 | # (Enter get_ceil info here) | ||
| 809 | # @return (Enter explanation for return value here) | ||
| 810 | sub get_ceil { | ||
| 811 | my ($self, $number) = @_; | ||
| 812 | |||
| 813 | if ((not defined $number) or ($number == 0) or (int($number) == $number)) { | ||
| 814 | return $number; | ||
| 815 | } | ||
| 816 | else { | ||
| 817 | return int($number + 1); | ||
| 818 | } | ||
| 819 | } | ||
| 820 | |||
| 821 | ## @method object get_db() | ||
| 822 | # (Enter get_db info here) | ||
| 823 | # @return (Enter explanation for return value here) | ||
| 824 | sub get_db { | ||
| 825 | my ($self, $params) = @_; | ||
| 826 | |||
| 827 | return defined $self->get_static({ value => '_db' }) ? $self->get_static({ value => '_db' }) : 'default'; | ||
| 828 | } | ||
| 829 | |||
| 830 | ## @method object get_dbh() | ||
| 831 | # (Enter get_dbh info here) | ||
| 832 | # @return (Enter explanation for return value here) | ||
| 833 | sub get_dbh { | ||
| 834 | my ($self, $params) = @_; | ||
| 835 | |||
| 836 | return RWDE::DB::DbRegistry->get_dbh({ db => $self->get_db() }); | ||
| 837 | } | ||
| 838 | |||
| 839 | #Transaction handling | ||
| 840 | #------------------------------ | ||
| 841 | ## @method void transaction() | ||
| 842 | # This closure provides support for a group of database operations to be executed immediately at runtime as a singular transaction. | ||
| 843 | # The intent is to provide support for a group of database operations to be executed in an atomic fashion. In order to accomplish | ||
| 844 | # this for a code block utilize the transaction closure as follows: | ||
| 845 | # - | ||
| 846 | #transaction { | ||
| 847 | # database_operation_1(); | ||
| 848 | # database_operation_2(); | ||
| 849 | # }; | ||
| 850 | # - | ||
| 851 | # Before executing the enclosed code block the RWDE::DB::DbRegistry will signal the database backend to start a transaction | ||
| 852 | # on the first connection utilized within the code. The underlying logic only affords a transaction to operate across one | ||
| 853 | # connection - so in the event that the code block requires more than one connection an exception will be thrown. | ||
| 854 | # - | ||
| 855 | # Note that transaction closures may be nested within each-other however any nested transactions are essentially no-ops. | ||
| 856 | # This enables you to guarantee that any particular method will be within a transaction if you require. | ||
| 857 | # - | ||
| 858 | # In the event that you require transactions across multiple connections you should see "prepare_transaction" | ||
| 859 | # ¶m code the requested code to be executed within a transaction | ||
| 860 | sub transaction(&) { | ||
| 861 | my $code = shift; | ||
| 862 | |||
| 863 | if (!RWDE::DB::DbRegistry->transaction_signalled) { | ||
| 864 | try { | ||
| 865 | RWDE::DB::DbRegistry->signal_transaction(); | ||
| 866 | &$code(); | ||
| 867 | RWDE::DB::DbRegistry->commit_transaction(); | ||
| 868 | } | ||
| 869 | catch Error with { | ||
| 870 | my $ex = shift; | ||
| 871 | |||
| 872 | #RWDE::Logger->syslog_msg('info', "In transaction: " . $ex); | ||
| 873 | |||
| 874 | RWDE::DB::DbRegistry->abort_transaction(); | ||
| 875 | $ex->throw(); | ||
| 876 | }; | ||
| 877 | } | ||
| 878 | else { | ||
| 879 | RWDE::Logger->syslog_msg('info', "Already in transaction, executing code"); | ||
| 880 | &$code(); | ||
| 881 | } | ||
| 882 | |||
| 883 | return (); | ||
| 884 | } | ||
| 885 | |||
| 886 | ## @method object prepare_transaction() | ||
| 887 | # This closure provides support for grouping database operations that need to be performed atomically. | ||
| 888 | # The intent is to provide a means of guaranteeing that transactions across different database connections can | ||
| 889 | # all be committed atomically. The closure operates in a similar way to transaction() except that prepared transactions | ||
| 890 | # may not be nested within each-other (they may utilize nested transaction() closures however) | ||
| 891 | # - | ||
| 892 | # Typically utilization of this method would include a pair of calls like follows: | ||
| 893 | # - | ||
| 894 | # my $named = prepare_transaction { | ||
| 895 | # database_operation(); | ||
| 896 | # }; | ||
| 897 | # - | ||
| 898 | # Before executing the enclosed code, RWDE::DB::DbRegistry will signal the database backend to start a transaction on the first connection | ||
| 899 | # that is utilized within the code. A transaction can only operate on one connection at a time - otherwise an exception is thrown. | ||
| 900 | # In the event that you want to submit or abort the prepared transaction see "commit_transaction" & "abort_transaction" | ||
| 901 | # @param code the requested code to be executed within a transaction | ||
| 902 | # @return string representing the database handle of the prepared transaction | ||
| 903 | sub prepare_transaction(&) { | ||
| 904 | my $code = shift; | ||
| 905 | |||
| 906 | if (RWDE::DB::DbRegistry->transaction_signalled) { | ||
| 907 | throw RWDE::DevelException({ info => "Attempt to nest a named transaction within a previously established transaction." }); | ||
| 908 | } | ||
| 909 | |||
| 910 | my $transaction_name = undef; | ||
| 911 | |||
| 912 | try { | ||
| 913 | RWDE::DB::DbRegistry->signal_transaction(); | ||
| 914 | &$code(); | ||
| 915 | $transaction_name = RWDE::DB::DbRegistry->prepare_transaction(); | ||
| 916 | } | ||
| 917 | catch Error with { | ||
| 918 | my $ex = shift; | ||
| 919 | |||
| 920 | RWDE::Logger->syslog_msg('info', 'In prepare: ' . $ex); | ||
| 921 | |||
| 922 | RWDE::DB::DbRegistry->abort_transaction(); | ||
| 923 | |||
| 924 | $ex->throw(); | ||
| 925 | }; | ||
| 926 | |||
| 927 | return $transaction_name; | ||
| 928 | } | ||
| 929 | |||
| 930 | ## @method object create_record_temp($login_id) | ||
| 931 | # (Enter create_record_temp info here) | ||
| 932 | # @param login_id (Enter explanation for param here) | ||
| 933 | # @return (Enter explanation for return value here) | ||
| 934 | sub create_record_temp { | ||
| 935 | my ($self, $params) = @_; | ||
| 936 | |||
| 937 | my $term; | ||
| 938 | |||
| 939 | my $transaction_name = prepare_transaction { | ||
| 940 | $term = $self->create($params); | ||
| 941 | }; | ||
| 942 | |||
| 943 | $term->{_data}->{transaction_name} = $transaction_name; | ||
| 944 | |||
| 945 | return $term; | ||
| 946 | } | ||
| 947 | |||
| 948 | ## @method void commit_record_temp() | ||
| 949 | # This method commits the prepared transaction referenced by the transaction_name parameter. | ||
| 950 | sub commit_record_temp { | ||
| 951 | my ($self, $params) = @_; | ||
| 952 | |||
| 953 | my $transaction_name = defined $$params{transaction_name} ? $$params{transaction_name} : $self->{_data}->{transaction_name}; | ||
| 954 | |||
| 955 | if (not defined($transaction_name)) { | ||
| 956 | throw RWDE::DevelException({ info => $self . 'This record is not involved in a temporary transaction.' }); | ||
| 957 | } | ||
| 958 | |||
| 959 | RWDE::DB::DbRegistry->commit_prepared_transaction({ transaction_name => $transaction_name, db => $self->get_db() }); | ||
| 960 | |||
| 961 | delete $self->{_data}->{transaction_name} if ref $self; | ||
| 962 | |||
| 963 | return 1; | ||
| 964 | } | ||
| 965 | |||
| 966 | ## @method void abort_record_temp() | ||
| 967 | # This method aborts the prepared transaction represented by the transaction_name parameter. | ||
| 968 | sub abort_record_temp { | ||
| 969 | my ($self, $params) = @_; | ||
| 970 | |||
| 971 | my $transaction_name = defined $$params{transaction_name} ? $$params{transaction_name} : $self->{_data}->{transaction_name}; | ||
| 972 | |||
| 973 | if (not defined($transaction_name)) { | ||
| 974 | throw RWDE::DevelException({ info => $self . 'This record is not involved in a temporary transaction.' }); | ||
| 975 | } | ||
| 976 | |||
| 977 | RWDE::DB::DbRegistry->abort_prepared_transaction({ transaction_name => $transaction_name }); | ||
| 978 | |||
| 979 | delete $self->{_data}->{transaction_name} if ref $self; | ||
| 980 | |||
| 981 | return (); | ||
| 982 | } | ||
| 983 | |||
| 984 | 1; | ||
| 985 |