EctoScript (EctoScript v0.1.0)

Copy Markdown View Source

Seamlessly use Ecto from IEx, Livebook or scripts.

Usage

Run Mix.install/1 directly in your IEx session, script or notebook in order to install it:

Mix.install([{:ecto_script, "~> 0.1.0"}])

or just

Mix.install([:ecto_script])

Here is a "hello world" example to connect to a (by default Postgres) database:

use EctoScript
EctoScript.setup!()
Repo.query!("SELECT NOW()") |> IO.inspect()

If the repo fails to connect to the database, setup!/1 will provide a sample docker command to spawn a working container as part of the error message:

** (RuntimeError) Port 5432 not listening (:econnrefused)

You can run the following docker command to create it:

  docker run -d --rm --name ecto-script-postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=ecto_script -p 5432:5432 postgres:18

You can try the sample schemas like EctoScript.Samples.Post:

use EctoScript
sample_migration()
EctoScript.setup!()
Repo.insert!(%EctoScript.Samples.Post{title: "hello", body: "world!"})

The adapter and other connection parameters can specified:

use EctoScript,
  adapter: Ecto.Adapters.MyXQL,
  hostname: "localhost",
  port: 1234,
  database: "foo",
  username: "foo",
  password: "foo",
  pool_size: 10

Migrations can be specified with the defmigration macro:

use EctoScript

defmigration do
  create table(:foos) do
    add :name, :string, null: false
    timestamps type: :utc_datetime_usec
  end
end

EctoScript.setup!(reset: true)
from(foo in "foos", select: foo.name) |> Repo.all()

Note: using reset: true is useful while working on the migration code to start with a clean slate each run.

Summary

Functions

Starts the repository and run all migrations.

Functions

reset!()

setup!(opts \\ [])

@spec setup!([{:reset, boolean()}]) :: :ok

Starts the repository and run all migrations.

Options

  • reset (boolean, default: false): when true, drops the database before running the migrations. Useful to start from a clean slate when iterating on the migration code.

Manual setup

While setup!/1 is meant as a convenient way that should work out of the box, it could be decomposed into manual steps for more fine-grained control:

use EctoScript

# start the repo - can also run Repo.start_link() directly
EctoScript.start_repo!()

defmigration 42 do
  create table(:foos) do
    add :name, :string, null: false
    timestamps type: :utc_datetime_usec
  end
end

# uncomment to reset if you need to change the migration:
# EctoScript.reset!()

# can also run EctoScript.Migrations.migrate_all!()
EctoScript.Migrations.migrate!(42)

Migrations could be provided an optional integer number and be run manually.

start_repo!()

storage_down!()

storage_up!()