执行 rake 脚本时锁定数据库
我创建了一个 rake 脚本来向某些用户发送电子邮件。
rake 脚本首先需要删除一些旧的数据库记录,然后继续处理电子邮件。
问题在于,在脚本运行期间,某些用户可能会自行查看/删除数据。如果脚本删除了数据,则应刷新视图,以容纳新数据。
我能想到的第一个明显的解决方案是永远不要在视图中显示旧数据,从而避免记录在被删除后被删除的可能性。
但我仍然认为这里有竞争条件的可能性,我想知道如何在执行脚本时锁定数据库。
我使用 Mysql 作为我的数据库系统。
I have created a rake script to send e-mails to some users.
The rake script first needs to delete some old database records, and then proceed with the e-mails.
The trouble is that during the time that the script is running, some users may view/delete the data themselves. If the data is deleted by the script, then the views should be refreshed, in order to accommodate the new data.
The first obvious solution that I can think of is to never display the old data in the views , and so avoid the possibility that a record is deleted after it has already been deleted.
But I still think that I have a race condition possibility here, and I would like to know how could I lock the database while executing the script.
I am using Mysql as my database system.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将通过设置一个 rake 任务来解决这个问题,该任务调用模型上的方法来删除数据库记录。然后,我将代码包装在事务中删除旧邮件。这将在删除电子邮件时锁定数据库,并允许您处理其他人尝试删除数据时引发的任何异常。
I would approach this by setting up a rake task that calls a method on a model to delete the database records. I would then wrap the code to delete the old mails in a transaction. That will lock the database while deleting the emails and allow you to handle any exceptions thrown when anyone else tries to delete the data.