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

com.lightningkite.ktordb.QuerySet.kt Maven / Gradle / Ivy

The newest version!
package com.lightningkite.ktordb

import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import com.lightningkite.khrysalis.IsCodableAndHashableNotNull
import kotlin.reflect.KProperty1

data class QuerySet(
    val on: FieldCollection,
    val condition: Condition,
) : Flow {
    override suspend fun collect(collector: FlowCollector) {
        on.find(condition).collect(collector)
    }
}

data class SortedQuerySet(
    val on: FieldCollection,
    val condition: Condition,
    val orderBy: List>
) : Flow {
    override suspend fun collect(collector: FlowCollector) {
        on.find(condition, orderBy).collect(collector)
    }
}

data class SlicedSortedQuerySet(
    val on: FieldCollection,
    val condition: Condition,
    val orderBy: List>,
    val skip: Int,
    val limit: Int
) : Flow {
    override suspend fun collect(collector: FlowCollector) {
        on.find(condition, orderBy, skip, limit).collect(collector)
    }
}

fun  FieldCollection.filter(conditionMaker: (PropChain) -> Condition) =
    QuerySet(
        this, conditionMaker(
            startChain()
        )
    )

@Suppress("UNCHECKED_CAST")
private fun > PropChain.field(): KProperty1 =
    (mapCondition(Condition.Always()) as Condition.OnField).key as KProperty1

fun  QuerySet.filter(conditionMaker: (PropChain) -> Condition) =
    copy(on, condition and conditionMaker(startChain()))

fun  SortedQuerySet.filter(conditionMaker: (PropChain) -> Condition) =
    copy(on, condition and conditionMaker(startChain()))

fun > QuerySet.sortedBy(field: KProperty1) =
    SortedQuerySet(on, condition, orderBy = listOf(SortPart(field)))

fun > QuerySet.sortedBy(field: (PropChain) -> PropChain) =
    SortedQuerySet(on, condition, orderBy = listOf(SortPart(field(startChain()).field())))

fun > QuerySet.sortedByDescending(field: KProperty1) =
    SortedQuerySet(on, condition, orderBy = listOf(SortPart(field, ascending = false)))

fun > QuerySet.sortedByDescending(field: (PropChain) -> PropChain) =
    SortedQuerySet(on, condition, orderBy = listOf(SortPart((field(startChain()).field()), ascending = false)))

fun  SortedQuerySet.take(count: Int) =
    SlicedSortedQuerySet(on, condition, orderBy, skip = 0, limit = count)

fun  SortedQuerySet.drop(count: Int) =
    SlicedSortedQuerySet(on, condition, orderBy, skip = count, limit = Int.MAX_VALUE)

fun  SlicedSortedQuerySet.take(count: Int) = copy(limit = limit + count)
fun  SlicedSortedQuerySet.drop(count: Int) = copy(skip = skip + count)




© 2015 - 2024 Weber Informatics LLC | Privacy Policy