如何通过 Rails 迁移克隆数据库表?
我希望迁移通过仅在名称后缀(包括原始表中的所有索引)来创建现有表的克隆。
因此,有一个“快照”表,我想创建“snapshots_temp”作为该表的精确副本(不是数据,只是表架构,但包括索引)。
我可以将块复制并粘贴到 schema.rb 文件中,然后手动重命名它。
但我不确定在应用此迁移时 schema.rb 中的定义是否仍然准确。其他开发人员可能已更改该表,而我不想更新我的迁移脚本。
那么如何在运行时获取表的架构呢?本质上,“rake schema:dump”如何对表进行逆向工程,以便我可以在迁移中执行相同的操作? (但更改表名称)。
I want a migration to create a clone of an existing table by just suffixing the name, including all the indexes from the original table.
So there's a "snapshots" table and I want to create "snapshots_temp" as an exact copy of the table (not the data, just the table schema, but including the indexes).
I could just copy and paste the block out of the schema.rb file and manually rename it.
But I'm not sure by the time this migration is applied if the definition from schema.rb will still be accurate. Another developer might have changed the table and I don't want to have to update my migration script.
So how might I get the schema of the table at runtime? Essentially, how does 'rake schema:dump' reverse engineer the table so I can do the same in my migration? (but changing the table name).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试用纯 SQL 来完成。这将做你想做的事:
Try doing it with pure SQL. This will do what you want:
在 Rails 4 和 Rails 4 中PostgreSQL,创建新的迁移并插入:
这将创建具有原始表的精确结构的克隆,并使用旧值填充新表。
更多信息: http://www.postgresql.org/docs/9.0/静态/sql-createtableas.html
In Rails 4 & PostgreSQL, create a new migration and insert:
This will create the clone with the exact structure of the original table, and populate the new table with old values.
More info: http://www.postgresql.org/docs/9.0/static/sql-createtableas.html
这样就可以了。它并不完美,因为它不会复制表选项或索引。如果您确实设置了任何表选项,则必须手动将它们添加到此迁移中。
要复制索引,您必须制定 SQL 查询来选择它们,然后将它们处理到新的 add_index 指令中。这有点超出我的知识范围了。但这适用于复制结构。
This will do. It's not perfect, because it won't copy table options or indices. If you do have any table options set, you will have to add them to this migration manually.
To copy indices you'll have to formulate a SQL query to select them, and then process them into new add_index directives. That's a little beyond my knowledge. But this works for copying the structure.
将项目
db/schema.rb
中的表条目直接复制到迁移中。只需更改表名即可。Copy the tables entry from your projects
db/schema.rb
straight into your migration. Just change the table name and your good to go.看起来这个逻辑包含在 ActiveRecord::SchemaDumper 中,但它只公开了一个 all-一体化“转储”方法,您不能仅转储特定表(“表”方法是私有的)。
It looks like this logic is wrapped up in ActiveRecord::SchemaDumper but it only exposes an all-in-one "dump" method and you can't dump just a specific table (the "table" method is private).