Pular para o conteúdo

Data Access Styles: Active Record vs. Data Mapper

Dois estilos de Fowler para ligar objeto e banco: Active Record se salva sozinho; Data Mapper traduz entre domínio puro e tabela.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

Favorecido PIX (cadastro puro) usa Active Record; conta corrente (regra de saldo) usa Data Mapper.

Planta

Fluxo
3/3
Active Record - favorecido PIXData Mapper - contaBeneficiary.create /beneficiary.save()mapperAccount.idFind / updateAccount.withdraw, sem bancobeneficiariesaccountsreconstrói e grava
3

3 passos — reproduza para seguir o fluxo

Como funciona

4passos

Active Record, que se salva sozinho, contra Data Mapper, que traduz entre domínio puro e tabela

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Beneficiary tem o próprio SQL: create e save

  2. 2

    Account só tem a regra (withdraw), sem banco

  3. 3

    mapperAccount carrega com FOR UPDATE, reconstrói e grava o saldo

  4. 4

    Um estilo por agregado

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Active Record: uma classe só, pouco código para cadastro simples

  • Data Mapper: domínio puro, regra testada sem banco

Custos

  • Active Record: regra presa ao SQL, teste exige banco

  • Data Mapper: domínio e mapper, mais código por agregado

Código

pattern/enterprise/data-access-styles

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 data-access-styles-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 data-access-styles-db

Saída: o favorecido landlord@bank.com se grava como “Aluguel apartamento”; a conta de João saca R$ 400,00 pelo mapper e fica com R$ 1.100,00.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: a PIX beneficiary saves itself (Active Record); an account with balance rules is persisted by a separate mapper (Data Mapper).
import pg from "pg";

const pool = new pg.Pool({ connectionString: Bun.env.DATA_ACCESS_STYLES_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/data_access_styles_db" });

// Active Record: model and table gateway are the same class; changes stay in memory until save().
class Beneficiary {
  private constructor(readonly id: string, public nickname: string, readonly pixKey: string) {}

  static async create(nickname: string, pixKey: string): Promise<Beneficiary> {
    // Upsert by PIX key, so a second run finds the same beneficiary instead of failing on UNIQUE.
    const { rows } = await pool.query<{ id: string }>(
      "INSERT INTO beneficiaries (nickname, pix_key, bank_code) VALUES ($1, $2, '260') ON CONFLICT (pix_key) DO UPDATE SET nickname = EXCLUDED.nickname RETURNING id",
      [nickname, pixKey],
    );
    return new Beneficiary(rows[0]!.id, nickname, pixKey);
  }

  async save(): Promise<void> {
    await pool.query("UPDATE beneficiaries SET nickname = $2, updated_at = now() WHERE id = $1", [this.id, this.nickname]);
  }
}

// Data Mapper domain: the banking rule, with no import from the database — testable without one.
class Account {
  constructor(readonly id: string, public balanceCents: number) {}

  withdraw(amountCents: number): void {
    if (amountCents > this.balanceCents) throw new Error(`balance ${this.balanceCents} cents, asked ${amountCents}`);
    this.balanceCents -= amountCents;
  }
}

// Only the mapper knows the SQL: it rebuilds the object from the row and writes its state back.
const mapperAccount = {
  async idFind(client: pg.PoolClient, id: string): Promise<Account> {
    const { rows } = await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = $1 FOR UPDATE", [id]);
    const row = rows[0]!;
    return new Account(row.id, Number(row.balance_cents));
  },
  async update(client: pg.PoolClient, account: Account): Promise<void> {
    await client.query("UPDATE accounts SET balance_cents = $2, updated_at = now() WHERE id = $1", [account.id, account.balanceCents]);
  },
};

const beneficiary = await Beneficiary.create("Aluguel", "landlord@bank.com");
beneficiary.nickname = "Aluguel apartamento";
await beneficiary.save();
console.log(`  [ACTIVE RECORD] beneficiary ${beneficiary.pixKey} saved itself as "${beneficiary.nickname}"`);

const { rows: [created] } = await pool.query<{ id: string }>("INSERT INTO accounts (owner_name, balance_cents) VALUES ('Joao Silva', 150000) RETURNING id");
const client = await pool.connect();
try {
  await client.query("BEGIN");
  const account = await mapperAccount.idFind(client, created!.id);
  account.withdraw(40_000);
  await mapperAccount.update(client, account);
  await client.query("COMMIT");
  console.log(`  [DATA MAPPER] Joao Silva account withdrew R$ 400.00, balance R$ ${(account.balanceCents / 100).toFixed(2)}`);
} catch (error) {
  await client.query("ROLLBACK");
  throw error;
} finally {
  client.release();
}
await pool.end();

Nível

intermediário

5/13

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

Domínio financeiro

  • PIX
  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Active Record
  • Data Mapper

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • beneficiaries
  • accounts

Variáveis de ambiente

DATA_ACCESS_STYLES_DATABASE_URL
postgres://postgres:postgres@localhost:5432/data_access_styles_db
PostgreSQL of beneficiaries and accounts.

Trilhapasso 2 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

Relações

Onde ele se encaixa

Mapa
  1. Data Access Styles: Active Record vs. Data Mapper
  • Combina com2
  • Alternativa a1

Por que se relacionam

Teste rápido

Qual destes combina com Data Access Styles: Active Record vs. Data Mapper?

Próximo projeto, Padrões EnterpriseDependency Injection
Esc

↑ ↓ navegarEnter abrir239 resultados