RWDE/DB/DbRegistry.pm untested

filter: Statementstmt 0.0% 0 / 231 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 51 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 433 CC 31 SCAR 23.9
CC
31
Cov
0%
commit_prepared_transaction
30.0
abort_prepared_transaction
30.0
get_dbh
20.0
CRAP 10.9
1 ## @file
2 # (Enter your file info here)
3 #
4 # $Id: DbRegistry.pm 496 2008-08-20 14:18:09Z damjan $
5  
6 # Database connection and handling registry
7  
8 ## @class RWDE::DB::DbRegistry
9 # Database registry which provides the underlying access API for RWDE objects. Once instantiated and initialized the registry
10 # provides a one stop shop for managing database connections (open/close), connection setting modifications and
11 # transaction management (begin/prepare/commit/abort)
12 package RWDE::DB::DbRegistry;
13  
14 use strict;
15 use warnings;
16  
17 use DBI;
18 use Error qw(:try);
19  
20 use RWDE::Configuration;
21 use RWDE::Exceptions;
22 use RWDE::RObject;
23  
24 use base qw(RWDE::Singleton);
25  
26 our (%dbh, %prepared_transactions, $transaction_connection, $transaction_sequence, $DB_CONFIG, $DB_CONNECTIONS, $impose_transaction);
27 our ($unique_instance);
28  
29 use vars qw($VERSION);
30 $VERSION = sprintf "%d", q$Revision: 561 $ =~ /(\d+)/;
31  
32 ## @method object get_instance()
33 # Retrieve the registry instance
34 # @return retrieved registry instance
35 sub get_instance {
36 my ($self, $params) = @_;
37  
38 if (ref $unique_instance ne $self) {
39 $unique_instance = $self->new;
40 }
41  
42 return $unique_instance;
43 }
44  
45 ## @method void initialize()
46 # Read the configuration file for DB names and locations
47 # these data are used for opening connections
48 sub initialize {
49 my ($self, $params) = @_;
50  
51 # initialize the params for connecting to the db
52 $DB_CONFIG = RWDE::Configuration->DB;
53  
54 # and mapping between the db names and connections
55 $DB_CONNECTIONS = RWDE::Configuration->DB_CONNECTIONS;
56  
57 $transaction_sequence = 0;
58  
59 $impose_transaction = undef;
60
61 return ();
62 }
63  
64 ## @method object get_dbh()
65 # Retrieve the database handle for a specific database name. In the event that a transaction was
66 # previously signalled the transaction will begin here
67 # &param db Database name
68 # @return The database handle for a specific database
69 sub get_dbh {
70 my ($self, $params) = @_;
71  
72 my $connection_name = $self->_get_connection_name($params);
73  
74 unless (defined $dbh{$connection_name} and $dbh{$connection_name}->ping()) {
75 $self->_connect_db({ connection => $connection_name });
76 }
77  
78 #we have received an earlier signal to start a transaction and it hasn't completed yet
79 if (transaction_signalled()) {
80  
81 #if there is no transaction defined yet
82 if (!defined($transaction_connection)) {
83  
84 $self->_begin_transaction($params);
85 }
86 }
87  
88 return $dbh{$connection_name};
89 }
90  
91 ## @method void add_db_settings($db_settings)
92 # Pass a setting to the database. This needs to be set before the connection is established
93 # @param db_settings Specific setting to be applied to the database at connect time
94 sub add_db_settings {
95 my ($self, $params) = @_;
96  
97 my $db_setting_param = $$params{db_settings};
98  
99 if (not defined($db_setting_param) || ref($db_setting_param) ne "ARRAY") {
100 throw RWDE::DevelException({ info => "DB setting supplied undefined or not an array" });
101 }
102  
103 my $connection_name = RWDE::DB::DbRegistry->_get_connection_name($params);
104
105 push (@{$$DB_CONFIG{$connection_name}{db_settings}}, @$db_setting_param);
106  
107 return ();
108 }
109  
110 ## @method object get_db_notifications($sleeptime)
111 # Retrieve notifications (pg_notifies) from the database
112 # &param db The database name that you want notifications for
113 # @param sleeptime Length of time to block while waiting for notifications
114 # @return Array reference of notifications the db raised
115 sub get_db_notifications {
116 my ($self, $params) = @_;
117  
118 my $dbh = $self->get_dbh($params);
119  
120 my @required = qw( sleeptime );
121 RWDE::RObject->check_params({ required => \@required, supplied => $params });
122  
123 use IO::Select;
124  
125 my @notifications;
126 my $dbpid = $dbh->{pg_pid};
127 my $dbsock = $dbh->{pg_socket};
128  
129 my $select = new IO::Select($dbsock)
130 or throw RWDE::DevelException({ info => "Failed to create selector" });
131  
132 if (my @ready = $select->can_read($$params{sleeptime})) {
133 while (my $notification = $dbh->func('pg_notifies')) {
134 push(@notifications, $notification); # "got NOTIFY $n->[0] from $n->[1]";
135 }
136 }
137  
138 return \@notifications;
139 }
140  
141 ## @method void destroy_dbh()
142 # Tear down and clear (from the registry) the database associated with the database parameter it was invoked with
143 # param db The database name you want to destroy the handle for
144 sub destroy_dbh {
145 my ($self, $params) = @_;
146  
147 my $connection_name = $self->_get_connection_name($params);
148  
149 $dbh{$connection_name}->{InactiveDestroy} = 1;
150  
151 $self->closeDB($params);
152  
153 return;
154 }
155  
156 ## @method void closeDB()
157 # Close a specific database handle and the delete referenced db from the registry
158 # -
159 # Note: Don't do explicit disconnect if we're a child process clearing out the old handle just prior to re-opening it.
160 # In this case, we set InactiveDestroy to keep DBI from doing the implicit disconnect when the handle goes away.
161 sub closeDB {
162 my ($self, $params) = @_;
163  
164 my $connection_name = $self->_get_connection_name($params);
165  
166 if ($dbh{$connection_name} and !$dbh{$connection_name}->{InactiveDestroy}) {
167 $dbh{$connection_name}->disconnect;
168 }
169  
170 delete $dbh{$connection_name};
171  
172 return ();
173 }
174  
175 ## @method void close_all()
176 # Close all database connections we are currently maintaining
177 sub close_all {
178 my ($self, $params) = @_;
179  
180 foreach my $connection_name (keys %$DB_CONNECTIONS) {
181 if ($dbh{$connection_name} and !$dbh{$connection_name}->{InactiveDestroy}) {
182 $dbh{$connection_name}->disconnect;
183 }
184  
185 delete $dbh{$connection_name};
186 }
187  
188 return ();
189 }
190  
191 ## @method void close_all()
192 # Release the handles w/o explicitly disconnecting: i.e. on fork
193 sub destroy_all {
194 my ($self, $params) = @_;
195  
196 foreach my $db_name (keys %$DB_CONNECTIONS) {
197 $self->destroy_dbh({ db => $db_name});
198 }
199  
200 return ();
201 }
202  
203 #================================================================
204 #everything below is transaction related - global can call these
205 #================================================================
206  
207 ## @method void signal_transaction()
208 # Signal the database backend to begin a transaction before the next database operation takes place
209 sub signal_transaction {
210 my ($self, $params) = @_;
211  
212 #if this flag is already set and we ended up here something is wrong
213 if (!transaction_signalled()) {
214 $impose_transaction = 1;
215 }
216 else {
217 warn 'Received a signal for impose transaction, but transaction already in progress';
218 }
219  
220 return ();
221 }
222  
223 ## @method object transaction_signalled()
224 # Determine if a transaction has been signalled in the backend
225 # @return true if a transaction is signalled, false otherwise
226 sub transaction_signalled {
227 my ($self, $params) = @_;
228  
229 return (defined($impose_transaction));
230 }
231  
232 ## @method void commit_transaction()
233 # Commit the running transaction within the database. Will invoke an exception if a transaction
234 # is not currently defined or if the transaction does not execute properly. After committing a
235 # transaction the related state variables are cleared.
236 sub commit_transaction {
237 my ($self, $params) = @_;
238  
239 if (!(defined $transaction_connection and $dbh{$transaction_connection} and $dbh{$transaction_connection}->commit())) {
240 warn "Commit transaction called with no outstanding transaction -> probably aborted before";
241 }
242  
243 $transaction_connection = undef;
244  
245 $impose_transaction = undef;
246  
247 return ();
248 }
249  
250 ## @method void abort_transaction()
251 # Abort the running transaction within the database. If no transaction is running then this operation
252 # acts as a no-op
253 sub abort_transaction {
254 my ($self, $params) = @_;
255  
256 if (defined($transaction_connection)) {
257 $dbh{$transaction_connection}->rollback();
258 $transaction_connection = undef;
259 }
260  
261 $impose_transaction = undef;
262  
263 return ();
264 }
265  
266 ## @method object prepare_transaction()
267 # Prepare and save the currently running transaction within the database. An exception will be thrown if
268 # no transaction is running or there is a problem preparing the transaction. Once the transaction is prepared a
269 # string handle/reference is returned back to the caller to allow for processing of the transaction at a later time
270 # @return string handle/reference to the prepared transaction
271 sub prepare_transaction {
272 my ($self, $params) = @_;
273  
274 $self->check_transaction();
275  
276 my $transaction_name = $self->_get_transaction_name($params);
277  
278 #unfortunately DBI does not have a call to support 2pc yet
279 my $sth = $dbh{$transaction_connection}->prepare("PREPARE TRANSACTION ?");
280  
281 if (!($sth && $sth->execute($transaction_name))) {
282 throw RWDE::DevelException({ info => $dbh{$transaction_connection}->errstr() });
283 }
284  
285 #store the transaction connection name associated with this prepared transaction
286 $prepared_transactions{$transaction_name} = $transaction_connection;
287  
288 #clear out transaction connection
289 $transaction_connection = undef;
290  
291 $impose_transaction = undef;
292  
293 return $transaction_name;
294 }
295  
296 ## @method void commit_prepared_transaction($transaction_name)
297 # Commit a previously prepared transaction within the database. An exception will be thrown if
298 # the transaction doesn't exist or if there is a problem committing the transaction.
299 # @param transaction_name Handle/reference to a previously prepared transaction
300 sub commit_prepared_transaction {
301 my ($self, $params) = @_;
302  
303 #if the transaction is not defined then something is wrong
304 if (!defined($$params{transaction_name})) {
305 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
306 throw RWDE::DevelException({ info => "Attempt to commit an unspecified prepared transaction without a name: $package on $line" });
307 }
308  
309 my $transaction_name = $$params{transaction_name};
310 my $connection = $prepared_transactions{$transaction_name};
311  
312 if (not defined $connection){
313 $connection = $self->_get_connection_name($params);
314 }
315  
316 if (defined($connection) && defined($transaction_name)) {
317  
318 #unfortunately DBI does not have a call to support 2pc yet
319 if (!defined($dbh{$connection}->do("COMMIT PREPARED " . $dbh{$connection}->quote($transaction_name)))) {
320 throw RWDE::DevelException({ info => $dbh{$connection}->errstr() });
321 }
322 }
323  
324 #clear out transaction
325 $prepared_transactions{$transaction_name} = undef;
326  
327 return ();
328 }
329  
330 ## @method void abort_prepared_transaction($transaction_name)
331 # Abort a previously prepared transaction within the database. An exception will be thrown if
332 # the transaction doesn't exist or if there is a problem committing the transaction.
333 # @param transaction_name Handle/reference to a previously prepared transaction
334 sub abort_prepared_transaction {
335 my ($self, $params) = @_;
336  
337 #if the transaction is not defined then something is wrong
338 if (!defined($$params{transaction_name})) {
339 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
340 throw RWDE::DevelException({ info => "Attempt to commit an unspecified prepared transaction without a name: $package on $line" });
341 }
342  
343 my $transaction_name = $$params{transaction_name};
344 my $connection = $prepared_transactions{$transaction_name};
345  
346 if (not defined $connection){
347 $connection = $self->_get_connection_name($params);
348 }
349  
350 if (defined($connection) && defined($transaction_name)) {
351  
352 #unfortunately DBI does not have a call to support 2pc yet
353 if (!defined($dbh{$connection}->do("ROLLBACK PREPARED " . $dbh{$connection}->quote($transaction_name)))) {
354 throw RWDE::DevelException({ info => $dbh{$connection}->errstr() });
355 }
356 }
357 else {
358 warn 'Either connection or transaction_name not defined';
359 }
360  
361 #clear out transaction
362 $prepared_transactions{$transaction_name} = undef;
363  
364 return ();
365 }
366  
367 ## @method void check_transaction()
368 # Test to see if we have a transaction and that everything is consistent. Throw a devel exception if no
369 # transaction is running.
370 # -
371 # This is used to ensure that we are in ANY transaction - regardless of connection. Maybe this is bad
372 sub check_transaction {
373 my ($self, $params) = @_;
374  
375 if (!defined($transaction_connection) || !defined($dbh{$transaction_connection}) || !transaction_signalled()) {
376 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
377 throw RWDE::DevelException({ info => "Attempt to get transaction name for nonexistent transaction: $package on $line" });
378 }
379  
380 return ();
381 }
382  
383 ## @method object has_transaction()
384 # Determine if the argument db connection has a transaction
385 # &param db name of the database supposedly in a transaction
386 # @return true if the database is in a transaction, false otherwise
387 sub has_transaction {
388 my ($self, $params) = @_;
389  
390 #check to see if a transaction is signalled and if the argument connection is associated with such a signalled transaction
391 return (transaction_signalled() && defined($transaction_connection) && ($transaction_connection eq $self->_get_connection_name($params)));
392 }
393  
394 ## @method void db_check_transaction()
395 # Determine if the current transaction is associated with the specified db param - otherwise devel exception
396 sub db_check_transaction {
397 my ($self, $params) = @_;
398  
399 unless (has_transaction($params)) {
400 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
401 throw RWDE::DevelException({ info => "$package on $line requires exclusive access to the affecting rows. Add transaction around the function call." });
402 }
403  
404 return ();
405 }
406  
407 ## @method void cleanup()
408 # Cleanup running transactions on all connections by aborting them
409 sub cleanup {
410 my ($self, $params) = @_;
411  
412 foreach my $db (keys %dbh) {
413 if (defined($transaction_connection)) {
414 $self->abort_transaction();
415 }
416 $dbh{$db}->do("RESET ALL"); # unset any special variables
417 }
418  
419 return ();
420 }
421  
422 #================================================================
423 #everything below is private - do not call externally
424 #================================================================
425  
426 ## @method protected object _get_connection_name($db)
427 # Private call to determine the connection name for a database name argument
428 # @param db Database name you are seeking the connection name for
429 # @return the connection name associated with the database name argument
430 sub _get_connection_name {
431 my ($self, $params) = @_;
432  
433 my $label = $$params{db};
434  
435 if (not defined $label) {
436 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(1);
437 throw RWDE::DevelException({ info => "DB not specified: $package on $line" });
438 }
439  
440 my $connection_name = $$DB_CONNECTIONS{$label};
441  
442 if (!defined($connection_name)) {
443 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(2);
444 throw RWDE::DevelException({ info => "No connection specified for given db:$label: from $package on $line" });
445 }
446  
447 return $connection_name;
448 }
449  
450 sub get_host {
451 my ($self, $params) = @_;
452  
453 my $connection_name = $self->_get_connection_name({ db => $$params{db}});
454  
455 my $DB = $$DB_CONFIG{$connection_name};
456  
457 return $$DB{db_host};
458 }
459  
460  
461 ## @method protected void _connect_db($connection)
462 # Create a database connection for the connection_name argument given. If there are any problems an exception will be thrown.
463 # Upon success the database connection handle is added to the registry and may be retrieved using "get_dbh".
464 # @param connection The connection_name you are trying to create a connection for
465 sub _connect_db {
466 my ($self, $params) = @_;
467  
468 my $connection_name = $$params{connection};
469  
470 my $DB = $$DB_CONFIG{$connection_name};
471 my $port = $$DB{db_port} ? $$DB{db_port} : 5432;
472 my $datasource = 'dbi:' . $$DB{db_type} . ':dbname=' . $$DB{db_name} . ';host=' . $$DB{db_host} . ';port=' . $port;
473  
474 if (RWDE::Configuration->Debug) {
475  
476 #disable preparing of queries so we can see them
477 $dbh{$connection_name} = DBI->connect($datasource, $$DB{db_user}, $$DB{db_pass}, { PrintError => 0, pg_server_prepare => 0 })
478 or throw RWDE::DevelException({ info => "dbi connect failure: " . $DBI::errstr });
479 }
480 else {
481 #tmp fix, put prepare to 0, looks like pg_bouncer is not liking it a lot
482 $dbh{$connection_name} = DBI->connect($datasource, $$DB{db_user}, $$DB{db_pass}, { PrintError => 0, pg_server_prepare => 0 })
483 or throw RWDE::DevelException({ info => "dbi connect failure: " . $DBI::errstr });
484 }
485  
486 # and listen for events to wake us up
487 foreach my $db_setting (@{$$DB{db_settings}}) {
488 $dbh{$connection_name}->do($db_setting)
489 or throw RWDE::DevelException({ info => "failed to set: $db_setting for $connection_name" });
490 }
491  
492 return ();
493 }
494  
495 ## @method protected object _get_transaction_name()
496 # This method provides a uniq naming scheme for naming prepared transactions.
497 # @return Unique name that is suitable to be used for preparing a transaction
498 sub _get_transaction_name {
499 my ($self, $params) = @_;
500  
501 $self->check_transaction();
502  
503 my $dbh = $dbh{$transaction_connection};
504  
505 my $transaction_name = $$ . "|" . $dbh->{pg_pid} . "|" . $transaction_sequence;
506  
507 $transaction_sequence++;
508  
509 return $transaction_name;
510 }
511  
512 ## @method protected void _begin_transaction()
513 # Private method to begin a transaction. The only appropriate place to use it within this registry construct
514 # is immediately after a transaction signal has been raised - but before any other database queries are executed.
515 sub _begin_transaction {
516 my ($self, $params) = @_;
517  
518 #if there are ANY other transactions then something is wrong
519 if (defined($transaction_connection)) {
520 throw RWDE::DevelException({ info => "Attempt to start multiple transactions" });
521 }
522  
523 my $connection_name = $self->_get_connection_name($params);
524  
525 $transaction_connection = $connection_name;
526  
527 if (!($dbh{$connection_name})) {
528 throw RWDE::DevelException({ info => 'Error while attempting to _begin_transaction -- no connection_name' });
529 }
530  
531 if (!($dbh{$connection_name}->begin_work())) {
532 throw RWDE::DevelException({ info => 'Error while attempting to _begin_transaction failed: ' . $dbh{$connection_name}->errstr() });
533 }
534  
535 return ();
536 }
537  
538 1;