preplay_mongoid_rails_migrations 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c892d310947b206fa8611fea68c0e31462a51868
4
+ data.tar.gz: efdd21045eae562a52008a3629d7a3e148df1d09
5
+ SHA512:
6
+ metadata.gz: 1883c3085b37d20d591b2a0d1edf3308f34fa69c49b3ad8cbf7de27dca2731cbdcf363e30fbcca115b1518f9c16eed2eac069a2cac0a8ed53e3c7439ca48c83f
7
+ data.tar.gz: e837fbfd6cb3208a378e8ad0318d2b5f8a67e8cb48616d941d40a09a56e74cf4d30365833bd20ffb81e8cf1dd67e03213ac409926db2dcdd05e9fad1b74c8a27
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ .bundle
2
+ .DS_Store
3
+ .rvmrc
4
+ .idea
5
+ log/
6
+ .ruby-version
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in gem_test.gemspec
4
+ gemspec :development_group => :development_mongoid_rails_migrations
5
+ gemspec :test_group => :test_mongoid_rails_migrations
6
+ gemspec :name => 'mongoid_rails_migrations'
data/Gemfile.lock ADDED
@@ -0,0 +1,104 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ mongoid_rails_migrations (1.0.0)
5
+ activesupport (>= 3.2.0)
6
+ bundler (>= 1.0.0)
7
+ rails (>= 3.2.0)
8
+ railties (>= 3.2.0)
9
+
10
+ GEM
11
+ remote: http://rubygems.org/
12
+ specs:
13
+ actionmailer (3.2.8)
14
+ actionpack (= 3.2.8)
15
+ mail (~> 2.4.4)
16
+ actionpack (3.2.8)
17
+ activemodel (= 3.2.8)
18
+ activesupport (= 3.2.8)
19
+ builder (~> 3.0.0)
20
+ erubis (~> 2.7.0)
21
+ journey (~> 1.0.4)
22
+ rack (~> 1.4.0)
23
+ rack-cache (~> 1.2)
24
+ rack-test (~> 0.6.1)
25
+ sprockets (~> 2.1.3)
26
+ activemodel (3.2.8)
27
+ activesupport (= 3.2.8)
28
+ builder (~> 3.0.0)
29
+ activerecord (3.2.8)
30
+ activemodel (= 3.2.8)
31
+ activesupport (= 3.2.8)
32
+ arel (~> 3.0.2)
33
+ tzinfo (~> 0.3.29)
34
+ activeresource (3.2.8)
35
+ activemodel (= 3.2.8)
36
+ activesupport (= 3.2.8)
37
+ activesupport (3.2.8)
38
+ i18n (~> 0.6)
39
+ multi_json (~> 1.0)
40
+ arel (3.0.2)
41
+ builder (3.0.0)
42
+ erubis (2.7.0)
43
+ hike (1.2.1)
44
+ i18n (0.6.0)
45
+ journey (1.0.4)
46
+ json (1.7.5)
47
+ mail (2.4.4)
48
+ i18n (>= 0.4.0)
49
+ mime-types (~> 1.16)
50
+ treetop (~> 1.4.8)
51
+ mime-types (1.19)
52
+ mongoid (3.0.4)
53
+ activemodel (~> 3.1)
54
+ moped (~> 1.1)
55
+ origin (~> 1.0)
56
+ tzinfo (~> 0.3.22)
57
+ moped (1.2.0)
58
+ multi_json (1.3.6)
59
+ origin (1.0.6)
60
+ polyglot (0.3.3)
61
+ rack (1.4.1)
62
+ rack-cache (1.2)
63
+ rack (>= 0.4)
64
+ rack-ssl (1.3.2)
65
+ rack
66
+ rack-test (0.6.1)
67
+ rack (>= 1.0)
68
+ rails (3.2.8)
69
+ actionmailer (= 3.2.8)
70
+ actionpack (= 3.2.8)
71
+ activerecord (= 3.2.8)
72
+ activeresource (= 3.2.8)
73
+ activesupport (= 3.2.8)
74
+ bundler (~> 1.0)
75
+ railties (= 3.2.8)
76
+ railties (3.2.8)
77
+ actionpack (= 3.2.8)
78
+ activesupport (= 3.2.8)
79
+ rack-ssl (~> 1.3.2)
80
+ rake (>= 0.8.7)
81
+ rdoc (~> 3.4)
82
+ thor (>= 0.14.6, < 2.0)
83
+ rake (0.9.2.2)
84
+ rdoc (3.12)
85
+ json (~> 1.4)
86
+ sprockets (2.1.3)
87
+ hike (~> 1.2)
88
+ rack (~> 1.0)
89
+ tilt (~> 1.1, != 1.3.0)
90
+ test-unit (2.5.1)
91
+ thor (0.16.0)
92
+ tilt (1.3.3)
93
+ treetop (1.4.10)
94
+ polyglot
95
+ polyglot (>= 0.3.1)
96
+ tzinfo (0.3.33)
97
+
98
+ PLATFORMS
99
+ ruby
100
+
101
+ DEPENDENCIES
102
+ mongoid (>= 3.0.0)
103
+ mongoid_rails_migrations!
104
+ test-unit (>= 2.5.0)
data/README.rdoc ADDED
@@ -0,0 +1,52 @@
1
+ == RELEASE NOTES
2
+ * For rails >= 3.2.0 and mongoid >= 3.0.0, use version 1.0.0
3
+ * For rails >= 3.0.0 (but < 3.2.0) and mongoid >= 2.0.0, use version 0.0.14
4
+
5
+ == SYNOPSIS
6
+ * Data migrations for Mongoid.
7
+
8
+ == MIGRATE WHEN ...
9
+ * The migrating is good
10
+
11
+ == INSTALL
12
+ * gem install mongoid_rails_migrations
13
+ * In your Gemfile, include (after including mongoid):
14
+ gem "mongoid_rails_migrations", <version>
15
+
16
+ == FEATURES AND HOW TO USE
17
+ * generator:
18
+ * rails generate mongoid:migration your_migration_name_here
19
+
20
+ * migrations:
21
+ * db:migrate
22
+ * db:migrate:down
23
+ * db:migrate:up
24
+ * db:rollback
25
+ * db:migrate:redo
26
+ * db:migrate:reset
27
+ * db:reseed (handled by mongoid)
28
+ * db:version
29
+
30
+ == CREDITS TO
31
+ * rails
32
+ * mongoid
33
+ * contributions from the community (git log)
34
+
35
+ Much of this gem simply modifies existing code from both projects.
36
+ With that out of the way, on to the license.
37
+
38
+ == LICENSE (MIT)
39
+
40
+ Copyright © 2012: Alan Da Costa
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'),
43
+ to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
44
+ distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
45
+ the following conditions:
46
+
47
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
48
+
49
+ The software is provided 'as is', without warranty of any kind, express or implied, including but not limited to the warranties of
50
+ merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any
51
+ claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
52
+ software or the use or other dealings in the software.
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ $:.unshift(File.dirname(__FILE__))
2
+ namespace :test do
3
+ require 'bundler/setup'
4
+ Bundler.require(:development_mongoid_rails_migrations)
5
+
6
+ namespace :mongoid do
7
+ desc "Test mongoid rails migrations"
8
+ task :migrations do
9
+ require File.dirname(__FILE__) + "/test/config"
10
+ require 'test/migration_test'
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,6 @@
1
+ # encoding: utf-8
2
+
3
+ require 'mongoid_rails_migrations/version'
4
+ require 'mongoid_rails_migrations/mongoid_ext/mongoid'
5
+ require 'mongoid_rails_migrations/mongoid_ext/railtie'
6
+ require 'mongoid_rails_migrations/active_record_ext/migrations'
@@ -0,0 +1,415 @@
1
+ # encoding: utf-8
2
+
3
+ module Mongoid #:nodoc
4
+ # Exception that can be raised to stop migrations from going backwards.
5
+ class IrreversibleMigration < RuntimeError
6
+ end
7
+
8
+ class DuplicateMigrationVersionError < RuntimeError#:nodoc:
9
+ def initialize(version)
10
+ super("Multiple migrations have the version number #{version}")
11
+ end
12
+ end
13
+
14
+ class DuplicateMigrationNameError < RuntimeError#:nodoc:
15
+ def initialize(name)
16
+ super("Multiple migrations have the name #{name}")
17
+ end
18
+ end
19
+
20
+ class UnknownMigrationVersionError < RuntimeError#:nodoc:
21
+ def initialize(version)
22
+ super("No migration with version number #{version}")
23
+ end
24
+ end
25
+
26
+ class IllegalMigrationNameError < RuntimeError#:nodoc:
27
+ def initialize(name)
28
+ super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
29
+ end
30
+ end
31
+
32
+ # Data migrations can manage the modification of data. It's a solution to the common problem of modifying
33
+ # data between code revisions within a document oriented database.
34
+ #
35
+ # Example of simple migration for a system dependency:
36
+ #
37
+ # class AddBaselineSurveySchema < Mongoid::Migration
38
+ # def self.up
39
+ # SurveySchema.create(:label => 'Baseline Survey')
40
+ # end
41
+ #
42
+ # def self.down
43
+ # SurveySchema.where(:label => 'Baseline Survey').first.destroy
44
+ # end
45
+ # end
46
+ #
47
+ # == Timestamped Migrations
48
+ #
49
+ # By default, Rails generates migrations that look like:
50
+ #
51
+ # 20080717013526_your_migration_name.rb
52
+ #
53
+ # The prefix is a generation timestamp (in UTC).
54
+ #
55
+ # If you'd prefer to use numeric prefixes, you can turn timestamped migrations
56
+ # off by setting:
57
+ #
58
+ # Mongoid.config.timestamped_migrations = false
59
+ #
60
+ # In environment.rb.
61
+ #
62
+ class Migration
63
+ @@verbose = true
64
+ cattr_accessor :verbose
65
+
66
+ class << self
67
+ def up_with_benchmarks #:nodoc:
68
+ migrate(:up)
69
+ end
70
+
71
+ def down_with_benchmarks #:nodoc:
72
+ migrate(:down)
73
+ end
74
+
75
+ # Execute this migration in the named direction
76
+ def migrate(direction)
77
+ return unless respond_to?(direction)
78
+
79
+ case direction
80
+ when :up then announce "migrating"
81
+ when :down then announce "reverting"
82
+ end
83
+
84
+ result = nil
85
+ time = Benchmark.measure { result = send("#{direction}_without_benchmarks") }
86
+
87
+ case direction
88
+ when :up then announce "migrated (%.4fs)" % time.real; write
89
+ when :down then announce "reverted (%.4fs)" % time.real; write
90
+ end
91
+
92
+ result
93
+ end
94
+
95
+ # Because the method added may do an alias_method, it can be invoked
96
+ # recursively. We use @ignore_new_methods as a guard to indicate whether
97
+ # it is safe for the call to proceed.
98
+ def singleton_method_added(sym) #:nodoc:
99
+ return if defined?(@ignore_new_methods) && @ignore_new_methods
100
+
101
+ begin
102
+ @ignore_new_methods = true
103
+
104
+ case sym
105
+ when :up, :down
106
+ singleton_class.send(:alias_method_chain, sym, "benchmarks")
107
+ end
108
+ ensure
109
+ @ignore_new_methods = false
110
+ end
111
+ end
112
+
113
+ def write(text="")
114
+ puts(text) if verbose
115
+ end
116
+
117
+ def announce(message)
118
+ version = defined?(@version) ? @version : nil
119
+
120
+ text = "#{version} #{name}: #{message}"
121
+ length = [0, 75 - text.length].max
122
+ write "== %s %s" % [text, "=" * length]
123
+ end
124
+
125
+ def say(message, subitem=false)
126
+ write "#{subitem ? " ->" : "--"} #{message}"
127
+ end
128
+
129
+ def say_with_time(message)
130
+ say(message)
131
+ result = nil
132
+ time = Benchmark.measure { result = yield }
133
+ say "%.4fs" % time.real, :subitem
134
+ say("#{result} rows", :subitem) if result.is_a?(Integer)
135
+ result
136
+ end
137
+
138
+ def suppress_messages
139
+ save, self.verbose = verbose, false
140
+ yield
141
+ ensure
142
+ self.verbose = save
143
+ end
144
+
145
+ def connection
146
+ # ActiveRecord::Base.connection
147
+ ::Mongoid.default_session
148
+ end
149
+
150
+ def method_missing(method, *arguments, &block)
151
+ arg_list = arguments.map(&:inspect) * ', '
152
+
153
+ say_with_time "#{method}(#{arg_list})" do
154
+ # unless arguments.empty? || method == :execute
155
+ # arguments[0] = Migrator.proper_table_name(arguments.first)
156
+ # end
157
+ connection.send(method, *arguments, &block)
158
+ end
159
+ end
160
+ end
161
+ end
162
+
163
+ # MigrationProxy is used to defer loading of the actual migration classes
164
+ # until they are needed
165
+ class MigrationProxy
166
+
167
+ attr_accessor :name, :version, :filename
168
+
169
+ delegate :migrate, :announce, :write, :to=>:migration
170
+
171
+ private
172
+
173
+ def migration
174
+ @migration ||= load_migration
175
+ end
176
+
177
+ def load_migration
178
+ require(File.expand_path(filename))
179
+ name.constantize
180
+ end
181
+
182
+ end
183
+
184
+ class Migrator#:nodoc:
185
+ class << self
186
+ def migrate(migrations_path, target_version = nil, mongoid_session = :default)
187
+ case
188
+ when target_version.nil? then up(migrations_path, target_version, mongoid_session)
189
+ when current_version > target_version then down(migrations_path, target_version, mongoid_session)
190
+ else up(migrations_path, target_version, mongoid_session)
191
+ end
192
+ end
193
+
194
+ def rollback(migrations_path, steps=1)
195
+ move(:down, migrations_path, steps)
196
+ end
197
+
198
+ def forward(migrations_path, steps=1)
199
+ move(:up, migrations_path, steps)
200
+ end
201
+
202
+ def up(migrations_path, target_version = nil, mongoid_session=:default)
203
+ self.new(:up, migrations_path, target_version, mongoid_session).migrate
204
+ end
205
+
206
+ def down(migrations_path, target_version = nil, mongoid_session=:default)
207
+ self.new(:down, migrations_path, target_version, mongoid_session).migrate
208
+ end
209
+
210
+ def run(direction, migrations_path, target_version)
211
+ self.new(direction, migrations_path, target_version).run
212
+ end
213
+
214
+ def migrations_path
215
+ 'db/migrate'
216
+ end
217
+
218
+ # def schema_migrations_table_name
219
+ # # Base.table_name_prefix + 'schema_migrations' + Base.table_name_suffix
220
+ # 'data_migrations'
221
+ # end
222
+
223
+ def get_all_versions(mongoid_session=:default)
224
+ new(nil, nil, nil, mongoid_session).get_all_versions
225
+ end
226
+
227
+ def current_version(mongoid_session=:default)
228
+ get_all_versions(mongoid_session).max || 0
229
+ end
230
+
231
+ def proper_table_name(name)
232
+ # Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
233
+ # name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
234
+ name
235
+ end
236
+
237
+ private
238
+
239
+ def move(direction, migrations_path, steps)
240
+ migrator = self.new(direction, migrations_path)
241
+ start_index = migrator.migrations.index(migrator.current_migration)
242
+
243
+ if start_index
244
+ finish = migrator.migrations[start_index + steps]
245
+ version = finish ? finish.version : 0
246
+ send(direction, migrations_path, version)
247
+ end
248
+ end
249
+ end
250
+
251
+ def initialize(direction, migrations_path, target_version = nil, mongoid_session=:default)
252
+ # raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
253
+ # Base.connection.initialize_schema_migrations_table
254
+ @direction, @migrations_path, @target_version, @mongoid_session = direction, migrations_path, target_version, mongoid_session
255
+ end
256
+
257
+ def get_all_versions
258
+ # table = Arel::Table.new(schema_migrations_table_name)
259
+ # Base.connection.select_values(table.project(table['version']).to_sql).map(&:to_i).sort
260
+ #
261
+ migration_model.all.map {|datamigration| datamigration.version.to_i }.sort
262
+ end
263
+
264
+ def current_version
265
+ migrated.last || 0
266
+ end
267
+
268
+ def current_migration
269
+ migrations.detect { |m| m.version == current_version }
270
+ end
271
+
272
+ def run
273
+ target = migrations.detect { |m| m.version == @target_version }
274
+ raise UnknownMigrationVersionError.new(@target_version) if target.nil?
275
+ unless (up? && migrated.include?(target.version.to_i)) || (down? && !migrated.include?(target.version.to_i))
276
+ target.migrate(@direction)
277
+ record_version_state_after_migrating(target.version)
278
+ end
279
+ end
280
+
281
+ def migrate
282
+ current = migrations.detect { |m| m.version == current_version }
283
+ target = migrations.detect { |m| m.version == @target_version }
284
+
285
+ if target.nil? && !@target_version.nil? && @target_version > 0
286
+ raise UnknownMigrationVersionError.new(@target_version)
287
+ end
288
+
289
+ start = up? ? 0 : (migrations.index(current) || 0)
290
+ finish = migrations.index(target) || migrations.size - 1
291
+ runnable = migrations[start..finish]
292
+
293
+ # skip the last migration if we're headed down, but not ALL the way down
294
+ runnable.pop if down? && !target.nil?
295
+
296
+ runnable.each do |migration|
297
+ Rails.logger.info "Migrating to #{migration.name} (#{migration.version})" if Rails.logger
298
+
299
+ # On our way up, we skip migrating the ones we've already migrated
300
+ next if up? && migrated.include?(migration.version.to_i)
301
+
302
+ # On our way down, we skip reverting the ones we've never migrated
303
+ if down? && !migrated.include?(migration.version.to_i)
304
+ migration.announce 'never migrated, skipping'; migration.write
305
+ next
306
+ end
307
+
308
+ # begin
309
+ # ddl_transaction do
310
+ # migration.migrate(@direction)
311
+ # record_version_state_after_migrating(migration.version)
312
+ # end
313
+ # rescue => e
314
+ # canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
315
+ # raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
316
+ # end
317
+ begin
318
+ migration.migrate(@direction)
319
+ record_version_state_after_migrating(migration.version)
320
+ rescue => e
321
+ raise StandardError, "An error has occurred, #{migration.version} and all later migrations canceled:\n\n#{e}", e.backtrace
322
+ end
323
+ end
324
+ end
325
+
326
+ def migrations
327
+ @migrations ||= begin
328
+ files = Dir["#{@migrations_path}/[0-9]*_*.rb"]
329
+
330
+ migrations = files.inject([]) do |klasses, file|
331
+ version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
332
+
333
+ raise IllegalMigrationNameError.new(file) unless version
334
+ version = version.to_i
335
+
336
+ if klasses.detect { |m| m.version == version }
337
+ raise DuplicateMigrationVersionError.new(version)
338
+ end
339
+
340
+ if klasses.detect { |m| m.name == name.camelize }
341
+ raise DuplicateMigrationNameError.new(name.camelize)
342
+ end
343
+
344
+ migration = MigrationProxy.new
345
+ migration.name = name.camelize
346
+ migration.version = version
347
+ migration.filename = file
348
+ klasses << migration
349
+ end
350
+
351
+ migrations = migrations.sort_by(&:version)
352
+ down? ? migrations.reverse : migrations
353
+ end
354
+ end
355
+
356
+ def pending_migrations
357
+ already_migrated = migrated
358
+ migrations.reject { |m| already_migrated.include?(m.version.to_i) }
359
+ end
360
+
361
+ def migrated
362
+ @migrated_versions ||= self.get_all_versions
363
+ end
364
+
365
+ private
366
+ def record_version_state_after_migrating(version)
367
+ # table = Arel::Table.new(self.class.schema_migrations_table_name)
368
+
369
+ @migrated_versions ||= []
370
+ # if down?
371
+ # @migrated_versions.delete(version)
372
+ # table.where(table["version"].eq(version.to_s)).delete
373
+ # else
374
+ # @migrated_versions.push(version).sort!
375
+ # table.insert table["version"] => version.to_s
376
+ # end
377
+ if down?
378
+ @migrated_versions.delete(version)
379
+ migration_model.where(:version => version.to_s).first.destroy
380
+ else
381
+ @migrated_versions.push(version).sort!
382
+ migration_model.create(:version => version.to_s)
383
+ end
384
+ end
385
+
386
+ def migration_model
387
+ @migration_model ||= begin
388
+ session = @mongoid_session
389
+ Class.new do
390
+ include Mongoid::Document
391
+ field :version
392
+ store_in session: session, collection: 'data_migrations'
393
+ end
394
+ end
395
+ end
396
+
397
+ def up?
398
+ @direction == :up
399
+ end
400
+
401
+ def down?
402
+ @direction == :down
403
+ end
404
+
405
+ # Wrap the migration in a transaction only if supported by the adapter.
406
+ def ddl_transaction(&block)
407
+ # if Base.connection.supports_ddl_transactions?
408
+ # Base.transaction { block.call }
409
+ # else
410
+ # block.call
411
+ # end
412
+ block.call
413
+ end
414
+ end
415
+ end
@@ -0,0 +1,23 @@
1
+ # encoding: utf-8
2
+ module Mongoid
3
+ # Specify whether or not to use timestamps for migration versions
4
+ # NOTE: newer style is a module
5
+ # Config.module_eval would work for both but still need to determine the type
6
+ # that's why we do it the ug way.
7
+ if Config.is_a? Class
8
+ # older mongoid style; pre 2.0.0.rc.1
9
+ Config.module_eval do
10
+ cattr_accessor :timestamped_migrations
11
+ class_variable_set(:@@timestamped_migrations, true) unless class_variable_get(:@@timestamped_migrations)
12
+
13
+ def self.reset
14
+ @@timestamped_migrations = true
15
+ end
16
+ end
17
+ else # module
18
+ Config.module_eval do
19
+ # newer mongoid style; >= 2.0.0.rc.1
20
+ option :timestamped_migrations, :default => true
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,18 @@
1
+ # encoding: utf-8
2
+
3
+ if defined?(Rails::Railtie)
4
+ module Rails #:nodoc:
5
+ module Mongoid #:nodoc:
6
+ class Railtie < Rails::Railtie
7
+ if config.respond_to?(:app_generators)
8
+ config.app_generators.orm :mongoid, :migration => true
9
+ else
10
+ config.generators.orm :mongoid, :migration => true
11
+ end
12
+ rake_tasks do
13
+ load "mongoid_rails_migrations/mongoid_ext/railties/database.rake"
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,93 @@
1
+ namespace :db do
2
+ unless Rake::Task.task_defined?("db:drop")
3
+ desc 'Drops all the collections for the database for the current Rails.env'
4
+ task :drop => :environment do
5
+ Mongoid.master.collections.each {|col| col.drop_indexes && col.drop unless ['system.indexes', 'system.users'].include?(col.name) }
6
+ end
7
+ end
8
+
9
+ unless Rake::Task.task_defined?("db:seed")
10
+ # if another ORM has defined db:seed, don't run it twice.
11
+ desc 'Load the seed data from db/seeds.rb'
12
+ task :seed => :environment do
13
+ seed_file = File.join(Rails.application.root, 'db', 'seeds.rb')
14
+ load(seed_file) if File.exist?(seed_file)
15
+ end
16
+ end
17
+
18
+ unless Rake::Task.task_defined?("db:setup")
19
+ desc 'Create the database, and initialize with the seed data'
20
+ task :setup => [ 'db:create', 'db:seed' ]
21
+ end
22
+
23
+ unless Rake::Task.task_defined?("db:reseed")
24
+ desc 'Delete data and seed'
25
+ task :reseed => [ 'db:drop', 'db:seed' ]
26
+ end
27
+
28
+ unless Rake::Task.task_defined?("db:create")
29
+ task :create => :environment do
30
+ # noop
31
+ end
32
+ end
33
+
34
+ desc 'Current database version'
35
+ task :version => :environment do
36
+ puts Mongoid::Migrator.current_version.to_s
37
+ end
38
+
39
+ desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
40
+ task :migrate => :environment do
41
+ Mongoid::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
42
+ Mongoid::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
43
+ end
44
+
45
+ namespace :migrate do
46
+ desc 'Rollback the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.'
47
+ task :redo => :environment do
48
+ if ENV["VERSION"]
49
+ Rake::Task["db:migrate:down"].invoke
50
+ Rake::Task["db:migrate:up"].invoke
51
+ else
52
+ Rake::Task["db:rollback"].invoke
53
+ Rake::Task["db:migrate"].invoke
54
+ end
55
+ end
56
+
57
+ desc 'Resets your database using your migrations for the current environment'
58
+ # should db:create be changed to db:setup? It makes more sense wanting to seed
59
+ task :reset => ["db:drop", "db:create", "db:migrate"]
60
+
61
+ desc 'Runs the "up" for a given migration VERSION.'
62
+ task :up => :environment do
63
+ version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
64
+ raise "VERSION is required" unless version
65
+ Mongoid::Migrator.run(:up, "db/migrate/", version)
66
+ end
67
+
68
+ desc 'Runs the "down" for a given migration VERSION.'
69
+ task :down => :environment do
70
+ version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
71
+ raise "VERSION is required" unless version
72
+ Mongoid::Migrator.run(:down, "db/migrate/", version)
73
+ end
74
+ end
75
+
76
+ desc 'Rolls the database back to the previous migration. Specify the number of steps with STEP=n'
77
+ task :rollback => :environment do
78
+ step = ENV['STEP'] ? ENV['STEP'].to_i : 1
79
+ Mongoid::Migrator.rollback('db/migrate/', step)
80
+ end
81
+
82
+ namespace :schema do
83
+ task :load do
84
+ # noop
85
+ end
86
+ end
87
+
88
+ namespace :test do
89
+ task :prepare do
90
+ # Stub out for MongoDB
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,3 @@
1
+ module MongoidRailsMigrations #:nodoc:
2
+ VERSION = '1.1.0'
3
+ end
@@ -0,0 +1,16 @@
1
+ require 'rails/generators/mongoid/mongoid_generator'
2
+
3
+ module Mongoid
4
+ module Generators
5
+ class MigrationGenerator < Base
6
+
7
+ def create_migration_file
8
+ migration_template "migration.rb", "db/migrate/#{file_name}.rb"
9
+ end
10
+
11
+ protected
12
+ attr_reader :migration_action
13
+
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,7 @@
1
+ class <%= migration_class_name %> < Mongoid::Migration
2
+ def self.up
3
+ end
4
+
5
+ def self.down
6
+ end
7
+ end
@@ -0,0 +1,26 @@
1
+ require 'rails/generators'
2
+
3
+ module Mongoid #:nodoc:
4
+ module Generators #:nodoc:
5
+ class Base < ::Rails::Generators::NamedBase #:nodoc:
6
+ include Rails::Generators::Migration
7
+
8
+ # A simple redef is fine because rails caches this path on class.inherited
9
+ # mongoid uses @_mongoid_source_root ||=, but that's not necessary
10
+ def self.source_root
11
+ File.expand_path("../../#{base_name}/#{generator_name}/templates", __FILE__)
12
+ end
13
+
14
+ # Implement the required interface for Rails::Generators::Migration.
15
+ def self.next_migration_number(dirname) #:nodoc:
16
+ next_migration_number = current_migration_number(dirname) + 1
17
+ if Mongoid.configure.timestamped_migrations
18
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
19
+ else
20
+ "%.3d" % next_migration_number
21
+ end
22
+ end
23
+
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,32 @@
1
+ require File.join(File.dirname(__FILE__), 'lib', 'mongoid_rails_migrations', 'version')
2
+
3
+ Gem::Specification.new do |s|
4
+ s.platform = Gem::Platform::RUBY
5
+ s.name = 'preplay_mongoid_rails_migrations'
6
+ s.version = MongoidRailsMigrations::VERSION
7
+ s.summary = 'Data migrations for Mongoid in Active Record style, minus column input.'
8
+ s.description = 'Migrations for the migrator.'
9
+
10
+ # only tested with 1.9.1, but let's go for it
11
+ s.required_ruby_version = '>= 1.8.6'
12
+ s.required_rubygems_version = '>= 1.3.6'
13
+
14
+ s.author = 'Alan Da Costa'
15
+ s.email = 'alandacosta@gmail.com.com'
16
+ s.date = %q{2012-09-04}
17
+ s.homepage = 'http://github.com/adacosta/mongoid_rails_migrations'
18
+
19
+ s.require_paths = ['lib']
20
+ s.files = Dir['.gitignore', 'Gemfile', 'Gemfile.lock', 'Rakefile', 'README.rdoc', 'mongoid_rails_migrations.gemspec', 'lib/**/*']
21
+ s.test_files = Dir['test/**/*']
22
+ s.has_rdoc = false
23
+
24
+ rails_version = '>= 3.2.0'
25
+
26
+ s.add_dependency('bundler', '>= 1.0.0')
27
+ s.add_dependency('rails', rails_version)
28
+ s.add_dependency('railties', rails_version)
29
+ s.add_dependency('activesupport', rails_version)
30
+ s.add_development_dependency('mongoid', '>= 3.0.0')
31
+ s.add_development_dependency('test-unit', '>= 2.5.0')
32
+ end
data/test/config.rb ADDED
@@ -0,0 +1,9 @@
1
+ require File.join(File.dirname(__FILE__), '..', 'lib', 'mongoid_rails_migrations')
2
+ require File.join(File.dirname(__FILE__), '..', 'lib', 'rails', 'generators', 'mongoid', 'mongoid_generator')
3
+
4
+ Mongoid.configure.connect_to('mongoid_test')
5
+
6
+ # require all models
7
+ Dir[File.join(File.dirname(__FILE__), 'models', '*.rb')].each { |file| require file }
8
+
9
+ MIGRATIONS_ROOT = File.join(File.dirname(__FILE__), 'migrations')
data/test/helper.rb ADDED
@@ -0,0 +1,33 @@
1
+ $:.unshift(File.dirname(__FILE__)) unless
2
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
3
+
4
+ require 'bundler/setup'
5
+ Bundler.require(:development_mongoid_rails_migrations)
6
+
7
+ require 'config'
8
+ require 'test/unit'
9
+
10
+ require 'rake'
11
+ require 'rake/testtask'
12
+ require 'rdoc/task'
13
+
14
+ # leave out active_record, in favor of a monogo adapter
15
+ %w(
16
+ action_controller
17
+ action_mailer
18
+ active_resource
19
+ rails/test_unit
20
+ mongoid
21
+ ).each do |framework|
22
+ begin
23
+ require "#{framework}/railtie"
24
+ rescue LoadError
25
+ end
26
+ end
27
+
28
+ module TestMongoidRailsMigrations
29
+ class Application < Rails::Application; end
30
+ end
31
+
32
+ # TestMongoidRailsMigrations::Application.initialize!
33
+ TestMongoidRailsMigrations::Application.load_tasks
@@ -0,0 +1,141 @@
1
+ require File.dirname(__FILE__) + '/helper'
2
+
3
+ class Mongoid::Migration
4
+ class <<self
5
+ attr_accessor :message_count
6
+
7
+ def puts(text="")
8
+ self.message_count ||= 0
9
+ self.message_count += 1
10
+ end
11
+ end
12
+ end
13
+
14
+ module Mongoid
15
+ class TestCase < ActiveSupport::TestCase #:nodoc:
16
+
17
+ def setup
18
+ Mongoid::Migration.verbose = true
19
+ # same as db:drop command in lib/mongoid_rails_migrations/mongoid_ext/railties/database.rake
20
+ Mongoid.default_session.drop
21
+ end
22
+
23
+ def teardown; end
24
+
25
+ def test_drop_works
26
+ assert_equal 0, Mongoid::Migrator.current_version, "db:drop should take us down to version 0"
27
+ end
28
+
29
+ def test_finds_migrations
30
+ assert Mongoid::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").migrations.size == 2
31
+ assert_equal 2, Mongoid::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").pending_migrations.size
32
+ end
33
+
34
+ def test_migrator_current_version
35
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 20100513054656)
36
+ assert_equal(20100513054656, Mongoid::Migrator.current_version)
37
+ end
38
+
39
+ def test_migrator
40
+ assert SurveySchema.first.nil?, "All SurveySchemas should be clear before migration run"
41
+
42
+ Mongoid::Migrator.up(MIGRATIONS_ROOT + "/valid")
43
+
44
+ assert_equal 20100513063902, Mongoid::Migrator.current_version
45
+ assert !SurveySchema.first.nil?
46
+
47
+ Mongoid::Migrator.down(MIGRATIONS_ROOT + "/valid")
48
+ assert_equal 0, Mongoid::Migrator.current_version
49
+
50
+ assert SurveySchema.create(:label => 'Questionable Survey')
51
+ assert_equal 1, SurveySchema.all.size
52
+ end
53
+
54
+ def test_migrator_two_up_and_one_down
55
+ assert SurveySchema.where(:label => 'Baseline Survey').first.nil?
56
+ assert_equal 0, SurveySchema.all.size
57
+
58
+ Mongoid::Migrator.up(MIGRATIONS_ROOT + "/valid", 20100513054656)
59
+
60
+ assert !SurveySchema.where(:label => 'Baseline Survey').first.nil?
61
+ assert_equal 1, SurveySchema.all.size
62
+
63
+ assert SurveySchema.where(:label => 'Improvement Plan Survey').first.nil?
64
+
65
+ Mongoid::Migrator.up(MIGRATIONS_ROOT + "/valid", 20100513063902)
66
+ assert_equal 20100513063902, Mongoid::Migrator.current_version
67
+
68
+ assert !SurveySchema.where(:label => 'Improvement Plan Survey').first.nil?
69
+ assert_equal 2, SurveySchema.all.size
70
+
71
+ Mongoid::Migrator.down(MIGRATIONS_ROOT + "/valid", 20100513054656)
72
+ assert_equal 20100513054656, Mongoid::Migrator.current_version
73
+
74
+ assert SurveySchema.where(:label => 'Improvement Plan Survey').first.nil?
75
+ assert !SurveySchema.where(:label => 'Baseline Survey').first.nil?
76
+ assert_equal 1, SurveySchema.all.size
77
+ end
78
+
79
+ def test_finds_pending_migrations
80
+ Mongoid::Migrator.up(MIGRATIONS_ROOT + "/valid", 20100513054656)
81
+ pending_migrations = Mongoid::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").pending_migrations
82
+
83
+ assert_equal 1, pending_migrations.size
84
+ assert_equal pending_migrations[0].version, 20100513063902
85
+ assert_equal pending_migrations[0].name, 'AddImprovementPlanSurveySchema'
86
+ end
87
+
88
+ def test_migrator_rollback
89
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
90
+ assert_equal(20100513063902, Mongoid::Migrator.current_version)
91
+
92
+ Mongoid::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
93
+ assert_equal(20100513054656, Mongoid::Migrator.current_version)
94
+
95
+ Mongoid::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
96
+ assert_equal(0, Mongoid::Migrator.current_version)
97
+ end
98
+
99
+ def test_migrator_forward
100
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 20100513054656)
101
+ assert_equal(20100513054656, Mongoid::Migrator.current_version)
102
+
103
+ Mongoid::Migrator.forward(MIGRATIONS_ROOT + "/valid", 20100513063902)
104
+ assert_equal(20100513063902, Mongoid::Migrator.current_version)
105
+ end
106
+
107
+ def test_migrator_with_duplicate_names
108
+ assert_raise(Mongoid::DuplicateMigrationNameError) do
109
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate/names", nil)
110
+ end
111
+ end
112
+
113
+ def test_migrator_with_duplicate_versions
114
+ assert_raise(Mongoid::DuplicateMigrationVersionError) do
115
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate/versions", nil)
116
+ end
117
+ end
118
+
119
+ def test_migrator_with_missing_version_numbers
120
+ assert_raise(Mongoid::UnknownMigrationVersionError) do
121
+ Mongoid::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 500)
122
+ end
123
+ end
124
+
125
+ def test_default_state_of_timestamped_migrations
126
+ assert Mongoid.configure.timestamped_migrations, "Mongoid.configure.timestamped_migrations should default to true"
127
+ end
128
+
129
+ def test_timestamped_migrations_generates_non_sequential_next_number
130
+ next_number = Mongoid::Generators::Base.next_migration_number(MIGRATIONS_ROOT + "/valid")
131
+ assert_not_equal "20100513063903", next_number
132
+ end
133
+
134
+ def test_turning_off_timestamped_migrations
135
+ Mongoid.configure.timestamped_migrations = false
136
+ next_number = Mongoid::Generators::Base.next_migration_number(MIGRATIONS_ROOT + "/valid")
137
+ assert_equal "20100513063903", next_number
138
+ end
139
+
140
+ end
141
+ end
@@ -0,0 +1,9 @@
1
+ class AddDuplicateSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:label => 'Duplicate Survey')
4
+ end
5
+
6
+ def self.down
7
+ SurveySchema.where(:label => 'Duplicate Survey').first.destroy
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ class AddDuplicateSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:label => 'Duplicate Survey')
4
+ end
5
+
6
+ def self.down
7
+ SurveySchema.where(:label => 'Duplicate Survey').first.destroy
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ class AddDuplicateSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:label => 'Duplicate Survey')
4
+ end
5
+
6
+ def self.down
7
+ SurveySchema.where(:label => 'Duplicate Survey').first.destroy
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ class AddDuplicateSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:label => 'Duplicate Survey')
4
+ end
5
+
6
+ def self.down
7
+ SurveySchema.where(:label => 'Duplicate Survey').first.destroy
8
+ end
9
+ end
@@ -0,0 +1,10 @@
1
+ class AddBaselineSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:id => '4c47bf87f3395c339c000001',
4
+ :label => 'Baseline Survey')
5
+ end
6
+
7
+ def self.down
8
+ SurveySchema.where(:label => 'Baseline Survey').first.destroy
9
+ end
10
+ end
@@ -0,0 +1,9 @@
1
+ class AddImprovementPlanSurveySchema < Mongoid::Migration
2
+ def self.up
3
+ SurveySchema.create(:label => 'Improvement Plan Survey')
4
+ end
5
+
6
+ def self.down
7
+ SurveySchema.where(:label => 'Improvement Plan Survey').first.destroy
8
+ end
9
+ end
@@ -0,0 +1,6 @@
1
+ class SurveySchema
2
+ include Mongoid::Document
3
+ include Mongoid::Timestamps
4
+
5
+ field :label
6
+ end
metadata ADDED
@@ -0,0 +1,162 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: preplay_mongoid_rails_migrations
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alan Da Costa
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2012-09-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: 1.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: 1.0.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rails
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: 3.2.0
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: 3.2.0
41
+ - !ruby/object:Gem::Dependency
42
+ name: railties
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: 3.2.0
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: 3.2.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: activesupport
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: 3.2.0
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: 3.2.0
69
+ - !ruby/object:Gem::Dependency
70
+ name: mongoid
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - '>='
74
+ - !ruby/object:Gem::Version
75
+ version: 3.0.0
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - '>='
81
+ - !ruby/object:Gem::Version
82
+ version: 3.0.0
83
+ - !ruby/object:Gem::Dependency
84
+ name: test-unit
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - '>='
88
+ - !ruby/object:Gem::Version
89
+ version: 2.5.0
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - '>='
95
+ - !ruby/object:Gem::Version
96
+ version: 2.5.0
97
+ description: Migrations for the migrator.
98
+ email: alandacosta@gmail.com.com
99
+ executables: []
100
+ extensions: []
101
+ extra_rdoc_files: []
102
+ files:
103
+ - .gitignore
104
+ - Gemfile
105
+ - Gemfile.lock
106
+ - Rakefile
107
+ - README.rdoc
108
+ - mongoid_rails_migrations.gemspec
109
+ - lib/mongoid_rails_migrations/active_record_ext/migrations.rb
110
+ - lib/mongoid_rails_migrations/mongoid_ext/mongoid.rb
111
+ - lib/mongoid_rails_migrations/mongoid_ext/railtie.rb
112
+ - lib/mongoid_rails_migrations/mongoid_ext/railties/database.rake
113
+ - lib/mongoid_rails_migrations/version.rb
114
+ - lib/mongoid_rails_migrations.rb
115
+ - lib/rails/generators/mongoid/migration/migration_generator.rb
116
+ - lib/rails/generators/mongoid/migration/templates/migration.rb
117
+ - lib/rails/generators/mongoid/mongoid_generator.rb
118
+ - test/config.rb
119
+ - test/helper.rb
120
+ - test/migration_test.rb
121
+ - test/migrations/duplicate/names/20100513073457_add_duplicate_survey_schema.rb
122
+ - test/migrations/duplicate/names/20100513073724_add_duplicate_survey_schema.rb
123
+ - test/migrations/duplicate/versions/20100513073457_add_another_duplicate_survey_schema.rb
124
+ - test/migrations/duplicate/versions/20100513073457_add_duplicate_survey_schema.rb
125
+ - test/migrations/valid/20100513054656_add_baseline_survey_schema.rb
126
+ - test/migrations/valid/20100513063902_add_improvement_plan_survey_schema.rb
127
+ - test/models/survey_schema.rb
128
+ homepage: http://github.com/adacosta/mongoid_rails_migrations
129
+ licenses: []
130
+ metadata: {}
131
+ post_install_message:
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - '>='
138
+ - !ruby/object:Gem::Version
139
+ version: 1.8.6
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - '>='
143
+ - !ruby/object:Gem::Version
144
+ version: 1.3.6
145
+ requirements: []
146
+ rubyforge_project:
147
+ rubygems_version: 2.0.3
148
+ signing_key:
149
+ specification_version: 4
150
+ summary: Data migrations for Mongoid in Active Record style, minus column input.
151
+ test_files:
152
+ - test/config.rb
153
+ - test/helper.rb
154
+ - test/migration_test.rb
155
+ - test/migrations/duplicate/names/20100513073457_add_duplicate_survey_schema.rb
156
+ - test/migrations/duplicate/names/20100513073724_add_duplicate_survey_schema.rb
157
+ - test/migrations/duplicate/versions/20100513073457_add_another_duplicate_survey_schema.rb
158
+ - test/migrations/duplicate/versions/20100513073457_add_duplicate_survey_schema.rb
159
+ - test/migrations/valid/20100513054656_add_baseline_survey_schema.rb
160
+ - test/migrations/valid/20100513063902_add_improvement_plan_survey_schema.rb
161
+ - test/models/survey_schema.rb
162
+ has_rdoc: false