package solutions.bitbadger.documents.query import solutions.bitbadger.documents.* /** * Functions to create `WHERE` clause fragments */ object Where { /** * Create a `WHERE` clause fragment to query by one or more fields * * @param fields The fields to be queried * @param howMatched How the fields should be matched (optional, defaults to `ALL`) * @return A `WHERE` clause fragment to match the given fields */ fun byFields(fields: Collection>, howMatched: FieldMatch? = null) = fields.joinToString(" ${(howMatched ?: FieldMatch.ALL).sql} ") { it.toWhere() } /** * Create a `WHERE` clause fragment to retrieve a document by its ID * * @param parameterName The parameter name to use for the ID placeholder (optional, defaults to ":id") * @param docId The ID value (optional; used for type determinations, string assumed if not provided) */ fun byId(parameterName: String = ":id", docId: TKey? = null) = byFields(listOf(Field.equal(Configuration.idField, docId ?: "", parameterName))) /** * Create a `WHERE` clause fragment to implement a JSON containment query (PostgreSQL only) * * @param parameterName The parameter name to use for the JSON placeholder (optional, defaults to ":criteria") * @return A `WHERE` clause fragment to implement a JSON containment criterion * @throws DocumentException If called against a SQLite database */ fun jsonContains(parameterName: String = ":criteria") = when (Configuration.dialect("create containment WHERE clause")) { Dialect.POSTGRESQL -> "data @> $parameterName" Dialect.SQLITE -> throw DocumentException("JSON containment is not supported") } /** * Create a `WHERE` clause fragment to implement a JSON path match query (PostgreSQL only) * * @param parameterName The parameter name to use for the placeholder (optional, defaults to ":path") * @return A `WHERE` clause fragment to implement a JSON path match criterion * @throws DocumentException If called against a SQLite database */ fun jsonPathMatches(parameterName: String = ":path") = when (Configuration.dialect("create JSON path match WHERE clause")) { Dialect.POSTGRESQL -> "jsonb_path_exists(data, $parameterName::jsonpath)" Dialect.SQLITE -> throw DocumentException("JSON path match is not supported") } }