How to run ecto.create programmatically

I’m building out a single file elixir script to run examples and I’ve got it working with Ecto with the exception of create and migrate. Does anyone know how you could run these in a single file (without a mix file)

“setup”: [“ecto.create”, “ecto.migrate”]

The functions used by the mix task are available here so you’d be able put something together with them. Take a look at the functions specifically. Sorry, I don’t have an example off the top of my head!

1 Like

Underjord has a couple of really good blogs on dynamic repos and migrations:

1 Like

For migrating I do these things in Livebook:

# up 
Ecto.Migrator.run(Repo, [{0, SomeMigrationModule}], :up, all: true, log: false)

# down
Ecto.Migrator.run(Repo, [{0, SomeMigrationModule}], :down, all: true, log: false)

The SomeMigrationModule is useing the Ecto.Migration module, like you always do.

So yes, Ecto.Migrator is your friend. I’ve never bothered to automate the creation of the schema, so can’t help there.

Edit: the creation mix task seems to be defined in the ecto package itself. Maybe get some inspiration here: https://github.com/elixir-ecto/ecto/blob/f2a0def734dcee354acb223116550e9ae659fb0c/lib/mix/tasks/ecto.create.ex#L53

Thanks everyone! I got a complete and working single file elixir app with Ecto that creates the database, runs migrations and a seed file :slight_smile:

1 Like