Pular para o conteúdo

Query Object

A consulta com filtros opcionais vira um objeto composto por métodos: cada método acrescenta um predicado parametrizado e colunas externas passam por allowlist. Use em listagens com filtros combináveis, sem SQL injection.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

Extrato com PIX e TED entre R$ 200,00 e R$ 900,00, do menor para o maior.

Planta

Sequência
4/4
forAccount, whereTypes, whereAmountBetween, orderBy, limit1sql com $1..$n e params2pool.query(sql, params)3linhas4AppQueryTransactionPostgreSQL
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

A consulta com filtros opcionais vira um objeto composto por métodos, com predicados parametrizados e allowlist de colunas

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

build()+1
  1. 1

    QueryTransaction: um método por filtro, devolve o próprio objeto

  2. 2

    build() numera os placeholders; nenhum valor entra no SQL

  3. 3

    orderBy fora da allowlist → ErrorQueryInvalid

  4. 4

    Quem executa recebe { sql, params } e chama pool.query

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Sem SQL injection por construção

  • build() testável sem banco

Custos

  • Mais código que SQL à mão

  • CTE e subquery ficam de fora

Código

pattern/enterprise/query-object

7 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec query-object-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f query-object-db

Saída: SQL com $1 a $5, os parâmetros à parte e as linhas pix R$ 400,00, ted R$ 500,00, pix R$ 800,00 e ted R$ 900,00.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: a statement query composed by methods; every value becomes a numbered parameter and ORDER BY a whitelisted column.
import pg from "pg";

type TransactionType = "pix" | "ted" | "boleto" | "card";

class ErrorQueryInvalid extends Error {
  override name = "ErrorQueryInvalid";
}

// ORDER BY cannot be a parameter, so the column is only ever one of these.
const SORT_COLUMNS = new Set(["created_at", "amount_cents"]);
const PAGE_SIZE_DEFAULT = 20;

// Builds SQL and never touches the database: each method adds one predicate.
class QueryTransaction {
  private readonly conditions: ((placeholder: (value: unknown) => string) => string)[] = [];
  private sort = { column: "created_at", direction: "DESC" as "ASC" | "DESC" };
  private pageSize = PAGE_SIZE_DEFAULT;

  forAccount(accountId: string): this {
    return this.where((p) => `account_id = ${p(accountId)}`);
  }

  whereTypes(types: TransactionType[]): this {
    return types.length ? this.where((p) => `type = ANY(${p(types)})`) : this;
  }

  // Both ends inclusive; either may be left open.
  whereAmountBetween(minCents?: number, maxCents?: number): this {
    if (minCents !== undefined) this.where((p) => `amount_cents >= ${p(minCents)}`);
    if (maxCents !== undefined) this.where((p) => `amount_cents <= ${p(maxCents)}`);
    return this;
  }

  orderBy(column: string, direction: "ASC" | "DESC" = "DESC"): this {
    if (!SORT_COLUMNS.has(column)) throw new ErrorQueryInvalid(`column "${column}" is not allowed in ORDER BY`);
    this.sort = { column, direction };
    return this;
  }

  limit(size: number): this {
    this.pageSize = size;
    return this;
  }

  build(): { sql: string; params: unknown[] } {
    const params: unknown[] = [];
    const placeholder = (value: unknown) => `$${params.push(value)}`;
    const predicates = this.conditions.map((condition) => condition(placeholder));
    const where = predicates.length ? ` WHERE ${predicates.join(" AND ")}` : "";
    return { sql: `SELECT type, amount_cents FROM transactions${where} ORDER BY ${this.sort.column} ${this.sort.direction} LIMIT ${placeholder(this.pageSize)}`, params };
  }

  private where(condition: (placeholder: (value: unknown) => string) => string): this {
    this.conditions.push(condition);
    return this;
  }
}

const pool = new pg.Pool({ connectionString: Bun.env.QUERY_OBJECT_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/query_object_db" });
const account = "CC-0001";
// Rewrites the account's transactions, so a second run reads the same twelve rows.
await pool.query("DELETE FROM transactions WHERE account_id = $1", [account]);
await pool.query(
  `INSERT INTO transactions (account_id, type, amount_cents, status)
   SELECT $1, (ARRAY['pix','ted','boleto','card'])[1 + n % 4], 10000 * n, 'completed' FROM generate_series(1, 12) AS n`,
  [account],
);
const { sql, params } = new QueryTransaction().forAccount(account).whereTypes(["pix", "ted"]).whereAmountBetween(20_000, 90_000).orderBy("amount_cents", "ASC").limit(5).build();
console.log(`  [SQL]    ${sql}\n  [PARAMS] ${JSON.stringify(params)}`);
const { rows } = await pool.query<{ type: TransactionType; amount_cents: string }>(sql, params);
console.log(`  [ROWS]   ${rows.map((row) => `${row.type} R$ ${(Number(row.amount_cents) / 100).toFixed(2)}`).join(", ")}`);
await pool.end();

Nível

intermediário

4/13

Linhas de TypeScript
61
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • TED
  • Boleto
  • Cartão
  • Extrato

Padrões do catálogo que implementa

  • Query Object

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • transactions

Variáveis de ambiente

QUERY_OBJECT_DATABASE_URL
postgres://postgres:postgres@localhost:5432/query_object_db

Trilhapasso 3 de 6

Lógica de domínio (PoEAA)

  1. 1Transaction Script
  2. 2Data Access Styles: Active Record vs. Data Mapper
  3. 3Query Object
  4. 4Specification
  5. 5Special Case (Null Object)
  6. 6Dependency Injection

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Query Object?

Próximo projeto, Padrões EnterpriseSpecial Case (Null Object)
Esc

↑ ↓ navegarEnter abrir239 resultados