3
votes

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?

2
Just a quick question - what is the purpose of the table?Kociamber
Every month I want to have a custom table to store data of a report. But I want the system to create this table when the user request the report (if it not exists).Eduardo Manoel
What is the DB behind Ecto?Aleksei Matiushkin
@mudasobwa MySQLEduardo Manoel

2 Answers

4
votes

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, [])

Ecto.Adapters.SQL.query/4.

Another (might be preferred) way would be to just delegate this to underlying mysql shell executable:

System.cmd("mysql", ["#{create_table_script}"])
1
votes

In your case (creating new report table every month) I would ditch creating DB table idea and consider using ETS / DETS combo. They are key-value stores (ETS - in-memory, DETS - data saved on disk - this is what you basically need) and you can read more about them here.