summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/storage/ExposedBacking.kt
blob: cbcb6f4c599ebc4fc5a6b7ed43e704446e240c9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package io.dico.parcels2.storage

import com.zaxxer.hikari.HikariDataSource
import io.dico.parcels2.*
import io.dico.parcels2.util.Vec2i
import io.dico.parcels2.util.toByteArray
import io.dico.parcels2.util.toUUID
import kotlinx.coroutines.experimental.channels.ProducerScope
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SchemaUtils.create
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.vendors.DatabaseDialect
import org.joda.time.DateTime
import java.util.*
import javax.sql.DataSource

object WorldsT : Table("worlds") {
    val id = integer("world_id").autoIncrement().primaryKey()
    val name = varchar("name", 50)
    val uid = binary("uid", 16)
    val index_uid = uniqueIndexR("index_uid", uid)
}

object ParcelsT : Table("parcels") {
    val id = integer("parcel_id").autoIncrement().primaryKey()
    val px = integer("px")
    val pz = integer("pz")
    val world_id = integer("world_id").references(WorldsT.id)
    val owner_uuid = binary("owner_uuid", 16).nullable()
    val owner_name = varchar("owner_name", 16).nullable()
    val claim_time = datetime("claim_time").nullable()
    val index_location = uniqueIndexR("index_location", world_id, px, pz)
}

object AddedLocalT : Table("parcels_added_local") {
    val parcel_id = integer("parcel_id").references(ParcelsT.id, ReferenceOption.CASCADE)
    val player_uuid = binary("player_uuid", 16)
    val allowed_flag = bool("allowed_flag")
    val index_pair = uniqueIndexR("index_pair", parcel_id, player_uuid)
}

object AddedGlobalT : Table("parcels_added_global") {
    val owner_uuid = binary("owner_uuid", 16)
    val player_uuid = binary("player_uuid", 16)
    val allowed_flag = bool("allowed_flag")
    val index_pair = uniqueIndexR("index_pair", owner_uuid, player_uuid)
}

object ParcelOptionsT : Table("parcel_options") {
    val parcel_id = integer("parcel_id").primaryKey().references(ParcelsT.id, ReferenceOption.CASCADE)
    val interact_inventory = bool("interact_inventory").default(false)
    val interact_inputs = bool("interact_inputs").default(false)
}

private class ExposedDatabaseException(message: String? = null) : Exception(message)

@Suppress("NOTHING_TO_INLINE")
class ExposedBacking(private val dataSourceFactory: () -> DataSource) : Backing {
    override val name get() = "Exposed"
    private var dataSource: DataSource? = null
    private var database: Database? = null
    private var isShutdown: Boolean = false

    override val isConnected get() = database != null

    companion object {
        init {
            Database.registerDialect("mariadb") {
                Class.forName("org.jetbrains.exposed.sql.vendors.MysqlDialect").newInstance() as DatabaseDialect
            }
        }
    }

    override suspend fun init() {
        if (isShutdown) throw IllegalStateException()
        dataSource = dataSourceFactory()
        database = Database.connect(dataSource!!)
        transaction(database) {
            create(WorldsT, ParcelsT, AddedLocalT, ParcelOptionsT)
        }
    }

    override suspend fun shutdown() {
        if (isShutdown) throw IllegalStateException()
        dataSource?.let {
            if (it is HikariDataSource) it.close()
        }
        database = null
        isShutdown = true
    }

    private fun <T> transaction(statement: Transaction.() -> T) = transaction(database, statement)

    private inline fun Transaction.getWorldId(binaryUid: ByteArray): Int? {
        return WorldsT.select { WorldsT.uid eq binaryUid }.firstOrNull()?.let { it[WorldsT.id] }
    }

    private inline fun Transaction.getWorldId(worldUid: UUID): Int? {
        return getWorldId(worldUid.toByteArray()!!)
    }

    private inline fun Transaction.getOrInitWorldId(worldUid: UUID, worldName: String): Int {
        val binaryUid = worldUid.toByteArray()!!
        return getWorldId(binaryUid)
            ?: WorldsT.insert /*Ignore*/ { it[uid] = binaryUid; it[name] = worldName }.get(WorldsT.id)
            ?: throw ExposedDatabaseException("This should not happen - failed to insert world named $worldName and get its id")
    }

    private inline fun Transaction.getParcelId(worldId: Int, parcelX: Int, parcelZ: Int): Int? {
        return ParcelsT.select { (ParcelsT.world_id eq worldId) and (ParcelsT.px eq parcelX) and (ParcelsT.pz eq parcelZ) }
            .firstOrNull()?.let { it[ParcelsT.id] }
    }

    private inline fun Transaction.getParcelId(worldUid: UUID, parcelX: Int, parcelZ: Int): Int? {
        return getWorldId(worldUid)?.let { getParcelId(it, parcelX, parcelZ) }
    }

    private inline fun Transaction.getOrInitParcelId(worldUid: UUID, worldName: String, parcelX: Int, parcelZ: Int): Int {
        val worldId = getOrInitWorldId(worldUid, worldName)
        return getParcelId(worldId, parcelX, parcelZ)
            ?: ParcelsT.insert /*Ignore*/ { it[world_id] = worldId; it[px] = parcelX; it[pz] = parcelZ }.get(ParcelsT.id)
            ?: throw ExposedDatabaseException("This should not happen - failed to insert parcel at $worldName($parcelX, $parcelZ)")
    }

    private inline fun Transaction.getParcelRow(id: Int): ResultRow? {
        return ParcelsT.select { ParcelsT.id eq id }.firstOrNull()
    }

    fun Transaction.getWorldId(world: ParcelWorld): Int? {
        return getWorldId(world.world.uid)
    }

    fun Transaction.getOrInitWorldId(world: ParcelWorld): Int {
        return world.world.let { getOrInitWorldId(it.uid, it.name) }
    }

    fun Transaction.getParcelId(parcel: Parcel): Int? {
        return getParcelId(parcel.world.world.uid, parcel.pos.x, parcel.pos.z)
    }

    fun Transaction.getOrInitParcelId(parcel: Parcel): Int {
        return parcel.world.world.let { getOrInitParcelId(it.uid, it.name, parcel.pos.x, parcel.pos.z) }
    }

    fun Transaction.getParcelRow(parcel: Parcel): ResultRow? {
        return getParcelId(parcel)?.let { getParcelRow(it) }
    }

    override suspend fun ProducerScope<Pair<Parcel, ParcelData?>>.produceParcelData(parcels: Sequence<Parcel>) {
        for (parcel in parcels) {
            val data = readParcelData(parcel)
            channel.send(parcel to data)
        }
        channel.close()
    }

    override suspend fun ProducerScope<Pair<SerializableParcel, ParcelData?>>.produceAllParcelData() {
        ParcelsT.selectAll().forEach { row ->
            val parcel = rowToSerializableParcel(row) ?: return@forEach
            val data = rowToParcelData(row)
            channel.send(parcel to data)
        }
        channel.close()
    }

    override suspend fun readParcelData(parcelFor: Parcel): ParcelData? = transaction {
        val row = getParcelRow(parcelFor) ?: return@transaction null
        rowToParcelData(row)
    }

    override suspend fun getOwnedParcels(user: ParcelOwner): List<SerializableParcel> = transaction {
        val where: SqlExpressionBuilder.() -> Op<Boolean>

        if (user.uuid != null) {
            val binaryUuid = user.uuid.toByteArray()
            where = { ParcelsT.owner_uuid eq binaryUuid }
        } else {
            val name = user.name
            where = { ParcelsT.owner_name eq name }
        }

        ParcelsT.select(where)
            .orderBy(ParcelsT.claim_time, isAsc = true)
            .mapNotNull(::rowToSerializableParcel)
            .toList()
    }


    override suspend fun setParcelData(parcelFor: Parcel, data: ParcelData?) {
        if (data == null) {
            transaction {
                getParcelId(parcelFor)?.let { id ->
                    ParcelsT.deleteIgnoreWhere() { ParcelsT.id eq id }

                    // Below should cascade automatically
                    /*
                    AddedLocalT.deleteIgnoreWhere { AddedLocalT.parcel_id eq id }
                    ParcelOptionsT.deleteIgnoreWhere(limit = 1) { ParcelOptionsT.parcel_id eq id }
                    */
                }

            }
            return
        }

        val id = transaction {
            val id = getOrInitParcelId(parcelFor)
            AddedLocalT.deleteIgnoreWhere { AddedLocalT.parcel_id eq id }
            id
        }

        setParcelOwner(parcelFor, data.owner)

        for ((uuid, status) in data.added) {
            val state = status.asBoolean
            setParcelPlayerState(parcelFor, uuid, state)
        }

        setParcelAllowsInteractInputs(parcelFor, data.allowInteractInputs)
        setParcelAllowsInteractInventory(parcelFor, data.allowInteractInventory)
    }

    override suspend fun setParcelOwner(parcelFor: Parcel, owner: ParcelOwner?) = transaction {
        val binaryUuid = owner?.uuid?.toByteArray()
        val name = owner?.name
        val time = owner?.let { DateTime.now() }

        val id = if (owner == null)
            getParcelId(parcelFor) ?: return@transaction
        else
            getOrInitParcelId(parcelFor)

        ParcelsT.update({ ParcelsT.id eq id }) {
            it[ParcelsT.owner_uuid] = binaryUuid
            it[ParcelsT.owner_name] = name
            it[ParcelsT.claim_time] = time
        }
    }

    override suspend fun setParcelPlayerState(parcelFor: Parcel, player: UUID, state: Boolean?) = transaction {
        val binaryUuid = player.toByteArray()!!

        if (state == null) {
            getParcelId(parcelFor)?.let { id ->
                AddedLocalT.deleteWhere { (AddedLocalT.parcel_id eq id) and (AddedLocalT.player_uuid eq binaryUuid) }
            }
            return@transaction
        }

        val id = getOrInitParcelId(parcelFor)
        AddedLocalT.upsert(AddedLocalT.parcel_id) {
            it[AddedLocalT.parcel_id] = id
            it[AddedLocalT.player_uuid] = binaryUuid
        }
    }

    override suspend fun setParcelAllowsInteractInventory(parcel: Parcel, value: Boolean): Unit = transaction {
        val id = getOrInitParcelId(parcel)
        /*ParcelOptionsT.upsert(ParcelOptionsT.parcel_id) {
            it[ParcelOptionsT.parcel_id] = id
            it[ParcelOptionsT.interact_inventory] = value
        }*/

        ParcelOptionsT.upsert(ParcelOptionsT.parcel_id) {
            it[ParcelOptionsT.parcel_id] = id
            it[ParcelOptionsT.interact_inventory] = value
        }
    }

    override suspend fun setParcelAllowsInteractInputs(parcel: Parcel, value: Boolean): Unit = transaction {
        val id = getOrInitParcelId(parcel)
        ParcelOptionsT.upsert(ParcelOptionsT.parcel_id) {
            it[ParcelOptionsT.parcel_id] = id
            it[ParcelOptionsT.interact_inputs] = value
        }
    }

    override suspend fun readGlobalPlayerStateData(owner: ParcelOwner): AddedData? {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override suspend fun setGlobalPlayerState(owner: ParcelOwner, player: UUID, state: Boolean?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    private fun rowToSerializableParcel(row: ResultRow): SerializableParcel? {
        val worldId = row[ParcelsT.world_id]
        val worldRow = WorldsT.select { WorldsT.id eq worldId }.firstOrNull()
            ?: return null

        val world = SerializableWorld(worldRow[WorldsT.name], worldRow[WorldsT.uid].toUUID())
        return SerializableParcel(world, Vec2i(row[ParcelsT.px], row[ParcelsT.pz]))
    }

    private fun rowToParcelData(row: ResultRow) = ParcelDataHolder().apply {
        owner = ParcelOwner.create(
            uuid = row[ParcelsT.owner_uuid]?.toUUID(),
            name = row[ParcelsT.owner_name],
            time = row[ParcelsT.claim_time]
        )

        val parcelId = row[ParcelsT.id]
        AddedLocalT.select { AddedLocalT.parcel_id eq parcelId }.forEach {
            val uuid = it[AddedLocalT.player_uuid].toUUID()!!
            val status = if (it[AddedLocalT.allowed_flag]) AddedStatus.ALLOWED else AddedStatus.BANNED
            setAddedStatus(uuid, status)
        }

        ParcelOptionsT.select { ParcelOptionsT.parcel_id eq parcelId }.firstOrNull()?.let {
            allowInteractInputs = it[ParcelOptionsT.interact_inputs]
            allowInteractInventory = it[ParcelOptionsT.interact_inventory]
        }
    }

}