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: 10Migrations 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.