> For the complete documentation index, see [llms.txt](https://docs.gaiodataos.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gaiodataos.com/gaio-dataos-spanish/herramientas/tareas/entrega/contenido/generador-de-consultas-estaticas-de-informes.md).

# Generador de consultas estáticas de informes

### Visión General

El **MiniQueryBuilder** es una interfaz fluida para construir consultas tipo SQL en Gaio DataOS. Proporciona una forma simple e intuitiva de crear consultas utilizando cláusulas como:

* SELECT
* FROM
* WHERE (filter)
* GROUP BY
* ORDER BY
* LIMIT
* OFFSET

***

## Uso Básico

```js
// Access the query builder through context.query
const results = await context.query
  .select(['id', 'name', 'created_at'])
  .from('users')
  .filter('status', 'eq', 'active')
  .orderBy('created_at', 'desc')
  .limit(100)
  .run();
```

## Referencia de la API

### Constructor

El constructor de consultas se accede mediante el objeto `context`:

```ts
// You don't need to create an instance - use context.query
const query = context.query;
```

### Métodos Disponibles

**select(fields: string\[])**

Especifica los campos a seleccionar en la consulta.

```js
context.query.select(['id', 'name', 'email']);
```

**from(table: string)**

Especifica la tabla desde la cual consultar. Este método es obligatorio.

```js
context.query.from('users');
```

**filter(field: string, operator: FilterOperator, value: any)**

Agrega una condición de filtro a la consulta.

```js
context.query.filter('age', 'gt', 18);
```

#### Operadores Disponibles

* `eq` → igual
* `neq` → distinto
* `gt` → mayor que
* `gte` → mayor o igual que
* `lt` → menor que
* `lte` → menor o igual que
* `like` → coincidencia de patrón con `%`
* `ilike` → coincidencia de patrón sin distinguir mayúsculas/minúsculas
* `in` → dentro de una lista de valores
* `is` → verificación de null
* `cs` → contiene (para arrays)
* `cd` → contenido por (para arrays)
* `ov` → superposición (para arrays)
* `fts` → búsqueda de texto completo
* `or` → operador lógico OR
* `and` → operador lógico AND

**groupBy(fields: string\[])**

Define los campos para agrupar resultados.

```js
context.query.groupBy(['department', 'role']);
```

**orderBy(field: string, direction: 'asc' | 'desc' = 'asc', nullsPosition?: 'first' | 'last')**

Agrega una cláusula ORDER BY.

```js
context.query.orderBy('created_at', 'desc', 'last');
```

**limit(limit: number)**

Define el número máximo de filas a devolver.

```js
context.query.limit(100);
```

**offset(offset: number)**

Define cuántas filas omitir (para paginación).

```js
context.query.offset(50);
```

#### run(): Promise\<GenericType\[]>

Ejecuta la consulta y devuelve una Promesa que resuelve un arreglo de resultados.

**Usage**

```js
const results = await context.query
  .select(['id', 'name'])
  .from('users')
  .limit(100)
  .run();
```

**Valor de Retorno**

Devuelve una Promesa que resuelve en un arreglo de objetos (`GenericType[]`). Cada objeto representa una fila del resultado, con propiedades que coinciden con las columnas seleccionadas.

**Validaciones**

The `run()` method performs the following validations before executing the query:

* Ensures that the limit is a number
* Ensures that the limit does not exceed 10,000 rows
* Implicitly checks that the FROM clause is specified (through the build method)

#### Manejo de Errores

El método `run()` puede lanzar errores en los siguientes casos:

* Si el `limit` no es un número

  ```
  Error('Limit must be a number')
  ```
* Si el `limit` supera 10,000

  ```
  Error('Limit must be less than 10000')
  ```
* Si no se especifica la cláusula `FROM`

  ```
  Error('FROM clause is required. Use .from() to specify a table.')
  ```
* Si falla la solicitud a la API\
  → El error del cliente API será propagado

***

#### Detalles de Implementación

El método `run()` envía una solicitud POST a:

```
api/table/query
```

Incluye el esquema de la consulta y los datos de la tarea, y luego extrae y devuelve los datos de la respuesta.

***

### Ejemplos

#### Consulta Básica

```js
const users = await context.query
  .select(['id', 'name', 'email'])
  .from('users')
  .limit(100)
  .run();
```

#### Consulta con Filtro

```js
const activeUsers = await context.query
  .select(['id', 'name', 'email'])
  .from('users')
  .filter('status', 'eq', 'active')
  .run();
```

#### Consulta con Agregación

```js
const departmentCounts = await context.query
  .select(['department', 'COUNT(*) as count'])
  .from('employees')
  .groupBy(['department'])
  .orderBy('count', 'desc')
  .run();
```

#### Paginación

```js
const page = 2;
const pageSize = 50;

const paginatedUsers = await context.query
  .select(['id', 'name', 'email'])
  .from('users')
  .orderBy('id', 'asc')
  .limit(pageSize)
  .offset((page - 1) * pageSize)
  .run();
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.gaiodataos.com/gaio-dataos-spanish/herramientas/tareas/entrega/contenido/generador-de-consultas-estaticas-de-informes.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
