sea-orm icon indicating copy to clipboard operation
sea-orm copied to clipboard

Generate the initial migration for an entity from its model definition

Open dob9601 opened this issue 2 years ago • 2 comments

Motivation

Creating an initial migration for a model can be quite tedious, especially if the model is complex. It would save a lot of time if the initial migration to create the table could be generated from the model definition.

Proposed Solutions

Expand on the functionality of sea-orm-cli. Arguably create_table_from_entity already does the majority of the legwork in terms of creating the TableCreateStatement. The only thing that would need doing is dumping the generated code into a migrations file.

Current Workarounds

  1. Convert the generated TableCreateStatement into a SQL string for the chosen backend.
  2. Convert the SQL string into a StatementBuilder (can be done by playing around with the StatementBuilder trait and Statement::from_sql_and_values.
  3. Use exec_stmt() to run this SQL.

dob9601 avatar Jun 20 '23 16:06 dob9601

Just a point to note, create_table_from_entity returns a raw SQL when executed, but not a generic SeaQuery statement. So if you are targeting multiple databases, this won't work unless we embed three versions of the SQL, one for each backend.

tyt2y3 avatar Jun 22 '23 22:06 tyt2y3

Maybe serialising the generated TableCreateStatement pre-execution could work - though I haven't looked at it's inner workings to see how viable it would be.

If it's something there's an interest in, I'm happy to try and whip up a PR for it

dob9601 avatar Jun 23 '23 17:06 dob9601