Core.JobStore.SQL (Elixir Server Core v0.1.1)

Copy Markdown View Source

Pure helper functions for building standard job-store SQL.

Use this module when writing a custom Core.JobStore adapter for any SQL database (PostgreSQL, MySQL, SQLite, etc.). It handles schema DDL, param encoding, and row deserialization so the adapter only needs to manage the connection.

Example PostgreSQL adapter skeleton

defmodule MyApp.JobStore.Postgres do
  @behaviour Core.JobStore
  alias Core.JobStore.SQL

  def init(_opts) do
    {table, index} = SQL.schema()
    Postgrex.query!(conn(), table, [])
    Postgrex.query!(conn(), index, [])
    :ok
  end

  def insert_job(job) do
    {sql, params} = SQL.insert_params(job)
    %{rows: [[id]]} = Postgrex.query!(conn(), sql <> " RETURNING id", params)
    {:ok, %Core.Workers.Job{job | id: id}}
  end

  def update_job(id, changes) do
    {sql, params} = SQL.update_params(id, changes)
    Postgrex.query!(conn(), sql, params)
    :ok
  end

  def get_job(id) do
    %{rows: rows} = Postgrex.query!(conn(), SQL.select_by_id(), [id])
    case rows do
      [row | _] -> {:ok, SQL.from_row(row)}
      []        -> {:error, :not_found}
    end
  end

  def list_jobs(opts) do
    {sql, params} =
      if status = Keyword.get(opts, :status) do
        {SQL.select_by_status(), [Atom.to_string(status)]}
      else
        {SQL.select_all(), []}
      end

    %{rows: rows} = Postgrex.query!(conn(), sql, params)
    Enum.map(rows, &SQL.from_row/1)
  end

  def cleanup(opts) do
    {sql, params} = SQL.cleanup_params(Keyword.get(opts, :max_age_days, 7))
    Postgrex.query!(conn(), sql, params)
    :ok
  end

  defp conn, do: MyApp.Repo
end

Summary

Functions

DELETE statement and cutoff param for old completed / failed jobs.

Convert a raw row (list of columns in SELECT * order) into a %Job{}.

INSERT statement and params for a %Job{}.

Returns the {create_table, create_index} DDL strings.

SELECT * ordered by insertion time.

SELECT * with WHERE id = ?

SELECT * filtered by status.

UPDATE statement and params. changes is a keyword list of fields.

Functions

cleanup_params(max_age_days)

DELETE statement and cutoff param for old completed / failed jobs.

from_row(list)

Convert a raw row (list of columns in SELECT * order) into a %Job{}.

insert_params(job)

INSERT statement and params for a %Job{}.

schema()

Returns the {create_table, create_index} DDL strings.

select_all()

SELECT * ordered by insertion time.

select_by_id()

SELECT * with WHERE id = ?

select_by_status()

SELECT * filtered by status.

update_params(id, changes)

UPDATE statement and params. changes is a keyword list of fields.