diff --git a/LOGICAL_GROUP_EXAMPLE.md b/LOGICAL_GROUP_EXAMPLE.md new file mode 100644 index 0000000..360b828 --- /dev/null +++ b/LOGICAL_GROUP_EXAMPLE.md @@ -0,0 +1,281 @@ +# Implementación de Agrupación de Condiciones AND / OR + +## Descripción + +Se ha implementado la agrupación de condiciones para las clases `QuerySelect` y `QueryDelete`, +permitiendo emitir grupos parentizados `AND (...)` y `OR (...)` dentro de una cláusula `WHERE`. + +El problema que resuelve la feature es de precedencia. Las condiciones se encadenaban en un único +nivel con `joinToString(" ")`, de modo que un `OR` agregado al final de una cadena de `AND` se +interpretaba como `(a AND b) OR (...)` en lugar de `a AND b AND (...)`. La biblioteca no contaba con +ninguna API para expressing esa intención. + +## Características implementadas + +1. **`LogicalOperation.Multiple` corregido** (`operator/LogicalOperation.kt`): + - `asString()` ahora usa `asConditionString()` —que delega en `SQLOperator.toSQLString()`— para + la primera condición del grupo, por lo que los valores `String` conservan sus comillas. Antes + usaba `asString()`, que las eliminaba. + - La primera condición ya no pierde su conector cuando el grupo se anida. + - `operations` no puede ser una lista vacía; el constructor lanza `IllegalArgumentException`. + - `symbol` solo admite `AND` u `OR`. Cualquier otro valor lanza `IllegalArgumentException` en + lugar de emitir un conector arbitrario. + - Nuevo constructor `vararg`: `Multiple(Or(a), Or(b))`. + - `operators()` y `sqlOperators()` recorren los grupos anidados y devuelven todos los operadores + en profundidad. + +2. **Renderizado de la posición `WHERE`**: una operación puede.renderizarse sin su conector para + ocupar el ancla de la cláusula. Un grupo en esa posición emite `WHERE (a OR b)` en lugar del + inválido `WHERE AND (a OR b)`. + +3. **Filtering recursivo** (`filterBy`): `asSql(predicate)` entra dentro de los grupos y conserva + las condiciones que el predicado acepta, en lugar de descartar el grupo completo por una sola + condición. Si el `WHERE` no sobrevive al filtro, la primera condición restante asciende a la + posición de `WHERE`, de modo que la sentencia nunca empieza con un conector colgante. + +4. **Builders con grupos** (`QuerySelect.QueryBuilder` y `QueryDelete.QueryBuilder`): + - `andGroup(key, vararg conditions)`: adjunta el grupo a la cadena con `AND`. + - `orGroup(key, vararg conditions)`: adjunta el grupo a la cadena con `OR`. + - `andGroup(key, connector, vararg conditions)` y `orGroup(key, connector, vararg conditions)`: + atajo que aplica [connector] entre las condiciones internas sin envolver cada una en + `LogicalOperation`. + +5. **`andGroup()` / `orGroup()` en las instancias** de `QuerySelect` y `QueryDelete`, con las mismas + cuatro sobrecargas, para agregar un grupo sobre una query ya construida sin pasar por + `newBuilder`. + +6. **`QueryDelete.QueryBuilder.addLogicalOperation(key, operation)`**: se agregó para mantener + paridad con `QuerySelect.QueryBuilder` y con la instancia de `QueryDelete`, que ya lo exponía. + +7. **`copyOperation` sobre grupos** (`utils/Extensions.kt`): reemplaza el operador de la primera + condición **no agrupada**, descendiendo en los grupos anidados. Reemplazar el primer elemento + anidaba un grupo dentro de otro y emitía un conector inválido como `AND (OR (a OR b))`. + +8. **`getSqlOperators()` y `getOperators()`** de `QuerySelect` y `QueryDelete` devuelven todos los + operadores de los grupos, no solo el primero, de modo que la serialización hacia + `RepeatedQueryParameters` ya no pierde condiciones. `getOperations()` sigue devolviendo un + operador representativo por clave, porque su valor es un `SQLOperator` y no admite listas. + +## Semántica de los símbolos + +El símbolo del grupo define **cómo se conecta** el grupo a la cláusula que lo contiene. El símbolo de +cada condición define **cómo se combina con la anterior dentro** del grupo. Esa separación es la que +permite expresar `AND (a OR b OR c)` y `OR (a AND b AND c)` con la misma primitiva. + +## Ejemplos de uso + +### Búsqueda con varios campos y precedencia AND / OR +```kotlin +val query = QuerySelect.builder("tire_transfer_document") + .where(SQLOperator.Equals("creator", 1)) + .and("status", SQLOperator.Equals("status", 1)) + .and("responsible", SQLOperator.NotEquals("responsible", 1)) + .andGroup( + "search", + LogicalType.OR, + SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER), + SQLOperator.Like("terminal_source_display", "cal", CaseConversion.LOWER), + SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER) + ) + .build() + +// Genera: +// SELECT * FROM tire_transfer_document WHERE creator = 1 AND status = 1 AND responsible != 1 +// AND (LOWER(doc_number) LIKE LOWER('%cal%') +// OR LOWER(terminal_source_display) LIKE LOWER('%cal%') +// OR LOWER(terminal_dest_display) LIKE LOWER('%cal%')) +``` + +Sin el grupo, la versión con `or()` produciría `... AND responsible != 1 OR (...)`, que SQL resuelve +como `(creator = 1 AND status = 1 AND responsible != 1) OR (...)`. + +### Grupo con conectores internos mixtos +Cuando las condiciones internas no comparten conector, se pasan como `LogicalOperation`: +```kotlin +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("id", 1)) + .andGroup( + "combo", + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.And(SQLOperator.GreaterThan("age", 18)) + ) + .build() + +// SELECT * FROM users WHERE id = 1 AND (role = 'admin' AND age > 18) +``` + +### Grupo conectado con OR +```kotlin +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .orGroup( + "role", + LogicalOperation.And(SQLOperator.Equals("role", "admin")), + LogicalOperation.And(SQLOperator.Equals("role", "root")) + ) + .build() + +// Genera: SELECT * FROM users WHERE status = 'active' OR (role = 'admin' AND role = 'root') +``` + +### Grupo conectado con AND +```kotlin +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("id", 1)) + .andGroup( + "range", + LogicalOperation.And(SQLOperator.GreaterThan("age", 18)), + LogicalOperation.And(SQLOperator.LessThan("age", 65)) + ) + .build() + +// Genera: SELECT * FROM users WHERE id = 1 AND (age > 18 AND age < 65) +``` + +### Grupos anidados +```kotlin +val group = LogicalOperation.Multiple( + listOf( + LogicalOperation.And(SQLOperator.Equals("status", "active")), + LogicalOperation.Multiple( + listOf( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ), + LogicalType.OR.sql + ) + ), + LogicalType.AND.sql +) + +// Genera: AND (status = 'active' OR (role = 'admin' OR role = 'root')) +``` + +### DELETE con grupo +```kotlin +val query = QueryDelete.builder("sessions") + .where(SQLOperator.LessThan("expires_at", now)) + .andGroup( + "stale", + LogicalType.OR, + SQLOperator.IsNull("refreshed_at"), + SQLOperator.LessThan("refreshed_at", threshold) + ) + .build() + +// Genera: +// DELETE FROM sessions WHERE expires_at < 1700000000 +// AND (refreshed_at IS NULL OR refreshed_at < 1600000000) +``` + +### Grupo como ancla de WHERE +```kotlin +val query = QuerySelect.builder("users") + .where( + "search", + LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ) + ) + .and("status", SQLOperator.Equals("status", "active")) + .build() + +// Genera: SELECT * FROM users WHERE (role = 'admin' OR role = 'root') AND status = 'active' +``` + +### Grupo agregado sobre una query ya construida +```kotlin +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .build() + +query.andGroup("search", LogicalType.OR, SQLOperator.Equals("role", "admin")) + +// Genera: SELECT * FROM users WHERE status = 'active' AND (role = 'admin') +``` + +### Filtering dentro del grupo +```kotlin +val query = QuerySelect.builder("tire_transfer_document") + .where(SQLOperator.Equals("creator", 1)) + .andGroup( + "search", + LogicalType.OR, + SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER), + SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER) + ) + .build() + +query.asSql { it.column != "terminal_dest_display" } +// SELECT * FROM tire_transfer_document WHERE creator = 1 +// AND (LOWER(doc_number) LIKE LOWER('%cal%')) +``` + +### Inspección del contenido de un grupo +```kotlin +val group = LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal")), + LogicalOperation.Or(SQLOperator.Equals("terminal_dest_display", "cal")) +) + +group.operators().map { it.toPair() } +// [(doc_number, cal), (terminal_dest_display, cal)] +``` + +## Validaciones implementadas + +- `Multiple` requiere al menos una operación; una lista vacía lanza `IllegalArgumentException` en el + momento de la construcción y no en el momento de generar el SQL. +- `Multiple` solo admite `AND` u `OR` como conector. `WHERE`, `EXISTS` o cualquier cadena arbitraria + lanzan `IllegalArgumentException` en lugar de emitir SQL inválido. +- `andGroup` y `orGroup` delegan esas validaciones: llamar `andGroup("search")` sin condiciones lanza + `IllegalArgumentException`. +- El grupo se registra en el mismo `LinkedHashMap` que el resto de las + condiciones, por lo que `remove(key)`, la sobreescritura por clave duplicada y el orden de emisión + funcionan igual que con una condición simple. + +## Tests + +`query/src/test/java/com/blipblipcode/query/LogicalGroupTest.kt` cubre: + +- El caso de búsqueda de múltiples campos con precedencia AND / OR. +- La conexión del grupo con `AND` y con `OR`, y el atajo con conector interno tipado. +- El renderizado de valores `String` con comillas dentro del grupo. +- El anidamiento de grupos y el recorrido de sus operadores. +- El filtrado por `predicate` dentro del grupo, la desaparición del grupo vacío y la promoción de + la primera condición superviviente cuando el `WHERE` no pasa el filtro, en SELECT y en DELETE. +- El grupo usado como ancla de `WHERE`, renderizado sin conector colgante. +- La inspección del contenido con `operators()` y con `getSqlOperators()`. +- Los `IllegalArgumentException` por grupo vacío y por conector inválido. +- La invariancia del renderizado plano cuando no hay grupos. +- El clonado profundo al copiar la consulta y el reemplazo de la primera hoja en `copyOperation`. +- La eliminación de un grupo por clave con `remove(key)`. +- El agregado de grupos sobre una instancia ya construida. + +## Orden de ejecución SQL + +La implementación no altera el orden de las cláusulas: + +1. SELECT campos +2. FROM tabla +3. WHERE condición principal + grupos y condiciones +4. ORDER BY (si existe) +5. LIMIT (si existe) + +## Compatibilidad + +No hay cambios de comportamiento para las consultas existentes. El renderizado de una cadena de +condiciones sin grupos sigue siendo plano, exactamente igual que antes, por lo que ninguna consulta +generada previamente cambia de string. `LogicalOperation.Multiple` no tenía cobertura de tests ni +call sites de producción antes de esta feature, y su renderizado anterior emitía SQL inválido +(valores `String` sin comillas), de modo que corregirlo no puede afectar a un consumidor que +dependiera de ese output. + +Los dos comportamientos corregidos que sí cambian el resultado, ambos casos de SQL inválido o pérdida +silenciosa de condiciones, solo eran alcanzables a través de `Multiple` o del overload de `predicate`: + +- `asSql(predicate)` ya no descarta un grupo entero por una sola condición rechazada, y ya no deja + una sentencia empezando por un conector colgante cuando el `WHERE` es filtrado. +- `getSqlOperators()` ya no expone un solo operador por grupo, lo que afecta a + `asQueryRepeatedQueryParameters()` de las consultas con grupos. \ No newline at end of file diff --git a/README.md b/README.md index 465eed0..05d736c 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Diseñada para integrarse perfectamente con la base de datos de Android y Room a - [🔗 Integración con Room](#-integración-con-room) - [📡 Integración con retrofit -> RepeatedQueryParameters](#-repeatedqueryparameters) - [📝 Ejemplos Avanzados](#-ejemplos-avanzados) + - [Agrupación de condiciones AND / OR](#-agrupación-de-condiciones-and--or) - [🤝 Contribuir](#-contribuir) --- @@ -49,6 +50,7 @@ Diseñada para integrarse perfectamente con la base de datos de Android y Room a - 🔄 **Joins Complejos**: Soporte para `INNER JOIN` - ⚡ **Operadores SQL**: Amplia gama de operadores (`=`, `!=`, `>`, `<`, `LIKE`, `IN`, `BETWEEN`, `IS NULL`, etc.) - 🧩 **Condiciones Lógicas**: Combina cláusulas fácilmente con `AND` y `OR` +- 🔒 **Agrupación de Condiciones**: Encapsula condiciones en grupos `AND (...)` / `OR (...)` para evitar fugas de precedencia - 🏛️ **Integración con Room**: Conversión directa a `SupportSQLiteQuery` con la función de extensión `asSQLiteQuery()` - 💯 **100% Kotlin**: Código moderno, idiomático y nulo-seguro @@ -376,6 +378,119 @@ val bulkUpdate = QueryUpdate.builder("inventory") .build() ``` +### Agrupación de condiciones AND / OR + +Las condiciones se encadenan en un solo nivel. Por eso un `OR` agregado al final **no** queda +ligado al `AND` anterior: en SQL `AND` tiene mayor precedencia que `OR`, así que + +```kotlin +// ⛔ NO hagas esto: el AND se interpreta como (creator = 1 AND status = 1) OR (...) +val broken = QuerySelect.builder("tire_transfer_document") + .where(SQLOperator.Equals("creator", 1)) + .and("status", SQLOperator.Equals("status", 1)) + .or("doc_number", SQLOperator.Like("doc_number", "cal")) + .or("terminal_dest_display", SQLOperator.Like("terminal_dest_display", "cal")) + .build() +``` + +Para expresses esa intención usá `andGroup` / `orGroup`. Cada condición del grupo conserva su propio +conector, y el símbolo del grupo define **cómo se conecta** el grupo a la cadena: + +```kotlin +val query = QuerySelect.builder("tire_transfer_document") + .where(SQLOperator.Equals("creator", 1)) + .and("status", SQLOperator.Equals("status", 1)) + .andGroup( + "search", + LogicalOperation.Or(SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_source_display", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER)) + ) + .build() + +// SELECT * FROM tire_transfer_document WHERE creator = 1 AND status = 1 +// AND (LOWER(doc_number) LIKE LOWER('%cal%') +// OR LOWER(terminal_source_display) LIKE LOWER('%cal%') +// OR LOWER(terminal_dest_display) LIKE LOWER('%cal%')) +``` + +`orGroup` hace lo inverso: conecta el grupo con `OR` a la cadena. + +```kotlin +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .orGroup( + "role", + LogicalOperation.And(SQLOperator.Equals("role", "admin")), + LogicalOperation.And(SQLOperator.Equals("role", "root")) + ) + .build() + +// SELECT * FROM users WHERE status = 'active' OR (role = 'admin' AND role = 'root') +``` + +Cuando todas las condiciones internas comparten el mismo conector, usá la sobrecarga con +`LogicalType` y evitás envolver cada una en `LogicalOperation`: + +```kotlin +// andGroup("search", LogicalType.OR, like1, like2) -> AND (like1 OR like2) +val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .andGroup( + "search", + LogicalType.OR, + SQLOperator.Like("doc_number", "cal"), + SQLOperator.Like("terminal_dest_display", "cal") + ) + .build() + +// SELECT * FROM users WHERE status = 'active' +// AND (doc_number LIKE '%cal%' OR terminal_dest_display LIKE '%cal%') +``` + +Un grupo también puede ocupar la posición de `WHERE`, en cuyo caso se emite sin su conector: + +```kotlin +QuerySelect.builder("users") + .where( + "search", + LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ) + ) + .and("status", SQLOperator.Equals("status", "active")) + .build() + +// SELECT * FROM users WHERE (role = 'admin' OR role = 'root') AND status = 'active' +``` + +Los grupos funcionan en `QueryDelete`, se pueden anidar entre sí y se pueden agregar sobre una query +ya construida con los mismos métodos. Para inspeccionar o transformar un grupo usá +`Multiple.operators()`, que devuelve todos los operadores del grupo —incluidos los de grupos +anidados— en orden. + +```kotlin +val query = QueryDelete.builder("sessions") + .where(SQLOperator.LessThan("expires_at", now)) + .andGroup( + "stale", + LogicalType.OR, + SQLOperator.IsNull("refreshed_at"), + SQLOperator.LessThan("refreshed_at", threshold) + ) + .build() + +// DELETE FROM sessions WHERE expires_at < 1700000000 +// AND (refreshed_at IS NULL OR refreshed_at < 1600000000) +``` + +`asSql(predicate)` **entra dentro de los grupos**: conserva las condiciones que el predicado acepta +y descarta solo las que rechaza. Si ninguna sobrevive, el grupo desaparece; si el `WHERE` no +sobrevive, la primera condición restante asciende a la posición de `WHERE` para que la sentencia +nunca empiece con un conector colgante. `getSqlOperators()` (y por lo tanto +`asQueryRepeatedQueryParameters()`) devuelve todos los operadores del grupo, no solo el primero. + --- ## 🤝 Contribuir diff --git a/build.gradle.kts b/build.gradle.kts index 3dcdfbd..675854f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,4 +5,4 @@ plugins { alias(libs.plugins.android.library) apply false } -version = "0.13.6" +version = "0.14.0" diff --git a/query/src/main/java/com/blipblipcode/query/QueryDelete.kt b/query/src/main/java/com/blipblipcode/query/QueryDelete.kt index 23f2ea4..82b6e35 100644 --- a/query/src/main/java/com/blipblipcode/query/QueryDelete.kt +++ b/query/src/main/java/com/blipblipcode/query/QueryDelete.kt @@ -1,7 +1,9 @@ package com.blipblipcode.query import com.blipblipcode.query.operator.LogicalOperation +import com.blipblipcode.query.operator.LogicalType import com.blipblipcode.query.operator.SQLOperator +import com.blipblipcode.query.operator.logicalGroup /** * Represents a SQL DELETE statement. @@ -68,11 +70,63 @@ class QueryDelete private constructor( return this } + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND. + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The current `QueryDelete` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, vararg conditions: LogicalOperation): QueryDelete { + operations[key] = logicalGroup(LogicalType.AND, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND, linking the + * conditions inside the group with [connector]. + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The current `QueryDelete` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryDelete { + operations[key] = logicalGroup(LogicalType.AND, connector, conditions) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR. + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The current `QueryDelete` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, vararg conditions: LogicalOperation): QueryDelete { + operations[key] = logicalGroup(LogicalType.OR, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR, linking the + * conditions inside the group with [connector]. + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The current `QueryDelete` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryDelete { + operations[key] = logicalGroup(LogicalType.OR, connector, conditions) + return this + } + override fun getSqlOperators(): List> { return buildList { require(where != null) { "A WHERE clause must be specified." } - add(where!!.second.operator) - operations.values.forEach { add(it.operator) } + addAll(where!!.second.sqlOperators()) + operations.values.forEach { addAll(it.sqlOperators()) } } } @@ -91,18 +145,28 @@ class QueryDelete private constructor( */ override fun asSql(): String { require(where != null) { "A WHERE clause must be specified." } - return "DELETE FROM $table ${where!!.second.asString()} ${operations.values.joinToString(" ") { it.asString() }}".trim() + return "DELETE FROM $table ${where!!.second.asWhereString()} ${operations.values.joinToString(" ") { it.asString() }}".trim() } /** * Generates the SQL string for the DELETE statement. + * + * The predicate descends into grouped conditions, so a group keeps the conditions the predicate + * accepts instead of being dropped as a whole. When the WHERE clause does not survive the + * filter, the first surviving condition is promoted to the WHERE position so the statement + * never starts with a dangling connector. + * * @param predicate The predicate to filter the operators. * @return The complete DELETE SQL query as a string. * @throws IllegalArgumentException if the WHERE clause is not set. */ override fun asSql(predicate: (SQLOperator<*>) -> Boolean): String { require(where != null) { "A WHERE clause must be specified." } - return "DELETE FROM $table ${where!!.second.asString()} ${operations.values.filter { predicate(it.operator) }.joinToString(" ") { it.asString() }}".trim() + val anchor = where!!.second.filterBy(predicate) + val retained = operations.values.mapNotNull { it.filterBy(predicate) } + val whereClause = anchor ?: retained.firstOrNull() ?: return "DELETE FROM $table" + val trailing = if (anchor != null) retained else retained.drop(1) + return "DELETE FROM $table ${whereClause.asWhereString()} ${trailing.joinToString(" ") { it.asString() }}".trim() } /** @@ -207,6 +271,70 @@ class QueryDelete private constructor( return this } + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND. + * + * The group renders as `AND ( ...)`, where each condition keeps its own + * connector. Combining it with `LogicalOperation.Or` entries builds + * `AND (a OR b OR c)` without the ORs escaping the preceding AND conditions. + * + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, vararg conditions: LogicalOperation): QueryBuilder { + operations[key] = logicalGroup(LogicalType.AND, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND, linking + * the conditions inside the group with [connector]. + * + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryBuilder { + operations[key] = logicalGroup(LogicalType.AND, connector, conditions) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR. + * + * The group renders as `OR ( ...)`, where each condition keeps its own + * connector. Combining it with `LogicalOperation.And` entries builds + * `OR (a AND b AND c)` without the group leaking into the surrounding chain. + * + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, vararg conditions: LogicalOperation): QueryBuilder { + operations[key] = logicalGroup(LogicalType.OR, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR, linking + * the conditions inside the group with [connector]. + * + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryBuilder { + operations[key] = logicalGroup(LogicalType.OR, connector, conditions) + return this + } + /** * Removes a condition by its key. * @param key The key of the condition to remove. @@ -227,6 +355,30 @@ class QueryDelete private constructor( return this } + /** + * Sets the main WHERE clause from an already built logical operation, preserving it as is. + * Use this overload to carry over a grouped clause without unwrapping it into its first + * operator. + * @param key The key the clause is registered under. + * @param operation The logical operation to use as the WHERE clause. + * @return The `QueryBuilder` instance for chaining. + */ + fun where(key: String, operation: LogicalOperation): QueryBuilder { + where = key to operation + return this + } + + /** + * Adds a logical operation, overwriting any previous operation registered under [key]. + * @param key A unique key for the logical operation. + * @param operation The logical operation to add. + * @return The `QueryBuilder` instance for chaining. + */ + fun addLogicalOperation(key: String, operation: LogicalOperation): QueryBuilder { + operations[key] = operation + return this + } + /** * Builds the `QueryDelete` instance. * @return A new `QueryDelete` object. diff --git a/query/src/main/java/com/blipblipcode/query/QuerySelect.kt b/query/src/main/java/com/blipblipcode/query/QuerySelect.kt index 6d14844..c8e2700 100644 --- a/query/src/main/java/com/blipblipcode/query/QuerySelect.kt +++ b/query/src/main/java/com/blipblipcode/query/QuerySelect.kt @@ -2,8 +2,10 @@ package com.blipblipcode.query import com.blipblipcode.query.operator.Limit import com.blipblipcode.query.operator.LogicalOperation +import com.blipblipcode.query.operator.LogicalType import com.blipblipcode.query.operator.OrderBy import com.blipblipcode.query.operator.SQLOperator +import com.blipblipcode.query.operator.logicalGroup /** * Represents a SQL SELECT statement. @@ -114,6 +116,58 @@ class QuerySelect private constructor( return this } + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND. + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The current `QuerySelect` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, vararg conditions: LogicalOperation): QuerySelect { + operations[key] = logicalGroup(LogicalType.AND, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND, linking the + * conditions inside the group with [connector]. + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The current `QuerySelect` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QuerySelect { + operations[key] = logicalGroup(LogicalType.AND, connector, conditions) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR. + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The current `QuerySelect` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, vararg conditions: LogicalOperation): QuerySelect { + operations[key] = logicalGroup(LogicalType.OR, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR, linking the + * conditions inside the group with [connector]. + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The current `QuerySelect` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QuerySelect { + operations[key] = logicalGroup(LogicalType.OR, connector, conditions) + return this + } + /** * Returns a new `QuerySelect` instance with the specified fields. * @param newFields The names of the columns to select. If empty, selects all columns ("*"). @@ -135,15 +189,15 @@ class QuerySelect private constructor( override fun getSqlOperators(): List> { return buildList { - where?.let { add(it.second.operator) } - operations.values.forEach { add(it.operator) } + where?.let { addAll(it.second.sqlOperators()) } + operations.values.forEach { addAll(it.sqlOperators()) } orderBy?.let { add(it) } limit?.let { add(it) } } } fun getOperators(): List> { - return operations.values.map { it.operator } + return operations.values.flatMap { it.sqlOperators() } } fun getOperations(): Map> { @@ -175,7 +229,7 @@ class QuerySelect private constructor( if (where == null) { append("SELECT $fieldStr FROM $table") } else { - append("SELECT $fieldStr FROM $table ${where?.second?.asString()} $operationsStr".trim()) + append("SELECT $fieldStr FROM $table ${where?.second?.asWhereString()} $operationsStr".trim()) } if (orderBy != null) { append(" ") @@ -190,20 +244,28 @@ class QuerySelect private constructor( /** * Generates the SQL string for the SELECT statement. + * + * The predicate descends into grouped conditions, so a group keeps the conditions the predicate + * accepts instead of being dropped as a whole. When the WHERE clause does not survive the + * filter, the first surviving condition is promoted to the WHERE position so the statement + * never starts with a dangling connector. + * * @param predicate The predicate to filter the operators. * @return The complete SELECT SQL query as a string. */ override fun asSql(predicate: (SQLOperator<*>) -> Boolean): String { val fieldStr = if (fields.isEmpty()) "*" else fields.joinToString(", ") - val filteredWhere = where?.takeIf { predicate(it.second.operator) } - val operationsStr = - if (operations.isNotEmpty()) operations.values.filter { predicate(it.operator) } - .joinToString(" ") { it.asString() } else "" + val anchor = where?.second?.filterBy(predicate) + val retained = operations.values.mapNotNull { it.filterBy(predicate) } + val whereClause = anchor ?: retained.firstOrNull() + val trailing = if (anchor != null) retained else retained.drop(1) return buildString { - if (filteredWhere == null) { + if (whereClause == null) { append("SELECT $fieldStr FROM $table") } else { - append("SELECT $fieldStr FROM $table ${filteredWhere.second.asString()} $operationsStr".trim()) + append( + "SELECT $fieldStr FROM $table ${whereClause.asWhereString()} ${trailing.joinToString(" ") { it.asString() }}".trim() + ) } orderBy?.takeIf { predicate(it) }?.let { append(" ") @@ -277,7 +339,7 @@ class QuerySelect private constructor( require(where != null) { "QuerySelect must have a WHERE clause to be converted to QueryDelete" } val deleteQuery = QueryDelete.builder(getTableName()) - .where(where!!.second.operator) + .where(where!!.first, where!!.second) .build() operations.forEach { (key, operation) -> @@ -422,6 +484,74 @@ class QuerySelect private constructor( return this } + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND. + * + * The group renders as `AND ( ...)`, where each condition keeps its own + * connector. Combining it with `LogicalOperation.Or` entries builds + * `AND (a OR b OR c)` without the ORs escaping the preceding AND conditions. + * + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, vararg conditions: LogicalOperation): QueryBuilder { + operations[key] = logicalGroup(LogicalType.AND, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with AND, linking + * the conditions inside the group with [connector]. + * + * This is the shortcut for the common "apply every filter but let the term match any of + * these columns" shape: `andGroup("search", LogicalType.OR, like1, like2)` renders + * `AND (like1 OR like2)` without spelling out a `LogicalOperation.Or` per condition. + * + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun andGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryBuilder { + operations[key] = logicalGroup(LogicalType.AND, connector, conditions) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR. + * + * The group renders as `OR ( ...)`, where each condition keeps its own + * connector. Combining it with `LogicalOperation.And` entries builds + * `OR (a AND b AND c)` without the group leaking into the surrounding chain. + * + * @param key A unique key for this condition. + * @param conditions The logical operations to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, vararg conditions: LogicalOperation): QueryBuilder { + operations[key] = logicalGroup(LogicalType.OR, conditions.toList()) + return this + } + + /** + * Adds a parenthesized group of conditions attached to the WHERE clause with OR, linking + * the conditions inside the group with [connector]. + * + * @param key A unique key for this condition. + * @param connector The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The `QueryBuilder` instance for chaining. + * @throws IllegalArgumentException if [conditions] is empty. + */ + fun orGroup(key: String, connector: LogicalType, vararg conditions: SQLOperator<*>): QueryBuilder { + operations[key] = logicalGroup(LogicalType.OR, connector, conditions) + return this + } + /** * Removes a condition by its key. * @param key The key of the condition to remove. diff --git a/query/src/main/java/com/blipblipcode/query/operator/LogicalOperation.kt b/query/src/main/java/com/blipblipcode/query/operator/LogicalOperation.kt index 8f0e828..28cd3a3 100644 --- a/query/src/main/java/com/blipblipcode/query/operator/LogicalOperation.kt +++ b/query/src/main/java/com/blipblipcode/query/operator/LogicalOperation.kt @@ -1,7 +1,5 @@ package com.blipblipcode.query.operator -import kotlin.collections.forEachIndexed - /** * Represents a logical operation in a SQL query, combining a [LogicalType] with a [SQLOperator]. @@ -80,27 +78,77 @@ sealed interface LogicalOperation: Copyable { return All(operator.clone()) } } - @Suppress("UNCHECKED_CAST") - data class Multiple(val operations: List, override val symbol: String = "AND") : LogicalOperation { + + /** + * Groups several [LogicalOperation] into a single parenthesized unit so it can be appended to + * a WHERE clause without its inner connectors leaking into the surrounding chain. + * + * [symbol] defines how the group attaches to the enclosing clause, while every grouped + * operation keeps its own connector internally. For example, + * `Multiple(listOf(Or(a), Or(b)), LogicalType.AND.sql)` renders as `AND (a OR b)`, so the ORs + * cannot escape the preceding AND conditions the way a flat `joinToString(" ")` would allow. + * + * @property operations The grouped operations, at least one. + * @property symbol The connector used to attach the group to the enclosing clause. + * @throws IllegalArgumentException if [operations] is empty or [symbol] is not a connector. + */ + data class Multiple( + val operations: List, + override val symbol: String = LogicalType.AND.sql + ) : LogicalOperation { + + constructor(vararg operations: LogicalOperation) : this(operations.toList(), LogicalType.AND.sql) + + init { + require(operations.isNotEmpty()) { "A logical group requires at least one operation" } + require(symbol in GROUP_CONNECTORS) { + "A logical group cannot use '$symbol' as connector, expected one of $GROUP_CONNECTORS" + } + } + override val operator: SQLOperator<*> get() = operations.first().operator - override fun asString(): String { - return buildString { - append("$symbol (") - operations.forEachIndexed { index, logicalOperation -> - if (index == 0) { - append(logicalOperation.operator.asString()) - } else { + /** + * Returns every operator contained in the group, including nested groups, in declaration + * order. + * @return The operators of the grouped operations, depth first. + */ + fun operators(): List> = sqlOperators() + + override fun sqlOperators(): List> = + operations.flatMap { it.sqlOperators() } + + override fun filterBy(predicate: (SQLOperator<*>) -> Boolean): LogicalOperation? { + val retained = operations.mapNotNull { it.filterBy(predicate) } + return if (retained.isEmpty()) null else Multiple(retained, symbol) + } + + override fun asString(): String = "$symbol ${asConditionString()}" + + override fun asConditionString(): String = buildString { + append("(") + operations.forEachIndexed { index, logicalOperation -> + when { + index == 0 -> { + append(logicalOperation.asConditionString()) + } + + else -> { append(" ${logicalOperation.asString()}") } } - append(")") - } + append(")") } + override fun clone(): LogicalOperation { - return Multiple(operations.map { it.clone() }, symbol = symbol) + return Multiple(operations.map { it.clone() }, symbol = symbol) + } + + companion object { + private val GROUP_CONNECTORS = listOf(LogicalType.AND, LogicalType.OR) + .map { it.sql } } } @@ -110,6 +158,82 @@ sealed interface LogicalOperation: Copyable { */ fun asString(): String + /** + * Converts the operation into its SQL fragment without the leading connector, so it can be + * placed right after the `WHERE` keyword or after another condition. + * @return The SQL string for the operation, e.g. "age > '18'" or "(a OR b)". + */ + fun asConditionString(): String = operator.toSQLString() + + /** + * Converts the logical operation into the SQL fragment anchored by the `WHERE` keyword, that + * is, without the connector that would be dangling at the start of a clause. + * @return The SQL string for the logical operation preceded by `WHERE`. + */ + fun asWhereString(): String = "${LogicalType.WHERE.sql} ${asConditionString()}" + + /** + * Returns every operator the operation holds, descending into nested groups. + * @return The operators of this operation, in declaration order. + */ + fun sqlOperators(): List> = listOf(operator) + /** + * Filters the operation by the given predicate, descending into nested groups. + * + * A group survives only if at least one of its conditions does, and the surviving conditions + * are kept with their original connectors. + * + * @param predicate The predicate applied to every contained operator. + * @return The filtered operation, or `null` when nothing is left. + */ + fun filterBy(predicate: (SQLOperator<*>) -> Boolean): LogicalOperation? = + if (predicate(operator)) this else null +} +/** + * Wraps this operator into the [LogicalOperation] matching [type]. + * @param type The connector the condition must be linked with. + * @return The logical operation holding this operator. + * @throws IllegalArgumentException if [type] cannot link a condition. + */ +internal fun SQLOperator<*>.asLogicalOperation(type: LogicalType): LogicalOperation = when (type) { + LogicalType.AND -> LogicalOperation.And(this) + LogicalType.OR -> LogicalOperation.Or(this) + LogicalType.AND_NOT -> LogicalOperation.AndNot(this) + LogicalType.EXISTS -> LogicalOperation.Exists(this) + LogicalType.NOT -> LogicalOperation.Not(this) + LogicalType.ALL -> LogicalOperation.All(this) + LogicalType.WHERE -> throw IllegalArgumentException( + "WHERE cannot link a condition, use it as the query anchor instead" + ) } + +/** + * Builds a [LogicalOperation.Multiple] attached to the enclosing clause with [outer]. + * @param outer The connector that attaches the group to the enclosing clause. + * @param conditions The conditions to group, at least one. + * @return The logical group. + */ +internal fun logicalGroup( + outer: LogicalType, + conditions: List +): LogicalOperation.Multiple = LogicalOperation.Multiple(conditions, outer.sql) + +/** + * Builds a [LogicalOperation.Multiple] where every condition is linked with [inner] and the whole + * group is attached to the enclosing clause with [outer]. + * @param outer The connector that attaches the group to the enclosing clause. + * @param inner The connector used between the conditions inside the group. + * @param conditions The conditions to group, at least one. + * @return The logical group. + * @throws IllegalArgumentException if [conditions] is empty or [inner] cannot link a condition. + */ +internal fun logicalGroup( + outer: LogicalType, + inner: LogicalType, + conditions: Array> +): LogicalOperation.Multiple = LogicalOperation.Multiple( + conditions.map { it.asLogicalOperation(inner) }, + outer.sql +) \ No newline at end of file diff --git a/query/src/main/java/com/blipblipcode/query/utils/Extensions.kt b/query/src/main/java/com/blipblipcode/query/utils/Extensions.kt index 9524438..912065b 100644 --- a/query/src/main/java/com/blipblipcode/query/utils/Extensions.kt +++ b/query/src/main/java/com/blipblipcode/query/utils/Extensions.kt @@ -136,11 +136,7 @@ fun LogicalOperation.copyOperation(operator: SQLOperator<*> = this.operator): Lo is AndNot -> AndNot(operator = operator) is Exists -> Exists(operator = operator) is Multiple -> { - val updatedOperations = operations.toMutableList() - if (updatedOperations.isNotEmpty()) { - updatedOperations[0] = updatedOperations[0].copyOperation(operator) - } - Multiple(updatedOperations, symbol) + Multiple(replaceFirstLeafOperator(operations, operator), symbol) } is Not -> Not(operator = operator) is Or -> Or(operator = operator) @@ -148,6 +144,27 @@ fun LogicalOperation.copyOperation(operator: SQLOperator<*> = this.operator): Lo } } +/** + * Replaces the operator of the first non grouped condition, keeping every connector intact. + * + * Replacing the first *element* of a group would nest a group inside a group and emit an invalid + * connector such as `AND (OR (a OR b))`, so the replacement walks into nested groups instead. + * + * @param operations The conditions of the group being copied. + * @param operator The `SQLOperator` that replaces the first condition. + * @return A new list with the replacement applied. + */ +private fun replaceFirstLeafOperator( + operations: List, + operator: SQLOperator<*> +): List { + val index = operations.indexOfFirst { it !is Multiple } + if (index == -1) return operations + val updated = operations.toMutableList() + updated[index] = updated[index].copyOperation(operator) + return updated +} + /** * Creates a copy of this `OrderBy` clause with updated parameters. * diff --git a/query/src/test/java/com/blipblipcode/query/LogicalGroupTest.kt b/query/src/test/java/com/blipblipcode/query/LogicalGroupTest.kt new file mode 100644 index 0000000..ab112b5 --- /dev/null +++ b/query/src/test/java/com/blipblipcode/query/LogicalGroupTest.kt @@ -0,0 +1,499 @@ +package com.blipblipcode.query + +import com.blipblipcode.query.builder.queryGroup +import com.blipblipcode.query.operator.CaseConversion +import com.blipblipcode.query.operator.LogicalOperation +import com.blipblipcode.query.operator.LogicalType +import com.blipblipcode.query.operator.SQLOperator +import com.blipblipcode.query.utils.copyOperation +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class LogicalGroupTest { + + @Test + fun should_keep_or_conditions_inside_the_and_chain_when_group_is_added_in_asSql() { + //GIVEN + val query = queryGroup { + withWhere("creator", SQLOperator.Equals("creator", 1)) + withAnd("status", SQLOperator.Equals("status", 1)) + withAnd("responsible", SQLOperator.NotEquals("responsible", 1)) + withAndGroup( + "search", + LogicalOperation.Or(SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_source_display", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER)) + ) + }.buildSelect() + + //WHEN + val actualSql = query.asSql() + + //THEN + val expectedSql = + "SELECT * FROM tire_transfer_document WHERE creator = 1 AND status = 1 AND responsible != 1 " + + "AND (LOWER(doc_number) LIKE LOWER('%cal%') OR LOWER(terminal_source_display) LIKE LOWER('%cal%') " + + "OR LOWER(terminal_dest_display) LIKE LOWER('%cal%'))" + assertEquals(expectedSql, actualSql) + } + + @Test + fun should_attach_group_with_and_when_and_group_is_added_in_asSql() { + //GIVEN + val query = queryGroup { + withAndGroup( + "range", + LogicalOperation.And(SQLOperator.GreaterThan("age", 18)), + LogicalOperation.And(SQLOperator.LessThan("age", 65)) + ) + }.buildSelect() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals("SELECT * FROM tire_transfer_document WHERE creator = 1 AND (age > 18 AND age < 65)", actualSql) + } + + @Test + fun should_attach_group_with_or_when_or_group_is_added_in_asSql() { + //GIVEN + val query = queryGroup { + withAnd("status", SQLOperator.Equals("status", "active")) + withOrGroup( + "owner", + LogicalOperation.And(SQLOperator.Equals("role", "admin")), + LogicalOperation.And(SQLOperator.Equals("role", "root")) + ) + }.buildSelect() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals( + "SELECT * FROM tire_transfer_document WHERE creator = 1 AND status = 'active' OR (role = 'admin' AND role = 'root')", + actualSql + ) + } + + @Test + fun should_quote_string_values_when_group_is_rendered_in_asString() { + //GIVEN + val group = LogicalOperation.Multiple( + listOf( + LogicalOperation.And(SQLOperator.Equals("name", "Ada")), + LogicalOperation.And(SQLOperator.Equals("city", "London")) + ), + LogicalType.AND.sql + ) + + //WHEN + val actualString = group.asString() + + //THEN + assertEquals("AND (name = 'Ada' AND city = 'London')", actualString) + } + + @Test + fun should_render_nested_group_when_group_contains_another_group_in_asString() { + //GIVEN + val group = LogicalOperation.Multiple( + listOf( + LogicalOperation.And(SQLOperator.Equals("status", "active")), + LogicalOperation.Multiple( + listOf( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ), + LogicalType.OR.sql + ) + ), + LogicalType.AND.sql + ) + + //WHEN + val actualString = group.asString() + + //THEN + assertEquals("AND (status = 'active' OR (role = 'admin' OR role = 'root'))", actualString) + } + + @Test + fun should_return_every_operator_when_group_is_inspected_in_operators() { + //GIVEN + val group = LogicalOperation.Multiple( + listOf( + LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal")), + LogicalOperation.Or(SQLOperator.Equals("terminal_dest_display", "cal")) + ), + LogicalType.AND.sql + ) + + //WHEN + val operators = group.operators() + + //THEN + assertEquals( + listOf("doc_number" to "cal", "terminal_dest_display" to "cal"), + operators.map { it.toPair() } + ) + } + + @Test + fun should_throw_IllegalArgumentException_when_group_has_no_conditions_in_andGroup() { + //GIVEN + val builder = QuerySelect.builder("users").where(SQLOperator.Equals("id", 1)) + + //WHEN + val result = runCatching { builder.andGroup("search") } + + //THEN + assertTrue(result.exceptionOrNull() is IllegalArgumentException) + } + + @Test + fun should_keep_flat_rendering_when_no_group_is_added_in_asSql() { + //GIVEN + val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("id", 1)) + .and("status", SQLOperator.Equals("status", "active")) + .or("role", SQLOperator.Equals("role", "admin")) + .build() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals("SELECT * FROM users WHERE id = 1 AND status = 'active' OR role = 'admin'", actualSql) + } + + @Test + fun should_keep_or_conditions_inside_the_and_chain_when_group_is_added_in_asSql_for_delete() { + //GIVEN + val query = queryGroup { + withWhere("creator", SQLOperator.Equals("creator", 1)) + withAndGroup( + "search", + LogicalOperation.Or(SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER)) + ) + }.buildDelete() + + //WHEN + val actualSql = query.asSql() + + //THEN + val expectedSql = + "DELETE FROM tire_transfer_document WHERE creator = 1 " + + "AND (LOWER(doc_number) LIKE LOWER('%cal%') OR LOWER(terminal_dest_display) LIKE LOWER('%cal%'))" + assertEquals(expectedSql, actualSql) + } + + @Test + fun should_keep_or_conditions_inside_the_and_chain_when_group_is_added_in_asSql_with_predicate() { + //GIVEN + val query = queryGroup { + withAnd("status", SQLOperator.Equals("status", 1)) + withAndGroup( + "search", + LogicalOperation.Or(SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER)) + ) + }.buildSelect() + + //WHEN + val actualSql = query.asSql { it.column != "status" } + + //THEN + val expectedSql = + "SELECT * FROM tire_transfer_document WHERE creator = 1 " + + "AND (LOWER(doc_number) LIKE LOWER('%cal%') OR LOWER(terminal_dest_display) LIKE LOWER('%cal%'))" + assertEquals(expectedSql, actualSql) + } + + @Test + fun should_clone_grouped_operations_when_query_is_copied_in_copy() { + //GIVEN + val query = queryGroup { + withAndGroup("search", LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal"))) + }.buildSelect() + + //WHEN + val copy = query.copy() + + //THEN + val originalOperation = query.getOperations()["search"] + val copiedOperation = copy.getOperations()["search"] + assertTrue(originalOperation !== copiedOperation) + assertEquals(query.asSql(), copy.asSql()) + } + + @Test + fun should_render_is_null_condition_when_group_contains_it_in_asSql_for_delete() { + //GIVEN + val query = QueryDelete.builder("sessions") + .where(SQLOperator.LessThan("expires_at", 1700000000)) + .andGroup( + "stale", + LogicalOperation.Or(SQLOperator.IsNull("refreshed_at")), + LogicalOperation.Or(SQLOperator.LessThan("refreshed_at", 1600000000)) + ) + .build() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals( + "DELETE FROM sessions WHERE expires_at < 1700000000 " + + "AND (refreshed_at IS NULL OR refreshed_at < 1600000000)", + actualSql + ) + } + + @Test + fun should_remove_grouped_operation_when_key_is_removed_in_remove() { + //GIVEN + val query = queryGroup { + withAnd("status", SQLOperator.Equals("status", 1)) + withAndGroup("search", LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal"))) + }.buildSelect() + + //WHEN + val removedQuery = query.remove("search") + + //THEN + assertEquals("SELECT * FROM tire_transfer_document WHERE creator = 1 AND status = 1", removedQuery.asSql()) + } + + @Test + fun should_anchor_group_without_connector_when_group_is_the_where_clause_in_asSql() { + //GIVEN + val query = QuerySelect.builder("users") + .where( + "search", + LogicalOperation.Multiple( + listOf( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ), + LogicalType.AND.sql + ) + ) + .and("status", SQLOperator.Equals("status", "active")) + .build() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals("SELECT * FROM users WHERE (role = 'admin' OR role = 'root') AND status = 'active'", actualSql) + } + + @Test + fun should_keep_retained_conditions_when_predicate_excludes_one_inside_group_in_asSql() { + //GIVEN + val query = queryGroup { + withAndGroup( + "search", + LogicalOperation.Or(SQLOperator.Like("doc_number", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_source_display", "cal", CaseConversion.LOWER)), + LogicalOperation.Or(SQLOperator.Like("terminal_dest_display", "cal", CaseConversion.LOWER)) + ) + }.buildSelect() + + //WHEN + val actualSql = query.asSql { it.column != "terminal_dest_display" } + + //THEN + val expectedSql = + "SELECT * FROM tire_transfer_document WHERE creator = 1 " + + "AND (LOWER(doc_number) LIKE LOWER('%cal%') OR LOWER(terminal_source_display) LIKE LOWER('%cal%'))" + assertEquals(expectedSql, actualSql) + } + + @Test + fun should_drop_group_when_predicate_excludes_every_condition_in_asSql() { + //GIVEN + val query = queryGroup { + withAndGroup("search", LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal"))) + }.buildSelect() + + //WHEN + val actualSql = query.asSql { false } + + //THEN + assertEquals("SELECT * FROM tire_transfer_document", actualSql) + } + + @Test + fun should_promote_first_survivor_when_where_clause_is_filtered_out_in_asSql() { + //GIVEN + val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("creator", 1)) + .and("status", SQLOperator.Equals("status", "active")) + .build() + + //WHEN + val actualSql = query.asSql { it.column != "creator" } + + //THEN + assertEquals("SELECT * FROM users WHERE status = 'active'", actualSql) + } + + @Test + fun should_promote_first_survivor_when_where_clause_is_filtered_out_in_asSql_for_delete() { + //GIVEN + val query = QueryDelete.builder("users") + .where(SQLOperator.Equals("creator", 1)) + .andGroup("search", LogicalType.OR, SQLOperator.Equals("role", "admin")) + .build() + + //WHEN + val actualSql = query.asSql { it.column != "creator" } + + //THEN + assertEquals("DELETE FROM users WHERE (role = 'admin')", actualSql) + } + + @Test + fun should_list_every_operator_of_nested_group_when_group_is_inspected_in_operators() { + //GIVEN + val nested = LogicalOperation.Multiple( + listOf( + LogicalOperation.And(SQLOperator.Equals("status", "active")), + LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ) + ), + LogicalType.AND.sql + ) + + //WHEN + val operators = nested.operators() + + //THEN + assertEquals( + listOf("status" to "active", "role" to "admin", "role" to "root"), + operators.map { it.toPair() } + ) + } + + @Test + fun should_list_every_operator_of_group_when_query_is_exposed_in_getSqlOperators() { + //GIVEN + val query = queryGroup { + withAndGroup( + "search", + LogicalOperation.Or(SQLOperator.Equals("doc_number", "cal")), + LogicalOperation.Or(SQLOperator.Equals("terminal_dest_display", "cal")) + ) + }.buildSelect() + + //WHEN + val columns = query.getSqlOperators().map { it.column } + + //THEN + assertEquals(listOf("creator", "doc_number", "terminal_dest_display"), columns) + } + + @Test + fun should_throw_IllegalArgumentException_when_symbol_is_not_a_connector_in_Multiple() { + //GIVEN + val conditions = listOf(LogicalOperation.And(SQLOperator.Equals("a", 1))) + + //WHEN + val result = runCatching { LogicalOperation.Multiple(conditions, "XOR") } + + //THEN + assertTrue(result.exceptionOrNull() is IllegalArgumentException) + } + + @Test + fun should_link_conditions_with_connector_when_typed_group_is_added_in_andGroup() { + //GIVEN + val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .andGroup( + "search", + LogicalType.OR, + SQLOperator.Like("doc_number", "cal"), + SQLOperator.Like("terminal_dest_display", "cal") + ) + .build() + + //WHEN + val actualSql = query.asSql() + + //THEN + assertEquals( + "SELECT * FROM users WHERE status = 'active' AND (doc_number LIKE '%cal%' OR terminal_dest_display LIKE '%cal%')", + actualSql + ) + } + + @Test + fun should_add_group_to_built_query_when_andGroup_is_called_on_instance() { + //GIVEN + val query = QuerySelect.builder("users") + .where(SQLOperator.Equals("status", "active")) + .build() + + //WHEN + val grouped = query.andGroup("search", LogicalType.OR, SQLOperator.Equals("role", "admin")) + + //THEN + assertEquals( + "SELECT * FROM users WHERE status = 'active' AND (role = 'admin')", + grouped.asSql() + ) + } + + @Test + fun should_keep_grouped_where_when_query_is_converted_in_toQueryDelete() { + //GIVEN + val query = QuerySelect.builder("users") + .where( + "search", + LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ) + ) + .and("status", SQLOperator.Equals("status", "active")) + .build() + + //WHEN + val actualSql = query.toQueryDelete().asSql() + + //THEN + assertEquals( + "DELETE FROM users WHERE (role = 'admin' OR role = 'root') AND status = 'active'", + actualSql + ) + } + + @Test + fun should_replace_first_leaf_when_group_is_copied_in_copyOperation() { + //GIVEN + val nested = LogicalOperation.Multiple( + listOf( + LogicalOperation.And(SQLOperator.Equals("status", "active")), + LogicalOperation.Multiple( + LogicalOperation.Or(SQLOperator.Equals("role", "admin")), + LogicalOperation.Or(SQLOperator.Equals("role", "root")) + ) + ), + LogicalType.AND.sql + ) + + //WHEN + val copied = nested.copyOperation(SQLOperator.Equals("status", "archived")) + + //THEN + assertEquals("AND (status = 'archived' AND (role = 'admin' OR role = 'root'))", copied.asString()) + } +} \ No newline at end of file diff --git a/query/src/test/java/com/blipblipcode/query/builder/QueryGroupBuilder.kt b/query/src/test/java/com/blipblipcode/query/builder/QueryGroupBuilder.kt new file mode 100644 index 0000000..51ef7b8 --- /dev/null +++ b/query/src/test/java/com/blipblipcode/query/builder/QueryGroupBuilder.kt @@ -0,0 +1,51 @@ +package com.blipblipcode.query.builder + +import com.blipblipcode.query.QueryDelete +import com.blipblipcode.query.QuerySelect +import com.blipblipcode.query.operator.LogicalOperation +import com.blipblipcode.query.operator.LogicalType +import com.blipblipcode.query.operator.SQLOperator + +class QueryGroupBuilder { + private var table: String = "tire_transfer_document" + private var whereKey: String = "creator" + private var whereOperation: LogicalOperation = LogicalOperation.Where(SQLOperator.Equals("creator", 1)) + private val conditions: MutableList> = mutableListOf() + + fun withTable(table: String) = apply { this.table = table } + + fun withWhere(key: String, operator: SQLOperator<*>) = apply { + this.whereKey = key + this.whereOperation = LogicalOperation.Where(operator) + } + + fun withAnd(key: String, operator: SQLOperator<*>) = apply { + conditions.add(key to LogicalOperation.And(operator)) + } + + fun withOr(key: String, operator: SQLOperator<*>) = apply { + conditions.add(key to LogicalOperation.Or(operator)) + } + + fun withAndGroup(key: String, vararg grouped: LogicalOperation) = apply { + conditions.add(key to LogicalOperation.Multiple(grouped.toList(), LogicalType.AND.sql)) + } + + fun withOrGroup(key: String, vararg grouped: LogicalOperation) = apply { + conditions.add(key to LogicalOperation.Multiple(grouped.toList(), LogicalType.OR.sql)) + } + + fun buildSelect(): QuerySelect { + val builder = QuerySelect.builder(table).where(whereKey, whereOperation) + conditions.forEach { (key, operation) -> builder.addLogicalOperation(key, operation) } + return builder.build() + } + + fun buildDelete(): QueryDelete { + val builder = QueryDelete.builder(table).where(whereOperation.operator) + conditions.forEach { (key, operation) -> builder.addLogicalOperation(key, operation) } + return builder.build() + } +} + +fun queryGroup(block: QueryGroupBuilder.() -> Unit): QueryGroupBuilder = QueryGroupBuilder().apply(block) \ No newline at end of file