According to this issue – Dynamic Models in Phoenix Framework – it is possible to dynamically create a model in Elixir using Module.create
.
Is it also possible to create a table in the database for this model during runtime, i.e. without using Ecto migration files?
PostgreSQL
and MySQL
adapters for Ecto
2.0+ have an ability to execute raw SQL:
qry =
"""
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
res = Ecto.Adapters.SQL.query!(Repo, qry, [])
Another (might be preferred) way would be to just delegate this to underlying mysql
shell executable:
System.cmd("mysql", ["#{create_table_script}"])