Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to check for existence of a table column before altering #43

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 35 additions & 10 deletions src/com/palmergames/bukkit/towny/db/TownySQLSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -201,18 +201,15 @@ public void initialize(Towny plugin, TownyUniverse universe) {
/*
* Update the table structure for older databases.
*/
String resident_update = "IF EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS "
+ "WHERE table_name = `" + tb_prefix + "RESIDENTS` "
+ "AND table_schema = `" + db_name + "` "
+ "AND column_name != `town-ranks`) THEN "
+ "ALTER TABLE " + tb_prefix + "RESIDENTS (ADD "
+ "`town-ranks` mediumtext,"
+ "`nation-ranks` mediumtext"
+ ");";

try {

Statement s = cntx.createStatement();
s.executeUpdate(resident_update);
if(!getFieldExists("RESIDENTS", "town-ranks")){
s.executeUpdate( "ALTER TABLE " + tb_prefix + "RESIDENTS (ADD `town-ranks` mediumtext);" );
}
if(!getFieldExists("RESIDENTS", "nation-ranks")){
s.executeUpdate( "ALTER TABLE " + tb_prefix + "RESIDENTS (ADD `nation-ranks` mediumtext);" );
}
TownyMessaging.sendDebugMsg("Table RESIDENTS is updated!");
} catch (SQLException ee) {
TownyMessaging.sendErrorMsg("Error updating table RESIDENTS :" + ee.getMessage());
Expand Down Expand Up @@ -301,6 +298,34 @@ public void initialize(Towny plugin, TownyUniverse universe) {

TownyMessaging.sendDebugMsg("Checking done!");
}

/**
* Verify if a database table field exists
* @param table_name
* @param field_name
* @return boolean
*/
protected boolean getFieldExists( String table_name, String field_name ){

if(!table_name.isEmpty() && !field_name.isEmpty()){

String field_check = "SHOW COLUMNS FROM `" + tb_prefix + table_name + "`";

try {
Statement s = cntx.createStatement();
s.executeQuery(field_check);
ResultSet rs = s.getResultSet();
while(rs.next()){
if(rs.getString("Field").equalsIgnoreCase(field_name)){
return true;
}
}
} catch (SQLException ee) {
// ?
}
}
return false;
}

/**
* open a connection to the SQL server.
Expand Down