Carbonite.Query (Carbonite v0.2.0) View Source

This module provides query functions for retrieving audit trails from the database.

Link to this section Summary

Functions

Returns an Ecto.Query that can be used to select changes for a single record.

Returns an Ecto.Query that can be used to select or delete the "current" transaction.

Link to this section Types

Specs

changes_option() :: {:carbonite_prefix, prefix()} | {:preload, preload()}
Link to this type

current_transaction_option()

View Source

Specs

current_transaction_option() ::
  {:carbonite_prefix, prefix()} | {:preload, preload()}

Specs

prefix() :: binary() | atom()

Specs

preload() :: atom() | [atom()] | true

Link to this section Functions

Link to this function

changes(record, opts \\ [])

View Source (since 0.2.0)

Specs

Returns an Ecto.Query that can be used to select changes for a single record.

Given an Ecto.Schema struct, this function builds a query that fetches all changes recorded for it from the database, ordered ascending by their ID (i.e., roughly by insertion date descending).

Example

%MyApp.Rabbit{id: 1}
|> Carbonite.Query.changes()
|> MyApp.Repo.all()

Options

  • carbonite_prefix defines the audit trail's schema, defaults to "carbonite_default"
  • preload can be used to preload the transaction
Link to this function

current_transaction(opts \\ [])

View Source (since 0.2.0)

Specs

current_transaction([current_transaction_option()]) :: Ecto.Query.t()

Returns an Ecto.Query that can be used to select or delete the "current" transaction.

This function is useful when your tests run in a database transaction using Ecto's SQL sandbox.

Examples

Asserting on the current transaction

When you insert your Carbonite.Transaction record somewhere inside your domain logic, you do not wish to return it to the caller only to be able to assert on its attributes in tests. This is how you can assert on the current transaction:

Carbonite.Query.current_transaction()
|> MyApp.Repo.all()

# Preload changes
Carbonite.Query.current_transaction(preload: :changes)
|> MyApp.Repo.all()

# Same
Carbonite.Query.current_transaction(preload: true)
|> MyApp.Repo.all()

Erasing the current transaction

Sometimes your test code may run a particular function twice (in multiple transactions if it wasn't for the SQL sandbox), in which case you may need to delete the Carbonite.Transaction inserted first in between.

# This deletes the transaction as well as any associated change (per FK constraint)
Carbonite.Query.current_transaction()
|> MyApp.Repo.delete_all()

Options

  • carbonite_prefix defines the audit trail's schema, defaults to "carbonite_default"
  • preload can be used to preload the changes