Phoenix 1.3 and Ecto with an existing database

Hi all, I’m creating a new api project using phoenix 1.3 but need it to use an existing mysql database. I’m fine with the mysql adaptor but not sure about connecting to an existing database with already populated tables. I created a context and schema using mix phx.gen.json <params> this generated my files but also generated a migration file. Do I have to run mix exto.migrate ? I think I don’t have to, but what if in the future I really need to create a migration to modify a column type or name? What would be the right way to accomplish this?

thanks!

You can just skip the migration. There is also a flag you can pass to the generator so it is not even generated in the first place. Also take a look at the mix ecto.load and mix ecto.dump tasks so you can dump the structure of the production database so you have something to develop/test against.

2 Likes

cool, I’ll just skip the migration, had to change the schema name to map the database table and it worked.
btw, didn’t know about mix ecto.dump , I just used mysqldump to get a test dump, but good to know for the next time.

thanks!

1 Like

Another tip. If your mysql field names aren’t in snake_case, you can use the source option in the Ecto Schema definition to rename them:

field :my_field, source: :MyField

https://hexdocs.pm/ecto/2.2.6/Ecto.Schema.html#field/3

3 Likes

Im in a similar situation, I was building out an elixir app that was using data from a database originally created & migrated by rails. I’ve since deployed the elixir app and shut down the rails app. While developing the new elixir app I generated ecto migrations that matched the rails app so that my tests would run properly. If I’m reading the above correctly, I should just mix ecto.dump the structure, remove the migration files that got the DB to that point, and build new migrations on top of that? How does that effect the test suite?

– Edit

I think I posted without thinking about this enough.

So, there’s no real reason for me to need those duplicated migrations since the structure of the database is already to that point. Instead, what I can do is add mix ecto.dump to in an alias around ecto.migrate and ecto.rollback, add structure.sql to my VCS, and add some docs stating that on a fresh setup the schema needs to be loaded before migrations runs.

(I got the alias idea from https://www.devmynd.com/blog/getting-a-schema-file-from-elixirs-ecto/)

3 Likes