Delimited.Schema (Delimited v0.1.0)

Copy Markdown View Source

Declares the columns of a delimited file as a struct.

defmodule Employee do
  use Delimited.Schema

  delimited_schema do
    field :id, :integer, header: "Employee ID"
    field :name, :string, required: true
    field :department, {:enum, [engineering: "ENG", sales: "SLS"]}
    field :hired_on, :date, header: "Hire Date"
    field :salary, :decimal
    field :active, :boolean, default: true
  end
end

The module gains a struct with one key per field, and Delimited gains everything it needs to read and write that file. A schema holds no behaviour of its own: Delimited.read/3 and Delimited.write/4 take the module the way an Ecto.Repo takes an Ecto.Schema.

What the declaration decides

The order of field/3 calls is the order of columns when writing, and the order columns are matched in when reading with headers: false. When reading with headers, order is irrelevant and only the :header name matters.

A field's name is the struct key. Its :header is the text in the file, and defaults to the field name. The two are separate because a file's column names are the file's business: renaming a column in the file changes one :header, not every call site.

See Delimited.Field for the field options and Delimited.Type for the types.

Dialect

delimited_schema/2 takes a format name, dialect options, or both, and they become the schema's defaults:

delimited_schema :tsv, headers: false do
  field :sku, :string
end

Any read or write can override them, so the dialect here should describe the file the schema was written for, not the only file it will ever meet. See Delimited.Dialect.

Introspection

Both are public, because generating a blank template, a column list for an upload form, or documentation from the schema is the point of declaring it once.

Summary

Functions

Declares the columns, and optionally the dialect, of a delimited file.

Functions

delimited_schema(format \\ :csv, opts \\ [], list)

(macro)

Declares the columns, and optionally the dialect, of a delimited file.

Defines a struct with one key per field, defaulting to the field's :default.

field(name, type \\ :string, opts \\ [])

(macro)

Declares one column.

The type defaults to :string, which is the type of every cell before anything is decided about it. See Delimited.Field for the options and Delimited.Type for the types.