Alter INSERT IGNORE queries to workaround innodb auto increment behaviour

An INSERT IGNORE query will still increment when using innodb, even if no row is inserted.  We can work around this by using a slightly convoluted query, but this only works if the table is non-empty, so also check for that on startup and create a dummy record if necessary.
This commit is contained in:
Philip Cass
2013-11-06 10:45:13 +00:00
parent c117bcd854
commit 7ac35e4698
2 changed files with 8 additions and 2 deletions

View File

@ -336,7 +336,8 @@ public class Consumer extends TimerTask
continue;
for (final String player : r.getPlayers())
if (!playerIds.containsKey(player) && !insertedPlayers.contains(player)) {
writer.println("INSERT IGNORE INTO `lb-players` (playername) VALUES ('" + player + "');");
// Odd query contruction is to work around innodb auto increment behaviour - bug #492
writer.println("INSERT IGNORE INTO `lb-players` (playername) SELECT '" + player + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE playername = '" + player + "') LIMIT 1;");
insertedPlayers.add(player);
}
for (final String insert : r.getInserts())
@ -365,7 +366,8 @@ public class Consumer extends TimerTask
}
private boolean addPlayer(Statement state, String playerName) throws SQLException {
state.execute("INSERT IGNORE INTO `lb-players` (playername) VALUES ('" + playerName + "')");
// Odd query contruction is to work around innodb auto increment behaviour - bug #492
state.execute("INSERT IGNORE INTO `lb-players` (playername) SELECT '" + playerName + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE playername = '" + playerName + "') LIMIT 1;");
final ResultSet rs = state.executeQuery("SELECT playerid FROM `lb-players` WHERE playername = '" + playerName + "'");
if (rs.next())
playerIds.put(playerName, rs.getInt(1));

View File

@ -246,6 +246,10 @@ class Updater
final DatabaseMetaData dbm = conn.getMetaData();
conn.setAutoCommit(true);
createTable(dbm, state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), UNIQUE (playername))");
// Players table must not be empty or inserts won't work - bug #492
final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;");
if (!rs.next())
state.execute("INSERT IGNORE INTO `lb-players` (playername) VALUES ('dummy_record')");
if (isLogging(Logging.CHAT))
createTable(dbm, state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(255) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) ENGINE=MyISAM DEFAULT CHARSET utf8");
for (final WorldConfig wcfg : getLoggedWorlds()) {