使用数据映射器进行迁移

发布于 2025-01-08 17:18:26 字数 406 浏览 4 评论 0原文

我需要向我的用户模型添加另一列(电子邮件)。我不想修改 MySql 数据库中的现有数据。我该怎么做呢?

下面是我原始模型类的代码,我正在使用 Sinatra。提前致谢。

require 'rubygems'
require 'data_mapper'

DataMapper.setup(:default,'mysql://root@localhost/database')

class User
  include DataMapper::Resource
  property :id,              Serial
  property :name,            String, :unique=>true, :required=>true
end

DataMapper.finalize

I need to add another column (email) to my User model. I do not wish to modify the existing data in MySql database. How should I do that?

Below is code of my original model class, and I am using Sinatra. Thanks in advance.

require 'rubygems'
require 'data_mapper'

DataMapper.setup(:default,'mysql://root@localhost/database')

class User
  include DataMapper::Resource
  property :id,              Serial
  property :name,            String, :unique=>true, :required=>true
end

DataMapper.finalize

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁拥 2025-01-15 17:18:26

对于添加新列之类的简单操作,您可以修改模型,然后调用 auto_upgrade!,如下所示:

require 'rubygems'
require 'data_mapper'

class User
  include DataMapper::Resource
  property :id,              Serial
  property :name,            String, :unique=>true, :required=>true
  property :email,           String, :unique=>true, :required=>true
end

DataMapper.finalize
DataMapper::Logger.new(STDOUT,  :debug)
DataMapper.setup(:default,'mysql://root@localhost/database')
DataMapper.auto_upgrade!

请注意,我更改了调用 setup 的位置,以便 SQL日志是在连接建立之前创建的。这里的 SQL 日志包括以下行:

ALTER TABLE `users` ADD COLUMN `email` VARCHAR(50) NOT NULL

我相信它可以满足您的要求,而无需更改现有数据。但请注意,如果您想要更改列的功能(例如,更改字段的大小),则此操作将不起作用。 DataMapper 不会检查此类更改。

For simple things like adding a new column, you can modify your model and then call auto_upgrade!, like this:

require 'rubygems'
require 'data_mapper'

class User
  include DataMapper::Resource
  property :id,              Serial
  property :name,            String, :unique=>true, :required=>true
  property :email,           String, :unique=>true, :required=>true
end

DataMapper.finalize
DataMapper::Logger.new(STDOUT,  :debug)
DataMapper.setup(:default,'mysql://root@localhost/database')
DataMapper.auto_upgrade!

Notice that I changed where setup is called, so that an SQL log is created before the connection is set up. Here the SQL log includes the following line:

ALTER TABLE `users` ADD COLUMN `email` VARCHAR(50) NOT NULL

Which I believe does what you want, without altering existing data. Notice, however, that if you wanted to change the features of a column (e.g., changing the size of fields), this wouldn't work. DataMapper doesn't check for that kind of change.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文