Skip to content

Commit 281fcf1

Browse files
committed
cleanup
1 parent 5480f4c commit 281fcf1

File tree

6 files changed

+22
-144
lines changed

6 files changed

+22
-144
lines changed

src/main/kotlin/li/angu/challengeplugin/database/DatabaseDriver.kt

Lines changed: 3 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -23,41 +23,23 @@ class DatabaseDriver(private val plugin: ChallengePluginPlugin) {
2323
// Ensure data folder exists
2424
plugin.dataFolder.mkdirs()
2525

26-
plugin.logger.info("Plugin data folder: ${plugin.dataFolder.absolutePath}")
27-
plugin.logger.info("Database file path: ${databaseFile.absolutePath}")
28-
plugin.logger.info("Database file exists: ${databaseFile.exists()}")
29-
if (databaseFile.exists()) {
30-
plugin.logger.info("Database file size: ${databaseFile.length()} bytes")
31-
}
3226

3327
// Load SQLite JDBC driver
3428
Class.forName("org.sqlite.JDBC")
3529

3630
// Create connection
3731
val connectionString = "jdbc:sqlite:${databaseFile.absolutePath}"
38-
plugin.logger.info("Connecting to database with: $connectionString")
3932
connection = DriverManager.getConnection(connectionString)
40-
41-
plugin.logger.info("Database connection established: ${connection != null}")
42-
plugin.logger.info("Database connection valid: ${connection?.isValid(5)}")
4333

4434
// Enable foreign keys
4535
connection?.createStatement()?.use { stmt ->
4636
stmt.execute("PRAGMA foreign_keys = ON")
47-
plugin.logger.info("Foreign keys enabled")
48-
49-
// Test if we can read basic SQLite info
50-
val result = stmt.executeQuery("PRAGMA database_list")
51-
while (result.next()) {
52-
plugin.logger.info("Database: name=${result.getString("name")}, file=${result.getString("file")}")
53-
}
54-
result.close()
5537
}
5638

5739
// Run migrations - this will throw an exception if any migration fails
5840
migrationManager.runMigrations()
5941

60-
plugin.logger.info("Database initialized successfully at: ${databaseFile.absolutePath}")
42+
plugin.logger.info("Database initialized successfully")
6143
return true
6244

6345
} catch (e: Exception) {
@@ -173,14 +155,10 @@ class DatabaseDriver(private val plugin: ChallengePluginPlugin) {
173155
return try {
174156
val conn = getConnection() ?: return false
175157

176-
plugin.logger.info("Starting database transaction with ${operations.size} operations")
177158
conn.autoCommit = false
178159

179160
try {
180-
operations.forEachIndexed { index, (sql, params) ->
181-
plugin.logger.info("Executing operation $index: $sql")
182-
plugin.logger.info("Parameters: ${params.joinToString(", ")}")
183-
161+
operations.forEach { (sql, params) ->
184162
conn.prepareStatement(sql).use { statement ->
185163
params.forEachIndexed { paramIndex, param ->
186164
when (param) {
@@ -193,17 +171,13 @@ class DatabaseDriver(private val plugin: ChallengePluginPlugin) {
193171
else -> statement.setObject(paramIndex + 1, param)
194172
}
195173
}
196-
val rowsAffected = statement.executeUpdate()
197-
plugin.logger.info("Operation $index affected $rowsAffected rows")
174+
statement.executeUpdate()
198175
}
199176
}
200177

201-
plugin.logger.info("Committing transaction")
202178
conn.commit()
203-
plugin.logger.info("Transaction committed successfully")
204179
true
205180
} catch (e: SQLException) {
206-
plugin.logger.severe("Transaction failed, rolling back: ${e.message}")
207181
conn.rollback()
208182
throw e
209183
} finally {
@@ -236,14 +210,10 @@ class DatabaseDriver(private val plugin: ChallengePluginPlugin) {
236210
*/
237211
fun sync() {
238212
try {
239-
plugin.logger.info("Database sync requested for file: ${databaseFile.absolutePath}")
240-
plugin.logger.info("Database file exists: ${databaseFile.exists()}, size: ${if (databaseFile.exists()) databaseFile.length() else 0} bytes")
241-
242213
// Execute PRAGMA synchronous to ensure data is written
243214
getConnection()?.createStatement()?.use { stmt ->
244215
stmt.execute("PRAGMA synchronous = FULL")
245216
stmt.execute("PRAGMA wal_checkpoint(FULL)")
246-
plugin.logger.info("Executed PRAGMA synchronous and WAL checkpoint")
247217
}
248218
} catch (e: Exception) {
249219
plugin.logger.warning("Error during database sync: ${e.message}")

src/main/kotlin/li/angu/challengeplugin/database/MigrationManager.kt

Lines changed: 6 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -55,25 +55,17 @@ class MigrationManager(
5555

5656
// Get current schema version
5757
val currentVersion = getCurrentSchemaVersion()
58-
plugin.logger.info("Current schema version: $currentVersion")
59-
60-
// Log all available migrations for debugging
61-
plugin.logger.info("Available migrations: ${migrations.map { "${it.version}: ${it.description}" }}")
6258

6359
// Get pending migrations
6460
val pendingMigrations = migrations
6561
.filter { it.version > currentVersion }
6662
.sortedBy { it.version }
6763

68-
plugin.logger.info("Pending migrations: ${pendingMigrations.map { "${it.version}: ${it.description}" }}")
69-
7064
if (pendingMigrations.isEmpty()) {
71-
plugin.logger.info("No pending migrations. Current schema version: ${getCurrentSchemaVersion()}")
65+
plugin.logger.info("No pending migrations")
7266
return
7367
}
7468

75-
plugin.logger.info("Found ${pendingMigrations.size} pending migrations to execute")
76-
7769
// Run pending migrations - STOP on first failure
7870
for (migration in pendingMigrations) {
7971
plugin.logger.info("Running migration ${migration.version}: ${migration.description}")
@@ -89,7 +81,7 @@ class MigrationManager(
8981
plugin.logger.info("Migration ${migration.version} completed successfully")
9082
}
9183

92-
plugin.logger.info("All migrations completed successfully. Current schema version: ${getCurrentSchemaVersion()}")
84+
plugin.logger.info("All migrations completed successfully")
9385

9486
// Force synchronization to disk so external tools can see the changes
9587
databaseDriver.sync()
@@ -114,62 +106,33 @@ class MigrationManager(
114106

115107
private fun getCurrentSchemaVersion(): Int {
116108
return try {
117-
plugin.logger.info("Querying current schema version...")
118-
119-
// First, let's check if the table exists and what's in it
120-
val count = databaseDriver.executeQuery("SELECT COUNT(*) as count FROM schema_migrations") { rs ->
121-
if (rs.next()) rs.getInt("count") else 0
122-
} ?: 0
123-
plugin.logger.info("Found $count entries in schema_migrations table")
124-
125-
// Check if the table exists at all
126-
val tableExists = databaseDriver.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations'") { rs ->
127-
rs.next()
128-
} ?: false
129-
plugin.logger.info("schema_migrations table exists: $tableExists")
130-
131-
// List all tables to see what exists
109+
// Check if database file exists with size > 0 but no tables found (corruption check)
132110
val tables = databaseDriver.executeQuery("SELECT name FROM sqlite_master WHERE type='table'") { rs ->
133111
val tableList = mutableListOf<String>()
134112
while (rs.next()) {
135113
tableList.add(rs.getString("name"))
136114
}
137115
tableList
138116
} ?: emptyList()
139-
plugin.logger.info("All tables in database: $tables")
140117

141118
// If database file exists with size > 0 but no tables found, it might be corrupted
142119
if (tables.isEmpty() && databaseDriver.getDatabaseFile().exists() && databaseDriver.getDatabaseFile().length() > 0) {
143120
plugin.logger.warning("Database file exists with ${databaseDriver.getDatabaseFile().length()} bytes but no tables found - possible corruption")
144121
throw SQLException("Database appears corrupted - contains data but no readable tables. Please delete the database file manually: ${databaseDriver.getDatabaseFile().absolutePath}")
145122
}
146123

147-
// Now let's see all versions in the table
148-
val versions = databaseDriver.executeQuery("SELECT version, description FROM schema_migrations ORDER BY version") { rs ->
149-
val versionList = mutableListOf<String>()
150-
while (rs.next()) {
151-
versionList.add("${rs.getInt("version")}: ${rs.getString("description")}")
152-
}
153-
versionList
154-
} ?: emptyList()
155-
plugin.logger.info("Existing migrations in database: $versions")
156-
157-
// Now get the max version
124+
// Get the max version
158125
val maxVersion = databaseDriver.executeQuery("SELECT MAX(version) as version FROM schema_migrations") { rs ->
159126
if (rs.next()) {
160-
val version = rs.getInt("version")
161-
plugin.logger.info("MAX version query returned: $version")
162-
version
127+
rs.getInt("version")
163128
} else {
164-
plugin.logger.info("No rows found in MAX version query, returning version 0")
165129
0
166130
}
167131
} ?: 0
168132

169133
maxVersion
170134
} catch (e: SQLException) {
171135
plugin.logger.warning("Failed to query schema version: ${e.message}")
172-
e.printStackTrace()
173136
0 // If table doesn't exist or query fails, assume version 0
174137
}
175138
}
@@ -178,23 +141,13 @@ class MigrationManager(
178141
val migration = migrations.find { it.version == version }
179142
val description = migration?.description ?: "Unknown migration"
180143

181-
plugin.logger.info("Updating schema version to $version: $description")
182-
183144
val rowsAffected = databaseDriver.executeUpdate(
184145
"INSERT INTO schema_migrations (version, description) VALUES (?, ?)",
185146
version, description
186147
)
187148

188-
if (rowsAffected > 0) {
189-
plugin.logger.info("Successfully recorded migration $version in schema_migrations table")
190-
} else {
149+
if (rowsAffected <= 0) {
191150
plugin.logger.warning("Failed to record migration $version in schema_migrations table (0 rows affected)")
192151
}
193-
194-
// Verify the insert worked by immediately querying back
195-
val count = databaseDriver.executeQuery("SELECT COUNT(*) as count FROM schema_migrations WHERE version = ?", version) { rs ->
196-
if (rs.next()) rs.getInt("count") else 0
197-
} ?: 0
198-
plugin.logger.info("Verification: Found $count entries for migration $version in schema_migrations table")
199152
}
200153
}

src/main/kotlin/li/angu/challengeplugin/listeners/PlayerConnectionListener.kt

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,23 @@ import java.util.UUID
2020
class PlayerConnectionListener(private val plugin: ChallengePluginPlugin) : Listener {
2121

2222
@EventHandler
23-
fun onPlayerQuit(event: PlayerQuitEvent) {
23+
fun onPlayerJoin(event: PlayerJoinEvent) {
2424
val player = event.player
25-
plugin.logger.info("Player ${player.name} (${player.uniqueId}) is quitting the server")
2625

26+
// Always teleport player to the lobby first
27+
plugin.lobbyManager.teleportToLobby(player)
28+
29+
// Send welcome message
30+
player.sendMessage(plugin.languageManager.getMessage("lobby.welcome", player))
31+
}
32+
33+
@EventHandler
34+
fun onPlayerQuit(event: PlayerQuitEvent) {
35+
val player = event.player
2736
val challenge = plugin.challengeManager.getPlayerChallenge(player)
28-
plugin.logger.info("Player ${player.name} current challenge: ${challenge?.name ?: "none"}")
2937

3038
// Save player data if they're in an active challenge
3139
if (challenge != null && challenge.isPlayerInChallenge(player)) {
32-
plugin.logger.info("Saving player data for ${player.name} in challenge ${challenge.name}")
3340
// Save player data for the challenge
3441
plugin.playerDataManager.savePlayerData(player, challenge.id)
3542

@@ -39,9 +46,6 @@ class PlayerConnectionListener(private val plugin: ChallengePluginPlugin) : List
3946
// Remove the player from the playerChallengeMap
4047
// This ensures they'll start in the lobby when reconnecting
4148
plugin.challengeManager.removePlayerFromChallenge(player.uniqueId)
42-
plugin.logger.info("Player ${player.name} removed from challenge and mapping cleared")
43-
} else {
44-
plugin.logger.info("Player ${player.name} was not in a challenge, no data to save")
4549
}
4650
}
4751

src/main/kotlin/li/angu/challengeplugin/managers/ChallengeManager.kt

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -419,12 +419,9 @@ class ChallengeManager(private val plugin: ChallengePluginPlugin) {
419419
}
420420

421421
// Check if player has saved data for this challenge
422-
plugin.logger.info("Checking for saved data for player ${player.name} (${player.uniqueId}) in challenge ${challenge.name} (${challenge.id})")
423422
if (plugin.playerDataManager.hasPlayerData(player.uniqueId, challenge.id)) {
424-
plugin.logger.info("Found saved data for player ${player.name} in challenge ${challenge.name}, attempting restore")
425423
// Restore player data (inventory, location, etc.)
426424
if (plugin.playerDataManager.restorePlayerData(player, challenge.id)) {
427-
plugin.logger.info("Successfully restored player data for ${player.name} in challenge ${challenge.name}")
428425
// Add player to challenge without resetting
429426
if (challenge.addPlayer(player)) {
430427
playerChallengeMap[player.uniqueId] = challenge.id
@@ -439,8 +436,6 @@ class ChallengeManager(private val plugin: ChallengePluginPlugin) {
439436
} else {
440437
plugin.logger.warning("Failed to restore player data for ${player.name} in challenge ${challenge.name}")
441438
}
442-
} else {
443-
plugin.logger.info("No saved data found for player ${player.name} in challenge ${challenge.name}, starting fresh")
444439
}
445440

446441
// If no saved data or restore failed, add player normally

src/main/kotlin/li/angu/challengeplugin/managers/PlayerDataManager.kt

Lines changed: 2 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -136,29 +136,20 @@ class PlayerDataManager(private val plugin: ChallengePluginPlugin) {
136136
* Checks if a player has saved data for a challenge
137137
*/
138138
fun hasPlayerData(playerId: UUID, challengeId: UUID): Boolean {
139-
plugin.logger.info("Checking hasPlayerData for player $playerId, challenge $challengeId")
140-
141139
// Check cache first
142140
if (cachedPlayerData[playerId]?.containsKey(challengeId) == true) {
143-
plugin.logger.info("Found data in cache for player $playerId, challenge $challengeId")
144141
return true
145142
}
146-
plugin.logger.info("No cached data found, checking database for player $playerId, challenge $challengeId")
147-
148-
// Check database for player data
149143

150144
// Check database
151145
val result = plugin.databaseDriver.executeQuery(
152146
"SELECT 1 FROM player_challenge_data WHERE player_uuid = ? AND challenge_id = ?",
153147
playerId.toString(),
154148
challengeId.toString()
155149
) { rs ->
156-
val hasData = rs.next()
157-
plugin.logger.info("Database query result for player $playerId, challenge $challengeId: $hasData")
158-
hasData
150+
rs.next()
159151
} ?: false
160152

161-
plugin.logger.info("Final hasPlayerData result for player $playerId, challenge $challengeId: $result")
162153
return result
163154
}
164155

@@ -168,20 +159,15 @@ class PlayerDataManager(private val plugin: ChallengePluginPlugin) {
168159
* Returns null if no saved data exists.
169160
*/
170161
fun findChallengeWithPlayerData(playerId: UUID): Challenge? {
171-
plugin.logger.info("Looking for challenge data for player $playerId")
172-
173162
// First check cache for any cached data
174163
cachedPlayerData[playerId]?.let { challengeMap ->
175164
if (challengeMap.isNotEmpty()) {
176165
// Player has cached data, find which challenge it belongs to
177166
val challengeId = challengeMap.keys.first()
178-
plugin.logger.info("Found cached data for player $playerId in challenge $challengeId")
179167
return plugin.challengeManager.getChallenge(challengeId)
180168
}
181169
}
182170

183-
plugin.logger.info("No cached data found, querying database for player $playerId")
184-
185171
// Query database once to find any challenge with player data
186172
val challengeId = plugin.databaseDriver.executeQuery(
187173
"SELECT challenge_id FROM player_challenge_data WHERE player_uuid = ? LIMIT 1",
@@ -190,24 +176,20 @@ class PlayerDataManager(private val plugin: ChallengePluginPlugin) {
190176
if (rs.next()) {
191177
try {
192178
val id = rs.getString("challenge_id")
193-
plugin.logger.info("Found database entry for player $playerId in challenge $id")
194179
UUID.fromString(id)
195180
} catch (e: Exception) {
196181
plugin.logger.warning("Invalid challenge_id UUID in player data: ${e.message}")
197182
null
198183
}
199184
} else {
200-
plugin.logger.info("No database entry found for player $playerId")
201185
null
202186
}
203187
}
204188

205189
// Return the challenge object if found
206190
return challengeId?.let {
207191
val challenge = plugin.challengeManager.getChallenge(it)
208-
if (challenge != null) {
209-
plugin.logger.info("Found challenge ${challenge.name} for player $playerId")
210-
} else {
192+
if (challenge == null) {
211193
plugin.logger.warning("Challenge $it found in database but not loaded in memory for player $playerId")
212194
}
213195
challenge
@@ -308,33 +290,8 @@ class PlayerDataManager(private val plugin: ChallengePluginPlugin) {
308290
)
309291
}
310292

311-
plugin.logger.info("Attempting to save player data for ${playerData.uuid} to challenge ${playerData.challengeId}")
312-
plugin.logger.info("Total operations to execute: ${operations.size}")
313-
314293
if (!plugin.databaseDriver.executeTransaction(operations)) {
315294
plugin.logger.severe("Failed to save player data to database for ${playerData.uuid}")
316-
plugin.logger.severe("Operations that failed:")
317-
operations.forEachIndexed { index, (sql, params) ->
318-
plugin.logger.severe(" Operation $index: $sql")
319-
plugin.logger.severe(" Parameters: ${params.joinToString(", ")}")
320-
}
321-
} else {
322-
plugin.logger.info("Successfully saved player data for ${playerData.uuid} to challenge ${playerData.challengeId}")
323-
324-
// Immediately verify the save worked
325-
plugin.logger.info("Verifying save by querying database...")
326-
val count = plugin.databaseDriver.executeQuery(
327-
"SELECT COUNT(*) as count FROM player_challenge_data WHERE player_uuid = ? AND challenge_id = ?",
328-
playerData.uuid.toString(),
329-
playerData.challengeId.toString()
330-
) { rs ->
331-
if (rs.next()) rs.getInt("count") else 0
332-
} ?: 0
333-
plugin.logger.info("Verification: Found $count entries in database for player ${playerData.uuid}, challenge ${playerData.challengeId}")
334-
335-
// Force database sync to disk
336-
plugin.databaseDriver.sync()
337-
plugin.logger.info("Database synced to disk")
338295
}
339296
}
340297

0 commit comments

Comments
 (0)