dekiru-data_migration 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a2b3d1e8c3c6af485f97be40590207de2b6279d9f7ac39db5ecf60011719110e
4
+ data.tar.gz: ae80bc1d486d121e6059819a958f7b19d62b050978062ba2ae043e3c2af37fee
5
+ SHA512:
6
+ metadata.gz: e6cad5b3306b2c9cc4b41ed94ed8b33d23f1eec7e83652a33dd3dc6a2b1159ffcd7868d2dac259b5c68ac1f7fe107d879f0a70139c531ab26c2e1a8455325387
7
+ data.tar.gz: 945d0f7161086370e437ece47988e6d45f465048f4502d6800de9601095c99de475c159d4c5ccfa387136ad2db61913529384f80e3f7c97b8125ad26f8a82f57
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-06-16
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 aki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # Dekiru::DataMigration
2
+
3
+ A Ruby on Rails library for executing data migration tasks safely and efficiently.
4
+
5
+ ## Overview
6
+
7
+ `Dekiru::DataMigration` provides the following features for data migration tasks:
8
+
9
+ - **Progress Display**: Real-time progress visualization during processing
10
+ - **Transaction Management**: Automatic transaction control to ensure data safety
11
+ - **Execution Confirmation**: Confirmation prompts before committing changes
12
+ - **Side Effect Monitoring**: Tracking of database queries, job enqueuing, and email sending
13
+ - **Logging**: Detailed execution logging
14
+
15
+ ## Installation
16
+
17
+ Add this line to your application's Gemfile:
18
+
19
+ ```ruby
20
+ gem 'dekiru-data_migration'
21
+ ```
22
+
23
+ And then execute:
24
+
25
+ ```bash
26
+ $ bundle install
27
+ ```
28
+
29
+ Or install it yourself as:
30
+
31
+ ```bash
32
+ $ gem install dekiru-data_migration
33
+ ```
34
+
35
+ ## Data Migration Operator
36
+
37
+ You can implement the necessary processing for data migration tasks with scripts like the following:
38
+
39
+ ```ruby
40
+ # scripts/demo.rb
41
+ Dekiru::DataMigration::Operator.execute('Grant admin privileges to users') do
42
+ targets = User.where("email LIKE '%sonicgarden%'")
43
+
44
+ log "Target user count: #{targets.count}"
45
+ find_each_with_progress(targets) do |user|
46
+ user.update!(admin: true)
47
+ end
48
+
49
+ log "Updated user count: #{User.where("email LIKE '%sonicgarden%'").where(admin: true).count}"
50
+ end
51
+ ```
52
+
53
+ Execution result:
54
+ ```
55
+ $ bin/rails r scripts/demo.rb
56
+ Start: Grant admin privileges to users at 2019-05-24 18:29:57 +0900
57
+
58
+ Target user count: 30
59
+ Time: 00:00:00 |=================>>| 100% Progress
60
+ Updated user count: 30
61
+
62
+ Are you sure to commit? (yes/no) > yes
63
+
64
+ Finished successfully: Grant admin privileges to users
65
+ Total time: 6.35 sec
66
+ ```
67
+
68
+ ## Side Effect Monitoring
69
+
70
+ By executing with the `warning_side_effects: true` option, side effects that occur during data migration tasks (database writes, job enqueuing, email sending, etc.) will be displayed.
71
+
72
+ ```ruby
73
+ Dekiru::DataMigration::Operator.execute('Grant admin privileges to users', warning_side_effects: true) do
74
+ # Processing content...
75
+ end
76
+ ```
77
+
78
+ Execution result:
79
+ ```
80
+ $ bin/rails r scripts/demo.rb
81
+ Start: Grant admin privileges to users at 2019-05-24 18:29:57 +0900
82
+
83
+ Target user count: 30
84
+ Time: 00:00:00 |=================>>| 100% Progress
85
+ Updated user count: 30
86
+
87
+ Write Queries!!
88
+ 30 call: Update "users" SET ...
89
+
90
+ Enqueued Jobs!!
91
+ 10 call: NotifyJob
92
+
93
+ Delivered Mailers!!
94
+ 10 call: UserMailer
95
+
96
+ Are you sure to commit? (yes/no) > yes
97
+ ```
98
+
99
+ ## Generating Maintenance Scripts
100
+
101
+ You can generate maintenance scripts that use `Dekiru::DataMigration::Operator` with the generator. The filename will be prefixed with the execution date.
102
+
103
+ ```bash
104
+ $ bin/rails g maintenance_script demo_migration
105
+ ```
106
+
107
+ Generated file example:
108
+ ```ruby
109
+ # scripts/20230118_demo_migration.rb
110
+ # frozen_string_literal: true
111
+
112
+ Dekiru::DataMigration::Operator.execute('demo_migration') do
113
+ # write here
114
+ end
115
+ ```
116
+
117
+ ### Output Directory Configuration
118
+
119
+ The output directory for files is by default the `scripts` directory directly under the application root. You can change the output directory through configuration.
120
+
121
+ ```ruby
122
+ # config/initializers/dekiru.rb
123
+ Dekiru::DataMigration.configure do |config|
124
+ config.maintenance_script_directory = 'scripts/maintenance'
125
+ end
126
+ ```
127
+
128
+ ## Custom Transaction Management
129
+
130
+ For scripts using `Dekiru::DataMigration::Operator`, there are cases where the default `ActiveRecord::Base.transaction` transaction handling is insufficient, such as when writing to multiple databases is required.
131
+
132
+ You can modify the transaction handling behavior of `Dekiru::DataMigration::Operator` by customizing `Dekiru::DataMigration::TransactionProvider`.
133
+
134
+ ### Implementation Example
135
+
136
+ Here's an example configuration for applications using multiple databases.
137
+
138
+ #### Application-side Configuration
139
+
140
+ ```ruby
141
+ # app/models/legacy_record.rb
142
+ class LegacyRecord < ApplicationRecord
143
+ connects_to database: { writing: :legacy, reading: :legacy }
144
+ end
145
+
146
+ # app/models/application_record.rb
147
+ class ApplicationRecord < ActiveRecord::Base
148
+ connects_to database: { writing: :primary, reading: :primary }
149
+
150
+ def self.with_legacy_transaction
151
+ ActiveRecord::Base.transaction do
152
+ LegacyRecord.transaction do
153
+ yield
154
+ end
155
+ end
156
+ end
157
+ end
158
+ ```
159
+
160
+ #### Custom TransactionProvider Configuration
161
+
162
+ To configure `Dekiru::DataMigration::Operator` to also use `ApplicationRecord.with_legacy_transaction` for transaction handling, set up the following configuration:
163
+
164
+ ```ruby
165
+ # config/initializers/dekiru.rb
166
+ class MyTransactionProvider < Dekiru::DataMigration::TransactionProvider
167
+ def within_transaction(&)
168
+ ApplicationRecord.with_legacy_transaction(&)
169
+ end
170
+ end
171
+
172
+ Dekiru::DataMigration.configure do |config|
173
+ config.transaction_provider = MyTransactionProvider.new
174
+ end
175
+ ```
176
+
177
+ ## Available Configuration Options
178
+
179
+ ### Basic Configuration
180
+
181
+ ```ruby
182
+ # config/initializers/dekiru.rb
183
+ Dekiru::DataMigration.configure do |config|
184
+ # Output directory for maintenance scripts (default: "scripts")
185
+ config.maintenance_script_directory = 'scripts/maintenance'
186
+
187
+ # Custom transaction provider (default: Dekiru::DataMigration::TransactionProvider.new)
188
+ config.transaction_provider = MyTransactionProvider.new
189
+ end
190
+ ```
191
+
192
+ ### Runtime Options
193
+
194
+ ```ruby
195
+ Dekiru::DataMigration::Operator.execute('Title', options) do
196
+ # Processing content
197
+ end
198
+ ```
199
+
200
+ Available options:
201
+ - `warning_side_effects`: Display side effects (default: true)
202
+ - `without_transaction`: Don't use transactions (default: false)
203
+ - `logger`: Custom logger (default: auto-generated)
204
+ - `output`: Output destination (default: $stdout)
205
+
206
+ ## Key Methods
207
+
208
+ ### `log(message)`
209
+ Outputs log messages. Properly handled even during progress bar display.
210
+
211
+ ### `find_each_with_progress(scope, options = {}, &block)`
212
+ Executes `find_each` with a progress bar for ActiveRecord scopes.
213
+
214
+ ### `each_with_progress(enum, options = {}, &block)`
215
+ Executes processing with a progress bar for any Enumerable objects.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/all"
4
+ require "ruby-progressbar"
5
+
6
+ module Dekiru
7
+ module DataMigration
8
+ # Data migration operator with transaction control and progress tracking
9
+ class Operator # rubocop:disable Metrics/ClassLength
10
+ class NestedTransactionError < StandardError; end
11
+
12
+ attr_reader :title, :stream, :logger, :result, :canceled, :started_at, :ended_at, :error
13
+
14
+ def self.execute(title, options = {}, &block)
15
+ new(title, options).execute(&block)
16
+ end
17
+
18
+ def initialize(title, options = {})
19
+ @title = title
20
+ @options = options
21
+ @logger = @options.fetch(:logger) do
22
+ Logger.new(Rails.root.join("log/data_migration_#{Time.current.strftime("%Y%m%d%H%M")}.log"))
23
+ end
24
+ @stream = @options.fetch(:output, $stdout)
25
+ @without_transaction = @options.fetch(:without_transaction, false)
26
+ @side_effects = Hash.new do |hash, key|
27
+ hash[key] = Hash.new(0)
28
+ end
29
+ end
30
+
31
+ def execute(&block) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength
32
+ @started_at = Time.current
33
+ log "Start: #{title} at #{started_at}\n\n"
34
+ if @without_transaction
35
+ run(&block)
36
+ @result = true
37
+ else
38
+ raise NestedTransactionError if current_transaction_open?
39
+
40
+ @result = transaction_provider.within_transaction do
41
+ run(&block)
42
+ log "Finished execution: #{title}"
43
+ confirm?("\nAre you sure to commit?")
44
+ end
45
+ end
46
+ log "Finished successfully: #{title}" if @result == true
47
+ rescue StandardError => e
48
+ @error = e
49
+ @result = false
50
+ ensure
51
+ @ended_at = Time.current
52
+ log "Total time: #{duration.round(2)} sec"
53
+
54
+ raise error if error
55
+
56
+ return @result # rubocop:disable Lint/EnsureReturn
57
+ end
58
+
59
+ def duration
60
+ ((ended_at || Time.current) - started_at)
61
+ end
62
+
63
+ def each_with_progress(enum, options = {}) # rubocop:disable Metrics/MethodLength
64
+ options = options.dup
65
+ options[:total] ||= begin
66
+ (enum.size == Float::INFINITY ? nil : enum.size)
67
+ rescue StandardError
68
+ nil
69
+ end
70
+ options[:format] ||= options[:total] ? "%a |%b>>%i| %p%% %t" : "%a |%b>>%i| ??%% %t"
71
+ options[:output] = stream
72
+
73
+ @pb = ::ProgressBar.create(options)
74
+ enum.each do |item|
75
+ yield item
76
+ @pb.increment
77
+ end
78
+ @pb.finish
79
+ end
80
+
81
+ def find_each_with_progress(target_scope, options = {}, &block)
82
+ # `LocalJumpError: no block given (yield)` が出る場合、 find_each メソッドが enumerator を返していない可能性があります
83
+ # 直接 each_with_progress を使うか、 find_each が enumerator を返すように修正してください
84
+ each_with_progress(target_scope.find_each, options, &block)
85
+ end
86
+
87
+ private
88
+
89
+ def log(message)
90
+ if @pb && !@pb.finished?
91
+ @pb.log(message)
92
+ else
93
+ stream.puts(message)
94
+ end
95
+
96
+ logger&.info(message.squish)
97
+ end
98
+
99
+ def confirm?(message = "Are you sure?") # rubocop:disable Metrics/MethodLength
100
+ loop do
101
+ stream.print "#{message} (yes/no) > "
102
+ case $stdin.gets.strip
103
+ when "yes"
104
+ newline
105
+ return true
106
+ when "no"
107
+ newline
108
+ cancel!
109
+ end
110
+ end
111
+ end
112
+
113
+ def newline
114
+ stream.puts("")
115
+ end
116
+
117
+ def cancel!
118
+ log "Canceled: #{title}"
119
+ raise ActiveRecord::Rollback
120
+ end
121
+
122
+ def handle_notification(*args) # rubocop:disable Metrics/AbcSize
123
+ event = ActiveSupport::Notifications::Event.new(*args)
124
+
125
+ increment_side_effects(:enqueued_jobs, event.payload[:job].class.name) if event.payload[:job]
126
+ increment_side_effects(:delivered_mailers, event.payload[:mailer]) if event.payload[:mailer]
127
+
128
+ return unless event.payload[:sql] && /\A\s*(insert|update|delete)/i.match?(event.payload[:sql])
129
+
130
+ increment_side_effects(:write_queries, event.payload[:sql])
131
+ end
132
+
133
+ def increment_side_effects(type, value)
134
+ @side_effects[type][value] += 1
135
+ end
136
+
137
+ def warning_side_effects(&block)
138
+ ActiveSupport::Notifications.subscribed(method(:handle_notification), /^(sql|enqueue|deliver)/) do
139
+ instance_eval(&block)
140
+ end
141
+
142
+ @side_effects.each do |name, items|
143
+ newline
144
+ log "#{name.to_s.titlecase}!!"
145
+ items.sort_by { |_v, c| c }.reverse.slice(0, 20).each do |value, count|
146
+ log "#{count} call: #{value}"
147
+ end
148
+ end
149
+ end
150
+
151
+ def run(&block)
152
+ if @options.fetch(:warning_side_effects, true)
153
+ warning_side_effects(&block)
154
+ else
155
+ instance_eval(&block)
156
+ end
157
+ end
158
+
159
+ def transaction_provider
160
+ Dekiru::DataMigration.configuration.transaction_provider
161
+ end
162
+
163
+ def current_transaction_open?
164
+ transaction_provider.current_transaction_open?
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+
5
+ module Dekiru
6
+ module DataMigration
7
+ # Provides transaction management functionality for data migrations.
8
+ # Wraps ActiveRecord transaction operations to ensure data consistency
9
+ # during migration operations.
10
+ class TransactionProvider
11
+ # Executes the given block within a database transaction.
12
+ # @yield Block to execute within transaction
13
+ def within_transaction(&)
14
+ ActiveRecord::Base.transaction(&)
15
+ end
16
+
17
+ # Checks if there is currently an open database transaction.
18
+ # @return [Boolean] true if transaction is open, false otherwise
19
+ def current_transaction_open?
20
+ ActiveRecord::Base.connection.current_transaction.open?
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dekiru
4
+ module DataMigration
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "data_migration/version"
4
+ require_relative "data_migration/transaction_provider"
5
+ require_relative "data_migration_operator"
6
+
7
+ module Dekiru
8
+ # The DataMigration module provides configuration and error handling
9
+ # for data migration tasks. It allows users to set up custom
10
+ # configuration options such as the maintenance script directory and
11
+ # transaction provider. The module exposes a `configure` method for
12
+ # block-based configuration and defines a custom error class for
13
+ # migration-related exceptions.
14
+ module DataMigration
15
+ class << self
16
+ def configure
17
+ yield(configuration)
18
+ end
19
+
20
+ def configuration
21
+ @configuration ||= Configuration.new
22
+ end
23
+ end
24
+
25
+ # Configuration class for Dekiru Data Migration.
26
+ class Configuration
27
+ attr_accessor :maintenance_script_directory, :transaction_provider
28
+
29
+ def initialize
30
+ @maintenance_script_directory = "scripts"
31
+ @transaction_provider = TransactionProvider.new
32
+ end
33
+ end
34
+
35
+ class Error < StandardError; end
36
+ # Your code goes here...
37
+ end
38
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "data_migration/operator"
4
+ require "active_support/deprecation"
5
+
6
+ module Dekiru
7
+ # Alias for backward compatibility
8
+ # Please use Dekiru::DataMigration::Operator in new code
9
+ class DataMigrationOperator < DataMigration::Operator
10
+ def self.new(...)
11
+ ActiveSupport::Deprecation.new.warn(
12
+ "Dekiru::DataMigrationOperator is deprecated. " \
13
+ "Use Dekiru::DataMigration::Operator instead."
14
+ )
15
+ DataMigration::Operator.new(...)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,8 @@
1
+ Description:
2
+ Create database maintenance script using Dekiru::DataMigration::Operator
3
+
4
+ Example:
5
+ rails generate maintenance_script UpdateUserName
6
+
7
+ This will create:
8
+ scripts/XXX_update_user_name.rb
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ # Generates a maintenance script file from a template.
6
+ #
7
+ # This generator creates a new maintenance script file in the directory specified by
8
+ # `Dekiru::DataMigration.configuration.maintenance_script_directory`. The generated file is named
9
+ # with the current date (in YYYYMMDD format) followed by the provided name.
10
+ #
11
+ # Example usage:
12
+ # rails generate maintenance_script MyScript
13
+ class MaintenanceScriptGenerator < Rails::Generators::NamedBase
14
+ source_root File.expand_path("templates", __dir__)
15
+
16
+ def copy_maintenance_script_file
17
+ template "maintenance_script.rb.erb",
18
+ "#{Dekiru::DataMigration.configuration.maintenance_script_directory}/#{filename_date}_#{file_name}.rb"
19
+ end
20
+
21
+ private
22
+
23
+ def filename_date
24
+ Time.current.strftime("%Y%m%d")
25
+ end
26
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ Dekiru::DataMigration::Operator.execute('<%= @name %>') do
4
+ # write here
5
+ end
@@ -0,0 +1,51 @@
1
+ module Dekiru
2
+ module DataMigration
3
+ class Operator
4
+ class NestedTransactionError < StandardError
5
+ end
6
+
7
+ attr_reader title: String
8
+ attr_reader stream: IO
9
+ attr_reader logger: Logger?
10
+ attr_reader result: bool?
11
+ attr_reader canceled: bool?
12
+ attr_reader started_at: Time?
13
+ attr_reader ended_at: Time?
14
+ attr_reader error: Exception?
15
+
16
+ def self.execute: (String title, Hash[Symbol, untyped] options) { () -> void } -> bool
17
+
18
+ def initialize: (String title, Hash[Symbol, untyped] options) -> void
19
+
20
+ def execute: () { () -> void } -> bool
21
+
22
+ def duration: () -> Float
23
+
24
+ def each_with_progress: [T] (Enumerable[T] enum, Hash[Symbol, untyped] options) { (T) -> void } -> void
25
+
26
+ def find_each_with_progress: (untyped target_scope, Hash[Symbol, untyped] options) { (untyped) -> void } -> void
27
+
28
+ private
29
+
30
+ def log: (String message) -> void
31
+
32
+ def confirm?: (?String message) -> bool
33
+
34
+ def newline: () -> void
35
+
36
+ def cancel!: () -> void
37
+
38
+ def handle_notification: (*untyped args) -> void
39
+
40
+ def increment_side_effects: (Symbol type, String value) -> void
41
+
42
+ def warning_side_effects: () { () -> void } -> void
43
+
44
+ def run: () { () -> void } -> void
45
+
46
+ def transaction_provider: () -> untyped
47
+
48
+ def current_transaction_open?: () -> bool
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,6 @@
1
+ module Dekiru
2
+ module DataMigration
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,90 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dekiru-data_migration
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - SonicGarden
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-06-21 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rails
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: ruby-progressbar
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ description: Dekiru::DataMigration provides features for data migration tasks including
41
+ progress display, transaction management, execution confirmation, side effect monitoring,
42
+ and detailed logging.
43
+ email:
44
+ - info@sonicgarden.jp
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".rspec"
50
+ - ".rubocop.yml"
51
+ - CHANGELOG.md
52
+ - CODE_OF_CONDUCT.md
53
+ - LICENSE.txt
54
+ - README.md
55
+ - Rakefile
56
+ - lib/dekiru/data_migration.rb
57
+ - lib/dekiru/data_migration/operator.rb
58
+ - lib/dekiru/data_migration/transaction_provider.rb
59
+ - lib/dekiru/data_migration/version.rb
60
+ - lib/dekiru/data_migration_operator.rb
61
+ - lib/generators/maintenance_script/USAGE
62
+ - lib/generators/maintenance_script/maintenance_script_generator.rb
63
+ - lib/generators/maintenance_script/templates/maintenance_script.rb.erb
64
+ - sig/dekiru/data_migration.rbs
65
+ - sig/dekiru/data_migration/operator.rbs
66
+ homepage: https://github.com/SonicGarden/dekiru-data_migration
67
+ licenses:
68
+ - MIT
69
+ metadata:
70
+ homepage_uri: https://github.com/SonicGarden/dekiru-data_migration
71
+ source_code_uri: https://github.com/SonicGarden/dekiru-data_migration
72
+ changelog_uri: https://github.com/SonicGarden/dekiru-data_migration/blob/main/CHANGELOG.md
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: 3.1.0
81
+ required_rubygems_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ requirements: []
87
+ rubygems_version: 3.6.2
88
+ specification_version: 4
89
+ summary: A Ruby on Rails library for executing data migration tasks safely and efficiently.
90
+ test_files: []