Skip to content

Commit

Permalink
Couchbase collection support
Browse files Browse the repository at this point in the history
Add collection as additional definition to database information
  • Loading branch information
marco-wolf-ergon committed Jul 3, 2024
1 parent 3535156 commit c4f533c
Show file tree
Hide file tree
Showing 15 changed files with 151 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ enum Type {
Type type() default Type.READ_AND_WRITE;

String database() default "";

String collection() default "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,38 @@ object PersistenceConfig {
fun getDocument(
id: String,
dbName: String,
collection: String = "",
onlyInclude: List<String>? = null
): Map<String, Any>?

fun getDocuments(
ids: List<String>,
dbName: String,
collection: String = "",
onlyInclude: List<String>? = null
): List<Map<String, Any>?>

fun queryDoc(
dbName: String,
collection: String = "",
queryParams: Map<String, Any>,
limit: Int? = null,
onlyInclude: List<String>? = null
): List<Map<String, Any>>

@Throws(PersistenceException::class)
fun deleteDocument(id: String, dbName: String)
fun deleteDocument(
id: String,
dbName: String,
collection: String = ""
)

@Throws(PersistenceException::class)
fun upsertDocument(
document: MutableMap<String, Any>,
id: String?,
dbName: String
dbName: String,
collection: String = ""
): Map<String, Any>
}

Expand All @@ -40,30 +48,38 @@ object PersistenceConfig {
suspend fun getDocument(
id: String,
dbName: String,
collection: String = "",
onlyInclude: List<String>? = null
): Map<String, Any>?

suspend fun getDocuments(
ids: List<String>,
dbName: String,
collection: String = "",
onlyInclude: List<String>? = null
): List<Map<String, Any>>

suspend fun queryDoc(
dbName: String,
collection: String = "",
queryParams: Map<String, Any>,
limit: Int? = null,
onlyInclude: List<String>? = null
): List<Map<String, Any>>

@Throws(PersistenceException::class)
suspend fun deleteDocument(id: String, dbName: String)
suspend fun deleteDocument(
id: String,
dbName: String,
collection: String = ""
)

@Throws(PersistenceException::class)
suspend fun upsertDocument(
document: MutableMap<String, Any>,
id: String?,
dbName: String
dbName: String,
collection: String = ""
): Map<String, Any>
}

Expand Down
2 changes: 1 addition & 1 deletion crystal-map-couchbase-connector/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
compileOnly 'com.couchbase.lite:couchbase-lite-android:2.1.2'
compileOnly 'com.couchbase.lite:couchbase-lite-android:3.1.8'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation project(path: ':crystal-map-api')
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ package com.schwarz.crystalcouchbaseconnector
import com.couchbase.lite.*
import com.schwarz.crystalapi.PersistenceConfig
import com.schwarz.crystalapi.PersistenceException
import java.lang.IllegalStateException
import java.util.*
import kotlin.jvm.Throws

abstract class Couchbase2Connector : PersistenceConfig.Connector {

protected abstract fun getDatabase(name: String): Database

override fun getDocument(id: String, dbName: String, onlyInclude: List<String>?): Map<String, Any>? {
val document = getDatabase(dbName).getDocument(id) ?: return null
override fun getDocument(id: String, dbName: String, collection: String, onlyInclude: List<String>?): Map<String, Any>? {
val document = getDocument(id, dbName, collection) ?: return null

val result = document.toMap()
result["_id"] = id
Expand All @@ -21,18 +22,23 @@ abstract class Couchbase2Connector : PersistenceConfig.Connector {
override fun getDocuments(
ids: List<String>,
dbName: String,
collection: String,
onlyInclude: List<String>?
): List<Map<String, Any>?> =
ids.mapNotNull { docId ->
getDocument(docId, dbName)
getDocument(docId, dbName, collection, null)
}

@Throws(PersistenceException::class)
override fun deleteDocument(id: String, dbName: String) {
override fun deleteDocument(id: String, dbName: String, collection: String) {
try {
val document = getDatabase(dbName).getDocument(id)
val document = getDocument(id, dbName, collection)
if (document != null) {
getDatabase(dbName).delete(document)
if (collection.isEmpty()) {
getDatabase(dbName).delete(document)
} else {
getDatabase(dbName).getCollection(collection)?.delete(document)
}
}
} catch (e: CouchbaseLiteException) {
throw PersistenceException(e)
Expand All @@ -42,13 +48,24 @@ abstract class Couchbase2Connector : PersistenceConfig.Connector {
@Throws(PersistenceException::class)
override fun queryDoc(
dbName: String,
collection: String,
queryParams: Map<String, Any>,
limit: Int?,
onlyInclude: List<String>?
): List<Map<String, Any>> {
try {
val builder = QueryBuilder.select(SelectResult.expression(Meta.id), SelectResult.all())
.from(DataSource.database(getDatabase(dbName)))
val builder = QueryBuilder.select(SelectResult.expression(Meta.id), SelectResult.all()).let { select ->
if (collection.isEmpty()) {
select.from(DataSource.database(getDatabase(dbName)))
} else {
select.from(
DataSource.collection(
getDatabase(dbName).getCollection(collection)
?: throw IllegalStateException("Collection $collection not found for db $dbName")
)
)
}
}

parseExpressions(queryParams)?.let {
builder.where(it)
Expand All @@ -67,10 +84,9 @@ abstract class Couchbase2Connector : PersistenceConfig.Connector {
ArrayList()
if (execute != null) {
for (result in execute) {
val item: MutableMap<String, Any> =
HashMap()
item["_id"] = result.getString(0)
item.putAll(result.getDictionary(1).toMap())
val item: MutableMap<String, Any> = mutableMapOf()
item["_id"] = result.getString(0).orEmpty()
item.putAll(result.getDictionary(1)?.toMap() ?: emptyMap())
parsed.add(item)
}
}
Expand All @@ -95,18 +111,30 @@ abstract class Couchbase2Connector : PersistenceConfig.Connector {
}

@Throws(PersistenceException::class)
override fun upsertDocument(document: MutableMap<String, Any>, id: String?, dbName: String): Map<String, Any> {
override fun upsertDocument(document: MutableMap<String, Any>, id: String?, dbName: String, collection: String): Map<String, Any> {
if (document["_id"] == null && id != null) {
document["_id"] = id
}
val unsavedDoc = MutableDocument(id, document)
return try {
document["_id"] = unsavedDoc.id
unsavedDoc.setString("_id", unsavedDoc.id)
getDatabase(dbName).save(unsavedDoc)
if (collection.isEmpty()) {
getDatabase(dbName).save(unsavedDoc)
} else {
getDatabase(dbName).getCollection(collection)?.save(unsavedDoc)
?: throw IllegalStateException("Collection $collection not found for db $dbName")
}
document
} catch (e: CouchbaseLiteException) {
throw PersistenceException(e)
}
}

private fun getDocument(id: String, dbName: String, collection: String): Document? =
if (collection.isEmpty()) {
getDatabase(dbName).getDocument(id) ?: null
} else {
getDatabase(dbName).getCollection(collection)?.getDocument(id) ?: null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,16 @@ class CommonInterfaceGeneration {
}

for (fieldHolder in holder.allFields) {
typeBuilder.addProperty(fieldHolder.property(null, holder.abstractParts, false, holder.deprecated, typeConvertersByConvertedClass))
typeBuilder.addProperty(
fieldHolder.property(
dbName = null,
collection = null,
holder.abstractParts,
useMDocChanges = false,
holder.deprecated,
typeConvertersByConvertedClass
)
)
}

val companionSpec = TypeSpec.companionObjectBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ class EntityGeneration {
companionSpec.addFunction(findByIds(holder, useSuspend))

for (query in holder.queries) {
query.queryFun(holder.dbName, holder, useSuspend, typeConvertersByConvertedClass).let {
query.queryFun(
holder.dbName,
holder.collection,
holder,
useSuspend,
typeConvertersByConvertedClass
).let {
companionSpec.addFunction(it)
}
}
Expand All @@ -68,6 +74,7 @@ class EntityGeneration {
.addSuperinterface(holder.interfaceTypeName)
.addSuperinterface(MandatoryCheck::class)
.addProperty(holder.dbNameProperty())
.addProperty(holder.collectionProperty())
.addFunction(EnsureTypesGeneration.ensureTypes(holder, false, typeConvertersByConvertedClass))
.addFunction(CblDefaultGeneration.addDefaults(holder, false))
.addFunction(CblConstantGeneration.addConstants(holder, false))
Expand Down Expand Up @@ -111,6 +118,7 @@ class EntityGeneration {
for (fieldHolder in holder.allFields) {
fieldHolder.builderSetter(
holder.dbName,
holder.collection,
holder.sourcePackage,
holder.entitySimpleName,
true,
Expand All @@ -123,6 +131,7 @@ class EntityGeneration {
typeBuilder.addProperty(
fieldHolder.property(
holder.dbName,
holder.collection,
holder.abstractParts,
true,
holder.deprecated,
Expand Down Expand Up @@ -155,9 +164,10 @@ class EntityGeneration {
builder.addStatement("throw %T()", UnsupportedOperationException::class)
} else {
builder.addStatement(
"val result = %T.${getDocumentMethod(useSuspend)}(id, %S, %N)",
"val result = %T.${getDocumentMethod(useSuspend)}(id, %S, %S, %N)",
PersistenceConfig::class,
holder.dbName,
holder.collection,
CblReduceGeneration.PROPERTY_ONLY_INCLUDES
)
.addStatement(
Expand All @@ -178,9 +188,10 @@ class EntityGeneration {
builder.addStatement("throw %T()", UnsupportedOperationException::class)
} else {
builder.addStatement(
"val result = %T.${getDocumentsMethod(useSuspend)}(ids, %S, %N)",
"val result = %T.${getDocumentsMethod(useSuspend)}(ids, %S, %S, %N)",
PersistenceConfig::class,
holder.dbName,
holder.collection,
CblReduceGeneration.PROPERTY_ONLY_INCLUDES
)
.addStatement(
Expand All @@ -197,15 +208,20 @@ class EntityGeneration {
}

private fun toMap(holder: EntityHolder, useSuspend: Boolean): FunSpec {
var refreshDoc = "getId()?.let{%T.${getDocumentMethod(useSuspend)}(it, %S)} ?: mDoc"
var refreshDoc = "getId()?.let{%T.${getDocumentMethod(useSuspend)}(it, %S, %S)} ?: mDoc"

if (useSuspend) {
refreshDoc = "kotlinx.coroutines.runBlocking{$refreshDoc}"
}

val toMapBuilder = FunSpec.builder("toMap").addModifiers(KModifier.OVERRIDE)
.returns(TypeUtil.mutableMapStringAny())
.addStatement("val doc = $refreshDoc", PersistenceConfig::class, holder.dbName)
.addStatement(
"val doc = $refreshDoc",
PersistenceConfig::class,
holder.dbName,
holder.collection
)

for (constantField in holder.fieldConstants.values) {
toMapBuilder.addStatement(
Expand Down Expand Up @@ -248,9 +264,10 @@ class EntityGeneration {
builder.addStatement("throw %T()", UnsupportedOperationException::class)
} else {
builder.addStatement(
"getId()?.let{%T.${deleteDocumentMethod(useSuspend)}(it, %S)}",
"getId()?.let{%T.${deleteDocumentMethod(useSuspend)}(it, %S, %S)}",
PersistenceConfig::class,
holder.dbName
holder.dbName,
holder.collection
)
}
return builder.build()
Expand Down Expand Up @@ -279,9 +296,10 @@ class EntityGeneration {

saveBuilder.addStatement("val docId = $idResolve")
saveBuilder.addStatement(
"val upsertedDoc = %T.${upsertDocumentMethod(useSuspend)}(doc, docId, %S)",
"val upsertedDoc = %T.${upsertDocumentMethod(useSuspend)}(doc, docId, %S, %S)",
PersistenceConfig::class,
holder.dbName
holder.dbName,
holder.collection
)
saveBuilder.addStatement("rebind(upsertedDoc)")
}
Expand Down Expand Up @@ -310,10 +328,11 @@ class EntityGeneration {
return listOf(
FunSpec.builder("create").addModifiers(evaluateModifiers(useSuspend))
.addParameter("id", String::class).addAnnotation(JvmStatic::class).addStatement(
"return %N(%T.${getDocumentMethod(useSuspend)}(id, %S) ?: mutableMapOf(_ID to id))",
"return %N(%T.${getDocumentMethod(useSuspend)}(id, %S, %S) ?: mutableMapOf(_ID to id))",
holder.entitySimpleName,
PersistenceConfig::class,
holder.dbName
holder.dbName,
holder.collection
).returns(holder.entityTypeName).build(),
FunSpec.builder("create").addModifiers(KModifier.PUBLIC, KModifier.OVERRIDE)
.addAnnotation(JvmStatic::class).addStatement(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,24 @@ class WrapperGeneration {

for (fieldHolder in holder.allFields) {
companionSpec.addProperties(fieldHolder.createFieldConstant())
typeBuilder.addProperty(fieldHolder.property(null, holder.abstractParts, false, holder.deprecated, typeConvertersByConvertedClass))
fieldHolder.builderSetter(null, holder.sourcePackage, holder.entitySimpleName, false, holder.deprecated)?.let {
typeBuilder.addProperty(
fieldHolder.property(
dbName = null,
collection = null,
holder.abstractParts,
useMDocChanges = false,
holder.deprecated,
typeConvertersByConvertedClass
)
)
fieldHolder.builderSetter(
dbName = null,
collection = null,
holder.sourcePackage,
holder.entitySimpleName,
useMDocChanges = false,
holder.deprecated
)?.let {
builderBuilder.addFunction(it)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ object EntityFactory {
sourceModel,
EntityHolder(
annotation.database,
annotation.collection,
annotation.modifierOpen,
annotation.type,
sourceModel
Expand Down
Loading

0 comments on commit c4f533c

Please sign in to comment.