emdbi.pm.in 19.6 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2014 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27
#
package emdbi;
use strict;
use File::Basename;
use English;
28
use Carp;
29
use Exporter;
30
use Data::Dumper;
31
use vars qw(@ISA @EXPORT);
32
@ISA = "Exporter";
33 34 35 36 37

# Configure variables
my $TB		= "@prefix@";
my $SCRIPTNAME  = "Unknown";
my $TBOPS       = "@TBOPSEMAIL@";
38
my $USEDBI	= @TBUSEDBI@;
39 40 41 42 43 44 45 46 47

# Untainted scriptname for below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
}
else {
    $SCRIPTNAME = "Tainted";
}

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#############################################################################
#
# We are going to wrap the DB handle in a wrapper object so that we
# can attach the current process ID to it. This is needed so that the
# child process after a fork() 1) set's InactiveDestroy to avoid
# sending a disconnect message since it will also close the parent's
# database handle 2) reconnects since two separate processes should not
# share the same handle.  (1) is handled via overridding the database
# handle DESTROY method, (2) is handled in the DBQueryN function.
#
package emdbi_wrapper::Mysql;
use vars '@ISA';
@ISA = ('Mysql');

sub Wrap($$$)
63
{
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    my ($class, $dbname, $dbuser) = @_;

    require Mysql;
    $Mysql::QUIET = 1;
    my $dbh = Mysql->connect("localhost", $dbname, $dbuser, "none");
    return undef
	if (!defined($dbh));

    $dbh->{'dbh'}->{'PrintError'} = 0;

    my $self = {};
    bless($self, $class);

    $self->{'PID'}    = $$;
    $self->{'DBH'}    = $dbh;
    $self->{'DBNAME'} = $dbname;
    return $self;
}
sub pid($)	{ return $_[0]->{'PID'}; };
sub dbh($)	{ return $_[0]->{'DBH'}; };
sub dbname($)	{ return $_[0]->{'DBNAME'}; };
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
#
# Check for existence of DB
#
sub DBExists($$)
{
    my ($class, $dbname) = @_;
    
    require Mysql;
    $Mysql::QUIET = 1;
    my $dbh = Mysql->connect("localhost");
    return undef
	if (!defined($dbh));

    my @dbs = $dbh->listdbs();
    return 1
	if (grep {$_ eq $dbname} @dbs);
    return 0;
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118
#
# Need to wrap the return value. See below.
#
sub query($$)
{
    my ($self, $query) = @_;
    my $result = $self->dbh->query($query);
    return undef
	if (!defined($result));

    # See below.
    bless($result, "emdbi_wrapper::Mysql::Statement");
    return $result;
}
119 120 121 122 123 124 125

sub DESTROY
{
    my ($self) = @_;
    # XXX Seems like a problem if parent gets here first.
    if ($self->pid() != $$) {
	$self->dbh()->setInactiveDestroy(1);
126
    }
127 128 129 130
    $self->dbh()->SUPER::DESTROY()
	if $self->dbh()->can("SUPER::DESTROY");
}

131 132 133 134 135 136 137 138 139 140
#############################################################################
# Trivial wrapper for the Mysql statement so that we can add a method.
#
package emdbi_wrapper::Mysql::Statement;
use vars '@ISA';
@ISA = ('Mysql::Statement');

# Natively supported, so nothing to worry about.
sub WrapForSeek($)	{ return $_[0]; }

141 142 143 144 145 146 147 148
#############################################################################
#
# We are making the transition to DBI so we can stop using the ancient
# and unmaintained Mysql module.
#
package emdbi_wrapper::DBI;
use vars '@ISA';
@ISA = ('DBI::db');
149
use Data::Dumper;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

sub Wrap($$$)
{
    my ($class, $dbname, $dbuser) = @_;

    require DBI;
    my $dbh = DBI->connect("DBI:mysql:database=$dbname;host=localhost",
			   $dbuser, "none",
			   {'PrintError' => 0});
    return undef
	if (!defined($dbh));

    my $self = {};
    bless($self, $class);

    $self->{'PID'}    = $$;
    $self->{'DBH'}    = $dbh;
    $self->{'DBNAME'} = $dbname;
    return $self;
}
sub pid($)	{ return $_[0]->{'PID'}; };
sub dbh($)	{ return $_[0]->{'DBH'}; };
sub dbname($)	{ return $_[0]->{'DBNAME'}; };

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
#
# Check for existence of DB
#
sub DBExists($$)
{
    my ($class, $dbname) = @_;
    
    require DBI;

    my @dbs = DBI->data_sources("mysql");
    return 1
	if (grep {$_ eq "DBI:mysql:$dbname"} @dbs);
    return 0;
}

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
#
# Wrap query for proper DBI syntax.
#
sub query($$)
{
    my ($self, $query) = @_;

    my $dbh = $self->dbh();;
    my $sth = $dbh->prepare($query);
    return undef
	if (!$sth);

    my $query_result = $sth->execute();
    return undef
	if (!$query_result);

    # See below; we add a couple of extra routines.
    bless($sth, "emdbi_wrapper::DBI::st");
    return $sth;
}

sub DESTROY
{
    my ($self) = @_;
    # XXX Seems like a problem if parent gets here first.
    if ($self->pid() != $$) {
	$self->dbh()->{'InactiveDestroy'} = 1;
216
    }
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    $self->dbh()->SUPER::DESTROY()
	if $self->dbh()->can("SUPER::DESTROY");
}

#############################################################################
# Trivial wrapper for the DBI statement class to avoid a zillion silly
# changes to the rest of the code. These were defined in the Mysql
# wrapper we used to use. Pretty simple stuff, no big deal.
#
package emdbi_wrapper::DBI::st;
use vars '@ISA';
@ISA = ('DBI::st');

sub numrows($)		{ return $_[0]->rows(); };
sub num_rows($)		{ return $_[0]->rows(); };
sub affectedrows($)	{ return $_[0]->rows(); };
sub insertid($)		{ return $_[0]->{'mysql_insertid'}; };
234 235 236 237 238 239 240 241 242 243 244 245
sub fetchrow($)
{
    my ($self) = @_;
    my @row    = $self->fetchrow_array();
    return (@row ? (wantarray ? @row : $row[0]) : ());
}
sub fetchhash($)
{
    my ($self) = @_;
    my $ref    = $self->fetchrow_hashref();
    return ($ref ? %$ref : ());
}
246 247 248 249 250
sub as_string($)
{
    my ($self) = @_;
    $self->dump_results();
}
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

# Not supported so generate an error.
sub dataseek($$)
{
    DBWarn("Attempt to 'seek' not supported. Better fix it!");
}

# This is how we do it. See below.
sub WrapForSeek($)	{ return emdbi_wrapper::DBI::WrapForSeek->Wrap($_[0]); }

#############################################################################
# Another wrapper. DBI does not implement "seek" or "rewind". The only way
# to do this is suck all the data out and save it. We do not want to do this
# for every query though, so anyplace we want to seek around, wrap things
# up with this, and then use it like a normal query result. 
#
package emdbi_wrapper::DBI::WrapForSeek;

use Data::Dumper;

sub Wrap($$)
{
    my ($class, $sth) = @_;
    my @data  = ();
    my @names = ();

    #
    # This tells us the original select column ordering.
    #
    my $names = $sth->{'NAME'};
    my $numFields = $sth->{'NUM_OF_FIELDS'};
    for (my $i = 0;  $i < $numFields;  $i++) {
	push(@names, $$names[$i]);
    }

    #
    # Grab all the rows. 90 percent of queries request rows as
    # arrays, so lets do that. We can construct a hash using the
    # column names we grabbed above.
    #
    while (my $rowref = $sth->fetchrow_arrayref()) {
	#
	# This looks weird and pointless, but there is some funky
	# memory stuff going in underneath; if we do not make a copy
	# explicitly, each successive row overwrites the previous row.
	# Not very perl like.
	#
	my @row = @$rowref;
	
	push(@data, \@row);
    }

    my $self = {};
    $self->{'STH'}       = $sth;
    $self->{'ROWS'}      = $sth->rows();
    $self->{'COLNAMES'}  = \@names;
    $self->{'COLCOUNT'}  = scalar(@names);
    $self->{'DATA'}      = \@data;
    $self->{'IDX'}       = 0;

    bless($self, $class);
    return $self;
}
sub sth($)		{ return $_[0]->{'STH'}; };
sub rows($)		{ return $_[0]->{'ROWS'}; };
sub idx($)		{ return $_[0]->{'IDX'}; };
sub incridx($)		{ return $_[0]->{'IDX'}++; };
sub data($)		{ return $_[0]->{'DATA'}; };
sub colnames($)		{ return $_[0]->{'COLNAMES'}; };
sub colcount($)		{ return $_[0]->{'COLCOUNT'}; };
sub numrows($)		{ return $_[0]->{'ROWS'}; };
sub num_rows($)		{ return $_[0]->{'ROWS'}; };
sub affectedrows($)	{ return $_[0]->{'ROWS'}; };
sub insertid($)		{ return $_[0]->sth()->{'mysql_insertid'}; };
sub dataseek($$)	{ $_[0]->{'IDX'} = $_[1]; };

sub fetchrow_arrayref($)
{
    my ($self) = @_;
    my $data   = $self->data();
    my $idx    = $self->idx();

    return undef
	if ($idx >= $self->rows());

    $self->incridx();
    return $data->[$idx];
}

sub fetchrow_array($)
{
    my ($self) = @_;
    my $ref    = $self->fetchrow_arrayref();

    return ()
	if (!defined($ref));

    return @{ $ref };
}

sub fetchrow_hashref($)
{
    my ($self) = @_;
    my $ref    = $self->fetchrow_arrayref();

    return undef
	if (!defined($ref));

    #
    # Construct a hash using the column names
    #
    my %hash  = ();
    my $count = $self->colcount();
    for (my $i = 0; $i < $count; $i++) {
	$hash{$self->colnames()->[$i]} = $ref->[$i];
    }
    return \%hash;
}

370 371 372 373 374 375 376 377 378 379 380
sub fetchrow($)
{
    my ($self) = @_;
    my @row    = $self->fetchrow_array();
    return (@row ? (wantarray ? @row : $row[0]) : ());
}
sub fetchhash($)
{
    my ($self) = @_;
    my $ref    = $self->fetchrow_hashref();
    return ($ref ? %$ref : ());
381 382
}

383 384 385 386 387
#############################################################################
# Back to the main package.
#
package emdbi;

388 389 390 391
#
# Set up for querying the database. Note that fork causes a reconnect
# to the DB in the child.
#
392
my @DB = ();
393

394
use vars qw($DBQUERY_MAXTRIES $DBCONN_MAXTRIES $DBErrorString $DBCONN_USEDBI
395
	    $DBCONN_EXITONERR $DBQUERY_RECONNECT $DBQUERY_DEBUG);
396 397
$DBQUERY_MAXTRIES  = 1;
$DBQUERY_RECONNECT = 1;
398
$DBCONN_USEDBI     = $USEDBI;
399 400 401
$DBCONN_MAXTRIES   = 5;
$DBCONN_EXITONERR  = 1;
$DBQUERY_DEBUG     = 0;
402 403
$DBErrorString     = "";
@EXPORT            = qw($DBQUERY_MAXTRIES $DBQUERY_RECONNECT $DBErrorString
404 405
			$DBCONN_EXITONERR $DBCONN_MAXTRIES $DBQUERY_DEBUG);

406 407
my $queryCount = 0;

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#
# Does DB exist yet.
#
sub DBExists($)
{
    my ($dbname) = @_;

    if ($DBCONN_USEDBI) {
	return emdbi_wrapper::DBI->DBExists($dbname);
    }
    else {
	return emdbi_wrapper::Mysql->DBExists($dbname);
    }
}

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
sub TBDBConnect($$)
{
    my ($dbnum, $dbname) = @_;
    my $maxtries = $DBCONN_MAXTRIES;

    if (!defined($dbname)) {
	    print STDERR "What DBNAME should I use?\n";
	    return -1
		if (! $DBCONN_EXITONERR);
	    exit(-1);
    }
    
    #
    # Do nothing if this DB handle is already connected to DB.
    #
    if (defined($DB[$dbnum])) {
439 440
	my $dbhw = $DB[$dbnum];
	
441
	return 0
442
	    if ($dbhw->dbname() eq $dbname);
443 444
	
	print STDERR "DBnum $dbnum already connected to another DB: ".
445
	    $dbhw->dbname() . "!\n";
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	return -1
	    if (! $DBCONN_EXITONERR);
	exit(-1);
    }

    #
    # Construct a 'username' from the name of this script and the user who
    # ran it. This is for accounting purposes.
    #
    my $name = getpwuid($UID);
    if (!$name) {
	$name = "uid$UID";
    }
    my $dbuser = "$SCRIPTNAME:$name:$PID";

    while ($maxtries) {
	if ($DBQUERY_DEBUG) {
463
	    print STDERR "DBConnect:$dbnum $dbname $$\n";
464
	}
465 466 467 468 469 470 471 472 473 474

	my $dbhw;
	if ($DBCONN_USEDBI) {
	    $dbhw = emdbi_wrapper::DBI->Wrap($dbname, $dbuser);
	}
	else {
	    $dbhw = emdbi_wrapper::Mysql->Wrap($dbname, $dbuser);
	}
	if (defined($dbhw)) {
	    $DB[$dbnum] = $dbhw;
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
	    last;
	}
	$maxtries--;
	if ($maxtries) {
	    print STDERR "Cannot connect to DB; trying again in 5 seconds!\n";
	    sleep(5);
	}
    }
    if (!defined($DB[$dbnum])) {
	print STDERR
	    "Cannot connect to DB after $DBQUERY_MAXTRIES attempts!\n";
	return -1
	    if (! $DBCONN_EXITONERR);
	exit(-1);
    }
    return 0;
}

# New version.
sub TBDBReconnect($)
{
    my ($retry) = @_;
    my ($exitonerr,$maxtries);
    
    if ($retry) {
	$exitonerr = $DBCONN_EXITONERR;
	$DBCONN_EXITONERR = 0;
	
	# And we want to keep trying for a long time!
	$maxtries = $DBCONN_MAXTRIES;
	$DBCONN_MAXTRIES  = 10000;
    }

    for (my $i = 0; $i < @DB; $i++) {
	next
	    if (!defined($DB[$i]));
511 512

	my $dbname = $DB[$i]->dbname();
513 514 515
	
	undef($DB[$i]);
	return -1
516
	    if (TBDBConnect($i, $dbname) != 0);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    }

    if ($retry) {
	$DBCONN_EXITONERR = $exitonerr;
	$DBCONN_MAXTRIES  = $maxtries;
    }
    #print "Reconnected to DB in process $PID\n";
   
    return 0;
}

# To avoid keeping a mysql connection around.
sub TBDBDisconnect()
{
    for (my $i = 0; $i < @DB; $i++) {
	undef($DB[$i]);
    }
}

# Create a new DB handle and return the handle number
sub NewTBDBHandle($)
{
    my ($dbname) = @_;
    
    my $dbnum = @DB;
    # Avoid using the initial one here.
    $dbnum++
	if (!$dbnum);
    
    TBDBConnect($dbnum, $dbname);
    return $dbnum;
}

#
# Issue a DB query. Argument is a string. Returns the actual query object, so
# it is up to the caller to test it. I would not for one moment view this
# as encapsulation of the DB interface. I'm just tired of typing the same
# silly stuff over and over.
#
# usage: DBQuery(char *str)
#        returns the query object result.
#
# Sets $DBErrorString is case of error; saving the original query string and
# the error string from the DB module. Use DBFatal (below) to print/email
# that string, and then exit.
#
sub DBQueryN($$)
{
    my($dbnum, $query)   = @_;
    my $maxtries = $DBQUERY_MAXTRIES;
    my $result;

569 570 571
    # Update query count total for debugging purposes
    $queryCount += 1;

572 573 574 575 576
    # Not really forever :-)
    if (!$maxtries) {
	$maxtries = 100000;
    }

577 578 579 580 581 582 583
    # Mostly for ProtoGeni;
    if (!defined($dbnum)) {
	print STDERR "DB connection not setup:\n";
	print STDERR "Query: '$query'\n";
	return undef;
    }
    
584
    # Reconnect to mysqld in child of fork.
585
    if ($DB[$dbnum]->pid() != $PID) {
586 587 588 589 590 591 592 593 594 595 596 597 598 599
	if (TBDBReconnect(1) != 0) {
	    $DBErrorString =
		"  Query: $query\n".
		"  Error: Could not reconnect to mysqld";
	    return undef;
	}
    }

    if ($DBQUERY_DEBUG) {
	print STDERR "Query: '$query'\n";
    }

    while ($maxtries) {
	# Get this each time through the loop since we try reconnect below.
600 601
	my $dbw = $DB[$dbnum];
	my $db  = $dbw->dbh();
602

603
	$result = $dbw->query($query);
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

	if (! defined($result)) {
	    my $err = $db->err;

	    $DBErrorString =
		"  Query: $query\n".
		"  Error: " . $db->errstr . " ($err)";
	}
	if (defined($result) ||
	    ($db->err != 2006) && ($db->err != 1053) && ($db->err != 2013) &&
	    ($db->err != 1046)) {
	    last;
	}

	#
	# If we lose the connection to mysqld; lets try to reconnect. 
	#
	if ($db->err == 2006 || $db->err == 2013) {
	    # This is just for the mysqld watchdog daemon.
	    return undef
		if (! $DBQUERY_RECONNECT);

	    if (TBDBReconnect(1) != 0) {
		$DBErrorString =
		    "  Query: $query\n".
		    "  Error: Could not reconnect to mysqld";

		return undef;
	    }
	    next;
	}

	$maxtries--;
	DBWarn("mysqld went away in process $PID. $maxtries tries left", 0);
	sleep(1);
    }
    return $result;
}
sub DBQuery($) {return DBQueryN(0,$_[0]);}

#
# Same as above, but die on error.
#
sub DBQueryFatalN($$)
{
    my($dbnum, $query) = @_;
    my($result);

    $result = DBQueryN($dbnum, $query);

    if (! $result) {
	DBFatal("DB Query failed");
    }
    return $result;
}
sub DBQueryFatal($) {return DBQueryFatalN(0,$_[0]);}

661
#
662 663 664
# Like DBQueryFatal but also fail if the query didn't return any
# results and returns the result as an array in list context or the
# first column of the result is scalar content.
665 666 667 668 669 670 671
#
sub DBQuerySingleFatalN($$)
{
    my ($dbnum, $query) = @_;
    my $query_result = DBQueryFatalN($dbnum, $query);
    DBFatal("DB Query \"$query\" didn't return any results") 
	unless $query_result->numrows > 0;
672 673
    DBFatal("DB Query \"$query\" returned more than one row")
	unless $query_result->numrows == 1;
674
    my @row = $query_result->fetchrow_array();
675
    return wantarray ? @row : $row[0];
676 677 678
}
sub DBQuerySingleFatal($) {return DBQuerySingleFatalN(0,$_[0]);}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
#
# Same as above, but just send email on error. This info is useful
# to the TB system, but the caller has to retain control.
#
sub DBQueryWarnN($$)
{
    my($dbnum, $query) = @_;
    my($result);

    $result = DBQueryN($dbnum, $query);

    if (! $result) {
	DBWarn("DB Query failed");
    }
    return $result;
}
sub DBQueryWarn($) {return DBQueryWarnN(0,$_[0]);}

Leigh Stoller's avatar
Leigh Stoller committed
697 698 699 700 701 702
#
# Helper functions.
#
sub emdbi_die($)	{ die($_[0]); }
sub emdbi_warn($)	{ warn($_[0]); }

703 704 705 706 707 708 709 710 711 712
#
# Warn and send email after a failed DB query. First argument is the error
# message to display. The contents of $DBErrorString is also printed.
#
# usage: DBWarn(char *message)
#
sub DBWarn($;$)
{
    my($message, $nomail) = @_;
    
Leigh Stoller's avatar
Leigh Stoller committed
713
    DBError(\&emdbi_warn, $message, $nomail);
714 715 716 717 718 719 720 721 722 723 724
}

#
# Same as above, but die after the warning.
#
# usage: DBFatal(char *message);
#
sub DBFatal($;$)
{
    my ($message,$nomail) = $_[0];
    
Leigh Stoller's avatar
Leigh Stoller committed
725
    DBError(\&emdbi_die, $message, $nomail);
726 727 728 729 730 731 732 733 734 735 736 737
}

#
# DBError, common parts of DBWarn and DBFatal
#
# usage: DBError(log function, message, nomail)
#
sub DBError($$;$) 
{
    my($f, $message, $nomail) = @_;
    
    if (! defined($nomail)) {
738
	if (open(MAIL, "| /usr/sbin/sendmail -i -t")) {
739 740
	    print MAIL "To: $TBOPS\n";
	    print MAIL "Subject: DBError\n";
741
	    print MAIL "\n";
742 743
	    print MAIL "In $SCRIPTNAME\n\n";
	    print MAIL "$message\n\n";
744
	    print MAIL "$DBErrorString\n\n";
745 746
	    print MAIL Carp::longmess();
	    print MAIL "\n";
747 748
	    close(MAIL);
	}
749 750 751 752 753 754 755 756 757 758 759 760
    }

    $f->("$message:\n$DBErrorString\n");
}

#
# Quote a string for DB insertion.
#
# usage: char *DBQuoteSpecial(char *string);
#
sub DBQuoteSpecial($)
{
Leigh Stoller's avatar
Leigh Stoller committed
761
    my ($string) = @_;
762

763
    return $DB[0]->dbh()->quote($string);
764 765 766 767
}

sub DBQuoteSpecialN($$)
{
Leigh Stoller's avatar
Leigh Stoller committed
768
    my ($dbnum, $string) = @_;
769

770
    return $DB[$dbnum]->dbh()->quote($string);
771 772 773 774 775 776 777
}

#
# Get the Error From the Last Database query
#
sub DBErrN($)
{
778
    return $DB[$_[0]]->dbh()->err;
779 780 781
}
sub DBErr()
{
782
    return $DB[0]->dbh()->err;
783 784
}

785 786 787 788 789 790 791 792
#
# Some utility routines for doing migration (DB upgrades).
#
sub DBTableExistsN($$)
{
    my($dbnum, $table) = @_;

    my $result =
793
	DBQueryFatalN($dbnum, "show tables like '$table'");
794 795 796 797 798 799 800 801 802 803

    return $result->numrows;
}
sub DBTableExists($) { return DBTableExistsN(0,$_[0]); }

sub DBSlotExistsN($$$)
{
    my($dbnum, $table, $slot) = @_;

    my $result =
804
	DBQueryFatalN($dbnum, "show columns from `$table` like '$slot'");
805 806 807 808 809

    return $result->numrows;
}
sub DBSlotExists($$) { return DBSlotExistsN(0,$_[0],$_[1]); }

810 811 812 813 814 815 816 817 818 819 820 821 822 823
sub DBSlotTypeN($$$)
{
    my($dbnum, $table, $slot) = @_;

    my $result =
	DBQueryFatalN($dbnum, "show columns from `$table` like '$slot'");

    return undef
	if (! $result->numrows);
    my $row = $result->fetchrow_hashref();
    return $row->{'Type'};
}
sub DBSlotType($$) { return DBSlotTypeN(0,$_[0],$_[1]); }

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
sub DBKeyExistsN($$$)
{
    my($dbnum, $table, $keyname) = @_;

    my $result =
	DBQueryFatalN($dbnum, "show index from `$table`");

    while (my (undef,undef,$kname,undef,$colname) = $result->fetchrow_array()){
	return 1
	    if ($kname eq $keyname);
    }
    return 0;
}
sub DBKeyExists($$) { return DBKeyExistsN(0,$_[0],$_[1]); }

839 840 841 842 843 844 845 846 847 848 849
sub DBHandleN($)
{
    my ($dbnum) = @_;
    
    my $dbw = $DB[$dbnum];
    my $db  = $dbw->dbh();

    return $db;
}
sub DBHandle()	    { return DBHandleN(0); }

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
END {
    # Call it here otherwise may get:
    #   (in cleanup) Can't call method "FETCH" on an undefined value at 
    #   /usr/local/lib/perl5/site_perl/5.8.8/mach/Mysql.pm line 91 during 
    #   global destruction.
    # where line 91 is:
    #  	my $oldvalue = $self->{'dbh'}->{'InactiveDestroy'};
    # which is in setInactiveDestroy() which get called in libdb.pm in:
    #   if ($self->db_pid() != $$) {
    #       $self->setInactiveDestroy(1);
    #   }
    # which is in TestbedDBHandle::DESTROY (still in libdb.pm even
    # though it is a diffrent package)
    #
    # This error is probably due to some object being destroyed too
    # soon somewhere in the DBI/DBD modules.
    TBDBDisconnect();
}

869 870 871 872 873 874 875 876 877 878
sub ClearQueryCount()
{
    $queryCount = 0;
}

sub GetQueryCount()
{
    return $queryCount;
}

879 880 881 882
# _Always_ make sure that this 1 is at the end of the file...

1;