All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.freya022.botcommands.internal.commands.application.cache.DatabaseApplicationCommandsCache.kt Maven / Gradle / Ivy

Go to download

A Kotlin-first (and Java) framework that makes creating Discord bots a piece of cake, using the JDA library.

There is a newer version: 3.0.0-alpha.18
Show newest version
package io.github.freya022.botcommands.internal.commands.application.cache

import io.github.freya022.botcommands.api.core.db.preparedStatement
import io.github.freya022.botcommands.internal.core.db.InternalDatabase
import net.dv8tion.jda.api.entities.Guild

internal class DatabaseApplicationCommandsCache internal constructor(
    private val guild: Guild?,
    private val database: InternalDatabase,
    private val applicationId: Long,
) : ApplicationCommandsCache {

    override suspend fun tryRead(): ApplicationCommandsData {
        database.preparedStatement(
            """
                select data, metadata
                from application_commands_cache
                where application_id = ?
                  and guild_id is not distinct from ?
            """.trimIndent(),
            readOnly = true
        ) {
            val row = executeQuery(applicationId, guild?.idLong).readOrNull()
                ?: return ApplicationCommandsData(null, null)
            return ApplicationCommandsData(row["data"], row["metadata"])
        }
    }

    override suspend fun write(commandBytes: ByteArray, metadataBytes: ByteArray) {
        database.preparedStatement(
            """
                insert into application_commands_cache (application_id, guild_id, data, metadata)
                values (?, ?, ?, ?)
                on conflict(application_id, guild_id) do update set data     = excluded.data,
                                                                    metadata = excluded.metadata
            """.trimIndent()
        ) {
            val commands = commandBytes.decodeToString()
            val metadata = metadataBytes.decodeToString()
            executeUpdate(applicationId, guild?.idLong, commands, metadata)
        }
    }

    override fun toString(): String {
        return "DatabaseApplicationCommandsCache(guild=${guild?.id})"
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy