
# EctoScript

[![Hex Version](https://img.shields.io/hexpm/v/ecto_script.svg)](https://hex.pm/packages/ecto_script)
[![docs](https://img.shields.io/badge/docs-hexpm-blue.svg)](https://hexdocs.pm/ecto_script/)

<!-- MDOC !-->
Seamlessly use [`Ecto`](https://ecto.hexdocs.pm) from [`IEx`](https://iex.hexdocs.pm), [`Livebook`](https://livebook.dev) or scripts.

## Usage

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

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

or just

```elixir
Mix.install([:ecto_script])
```

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

```elixir
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:

```sh
** (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`:

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

The adapter and other connection parameters can specified:

```elixir
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:

```elixir
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.

<!-- MDOC !-->
