From df2416da4724687410da22636e5825a3bab8f34f Mon Sep 17 00:00:00 2001 From: cosmin-marginean Date: Sun, 12 May 2024 18:47:11 +0100 Subject: [PATCH] Add support for Java-based create indexes --- gradle.properties | 2 +- .../src/main/kotlin/invirt/mongodb/index.kt | 32 +++++++++++++++---- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/gradle.properties b/gradle.properties index c9ed7fc..e4066fb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -invirtVersion = 0.9.6 +invirtVersion = 0.9.8 kotlinVersion = 1.9.23 http4kVersion = 5.17.0.0 mockkVersion = 1.13.9 diff --git a/invirt-mongodb/src/main/kotlin/invirt/mongodb/index.kt b/invirt-mongodb/src/main/kotlin/invirt/mongodb/index.kt index 72e6ac2..f286a17 100644 --- a/invirt-mongodb/src/main/kotlin/invirt/mongodb/index.kt +++ b/invirt-mongodb/src/main/kotlin/invirt/mongodb/index.kt @@ -32,6 +32,30 @@ fun MongoCollection.createIndexes( clientSession: ClientSession? = null, build: IndexesBuilder.() -> Unit ) { + val indexes = buildIndexes(this.namespace.collectionName, build) + if (clientSession != null) { + createIndexes(clientSession, indexes) + } else { + createIndexes(indexes) + } +} + +/** + * For backwards compatibility with the Java driver + */ +fun com.mongodb.client.MongoCollection<*>.createIndexes( + clientSession: com.mongodb.client.ClientSession? = null, + build: IndexesBuilder.() -> Unit +) { + val indexes = buildIndexes(this.namespace.collectionName, build) + if (clientSession != null) { + createIndexes(clientSession, indexes) + } else { + createIndexes(indexes) + } +} + +private fun buildIndexes(collectionName: String, build: IndexesBuilder.() -> Unit): List { val indexesBuilder = IndexesBuilder() indexesBuilder.asc(StoredEntity::version) indexesBuilder.desc(StoredEntity::createdAt) @@ -40,16 +64,12 @@ fun MongoCollection.createIndexes( log.atInfo { message = "Creating indexes for collection" payload = mapOf( - "collection" to this@createIndexes.namespace.collectionName, + "collection" to collectionName, "count" to indexesBuilder.indexes.size, "indexes" to indexesBuilder.indexes.map { it.keys } ) } - if (clientSession != null) { - createIndexes(clientSession, indexesBuilder.indexes) - } else { - createIndexes(indexesBuilder.indexes) - } + return indexesBuilder.indexes } private fun indexOptions(caseInsensitive: Boolean): IndexOptions {