From 1d9c1ecaa12350a5f49adae6cd7e9459b3cbabdb Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Thu, 17 Jan 2019 22:41:23 -0300 Subject: [PATCH] Bug 22159: Add ColumnExists method This patch adds a method for checking if a column exists on a DB table. The way this is checked is used already on updatedatabase.pl [1] (i.e. querying INFORMATION_SCHEMA. To test: - Create an atomicupdate file like this: $ cd installer/data/mysql/atomicupdate $ cp skeleton.perl test.perl - Change the contents of test.perl so it looks like this: $DBversion = 'XXX'; if( CheckVersion( $DBversion ) ) { if ( ColumnExists( 'borrowers', 'firstname' ) ) { print "Column borrowers.firstname exists!"; } else { print "Boo, borrowers.firstname wasn't detected"; } if ( ColumnExists( 'borrowers', 'friendly_alias' ) ) { print "Great, there's no borrowers.firend_alias"; } else { print "Boo, this is really wrong"; } } - Run: $ updatedatabase or $ kshell k$ perl installer/data/mysql/updatedatabase.pl => SUCCESS: No 'Boo' message is printed - Sign off :-D [1] See 3.03.00.023 or 18.12.00.002 --- installer/data/mysql/updatedatabase.pl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/installer/data/mysql/updatedatabase.pl b/installer/data/mysql/updatedatabase.pl index b4d246ab85..f91fa994a7 100755 --- a/installer/data/mysql/updatedatabase.pl +++ b/installer/data/mysql/updatedatabase.pl @@ -17280,6 +17280,27 @@ sub TableExists { return 0; } +=head2 ColumnExists( $table, $column ) + +=cut + +sub ColumnExists { + my ( $table, $column ) = @_; + + my $database = C4::Context->config("database"); + + my $sth = $dbh->prepare(qq{ + SELECT * FROM INFORMATION_SCHEMA.COLUMNS + WHERE + TABLE_SCHEMA='$database' AND + TABLE_NAME='$table' AND + COLUMN_NAME='$column'; + }); + $sth->execute; + + return ($sth->fetchrow_hashref) ? 1 : 0; +} + =head2 DropAllForeignKeys($table) Drop all foreign keys of the table $table -- 2.20.1