dm-hibernate-migrations 1.0.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.
Files changed (40) hide show
  1. data/lib/dm-migrations.rb +3 -0
  2. data/lib/dm-migrations/adapters/dm-do-adapter.rb +284 -0
  3. data/lib/dm-migrations/adapters/dm-mysql-adapter.rb +283 -0
  4. data/lib/dm-migrations/adapters/dm-oracle-adapter.rb +321 -0
  5. data/lib/dm-migrations/adapters/dm-postgres-adapter.rb +159 -0
  6. data/lib/dm-migrations/adapters/dm-sqlite-adapter.rb +96 -0
  7. data/lib/dm-migrations/adapters/dm-sqlserver-adapter.rb +177 -0
  8. data/lib/dm-migrations/adapters/dm-yaml-adapter.rb +23 -0
  9. data/lib/dm-migrations/auto_migration.rb +237 -0
  10. data/lib/dm-migrations/migration.rb +217 -0
  11. data/lib/dm-migrations/migration_runner.rb +85 -0
  12. data/lib/dm-migrations/sql.rb +5 -0
  13. data/lib/dm-migrations/sql/column.rb +5 -0
  14. data/lib/dm-migrations/sql/mysql.rb +53 -0
  15. data/lib/dm-migrations/sql/postgres.rb +78 -0
  16. data/lib/dm-migrations/sql/sqlite.rb +45 -0
  17. data/lib/dm-migrations/sql/table.rb +15 -0
  18. data/lib/dm-migrations/sql/table_creator.rb +102 -0
  19. data/lib/dm-migrations/sql/table_modifier.rb +51 -0
  20. data/lib/spec/example/migration_example_group.rb +73 -0
  21. data/lib/spec/matchers/migration_matchers.rb +106 -0
  22. data/spec/integration/auto_migration_spec.rb +506 -0
  23. data/spec/integration/migration_runner_spec.rb +89 -0
  24. data/spec/integration/migration_spec.rb +138 -0
  25. data/spec/integration/sql_spec.rb +190 -0
  26. data/spec/isolated/require_after_setup_spec.rb +30 -0
  27. data/spec/isolated/require_before_setup_spec.rb +30 -0
  28. data/spec/isolated/require_spec.rb +25 -0
  29. data/spec/rcov.opts +6 -0
  30. data/spec/spec.opts +4 -0
  31. data/spec/spec_helper.rb +16 -0
  32. data/spec/unit/migration_spec.rb +453 -0
  33. data/spec/unit/sql/column_spec.rb +14 -0
  34. data/spec/unit/sql/postgres_spec.rb +97 -0
  35. data/spec/unit/sql/sqlite_extensions_spec.rb +108 -0
  36. data/spec/unit/sql/table_creator_spec.rb +94 -0
  37. data/spec/unit/sql/table_modifier_spec.rb +49 -0
  38. data/spec/unit/sql/table_spec.rb +28 -0
  39. data/spec/unit/sql_spec.rb +7 -0
  40. metadata +157 -0
@@ -0,0 +1,217 @@
1
+ require 'benchmark'
2
+
3
+ require 'dm-migrations/sql'
4
+
5
+ module DataMapper
6
+ class DuplicateMigrationNameError < StandardError
7
+ def initialize(migration)
8
+ super("Duplicate Migration Name: '#{migration.name}', version: #{migration.position}")
9
+ end
10
+ end
11
+
12
+ class Migration
13
+ include SQL
14
+
15
+ attr_accessor :position, :name, :database, :adapter
16
+
17
+ def initialize( position, name, opts = {}, &block )
18
+ @position, @name = position, name
19
+ @options = opts
20
+
21
+ @database = DataMapper.repository(@options[:database] || :default)
22
+ @adapter = @database.adapter
23
+
24
+ if @adapter.respond_to?(:dialect)
25
+ begin
26
+ @adapter.extend(SQL.const_get("#{@adapter.dialect}"))
27
+ rescue NameError
28
+ raise "Unsupported Migration Adapter #{@adapter.class} with SQL dialect #{@adapter.dialect}"
29
+ end
30
+ else
31
+ raise "Unsupported Migration Adapter #{@adapter.class}"
32
+ end
33
+
34
+ @verbose = @options.has_key?(:verbose) ? @options[:verbose] : true
35
+
36
+ @up_action = lambda {}
37
+ @down_action = lambda {}
38
+
39
+ instance_eval &block
40
+ end
41
+
42
+ # define the actions that should be performed on an up migration
43
+ def up(&block)
44
+ @up_action = block
45
+ end
46
+
47
+ # define the actions that should be performed on a down migration
48
+ def down(&block)
49
+ @down_action = block
50
+ end
51
+
52
+ # perform the migration by running the code in the #up block
53
+ def perform_up
54
+ result = nil
55
+ if needs_up?
56
+ # TODO: fix this so it only does transactions for databases that support create/drop
57
+ # database.transaction.commit do
58
+ say_with_time "== Performing Up Migration ##{position}: #{name}", 0 do
59
+ result = @up_action.call
60
+ end
61
+ update_migration_info(:up)
62
+ # end
63
+ end
64
+ result
65
+ end
66
+
67
+ # un-do the migration by running the code in the #down block
68
+ def perform_down
69
+ result = nil
70
+ if needs_down?
71
+ # TODO: fix this so it only does transactions for databases that support create/drop
72
+ # database.transaction.commit do
73
+ say_with_time "== Performing Down Migration ##{position}: #{name}", 0 do
74
+ result = @down_action.call
75
+ end
76
+ update_migration_info(:down)
77
+ # end
78
+ end
79
+ result
80
+ end
81
+
82
+ # execute raw SQL
83
+ def execute(sql, *bind_values)
84
+ say_with_time(sql) do
85
+ @adapter.execute(sql, *bind_values)
86
+ end
87
+ end
88
+
89
+ def create_table(table_name, opts = {}, &block)
90
+ execute TableCreator.new(@adapter, table_name, opts, &block).to_sql
91
+ end
92
+
93
+ def drop_table(table_name, opts = {})
94
+ execute "DROP TABLE #{@adapter.send(:quote_name, table_name.to_s)}"
95
+ end
96
+
97
+ def modify_table(table_name, opts = {}, &block)
98
+ TableModifier.new(@adapter, table_name, opts, &block).statements.each do |sql|
99
+ execute(sql)
100
+ end
101
+ end
102
+
103
+ def create_index(table_name, *columns_and_options)
104
+ if columns_and_options.last.is_a?(Hash)
105
+ opts = columns_and_options.pop
106
+ else
107
+ opts = {}
108
+ end
109
+ columns = columns_and_options.flatten
110
+
111
+ opts[:name] ||= "#{opts[:unique] ? 'unique_' : ''}index_#{table_name}_#{columns.join('_')}"
112
+
113
+ execute <<-SQL.compress_lines
114
+ CREATE #{opts[:unique] ? 'UNIQUE ' : '' }INDEX #{quote_column_name(opts[:name])} ON
115
+ #{quote_table_name(table_name)} (#{columns.map { |c| quote_column_name(c) }.join(', ') })
116
+ SQL
117
+ end
118
+
119
+ # Orders migrations by position, so we know what order to run them in.
120
+ # First order by position, then by name, so at least the order is predictable.
121
+ def <=> other
122
+ if self.position == other.position
123
+ self.name.to_s <=> other.name.to_s
124
+ else
125
+ self.position <=> other.position
126
+ end
127
+ end
128
+
129
+ # Output some text. Optional indent level
130
+ def say(message, indent = 4)
131
+ write "#{" " * indent} #{message}"
132
+ end
133
+
134
+ # Time how long the block takes to run, and output it with the message.
135
+ def say_with_time(message, indent = 2)
136
+ say(message, indent)
137
+ result = nil
138
+ time = Benchmark.measure { result = yield }
139
+ say("-> %.4fs" % time.real, indent)
140
+ result
141
+ end
142
+
143
+ # output the given text, but only if verbose mode is on
144
+ def write(text="")
145
+ puts text if @verbose
146
+ end
147
+
148
+ # Inserts or removes a row into the `migration_info` table, so we can mark this migration as run, or un-done
149
+ def update_migration_info(direction)
150
+ save, @verbose = @verbose, false
151
+
152
+ create_migration_info_table_if_needed
153
+
154
+ if direction.to_sym == :up
155
+ execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})")
156
+ elsif direction.to_sym == :down
157
+ execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
158
+ end
159
+ @verbose = save
160
+ end
161
+
162
+ def create_migration_info_table_if_needed
163
+ save, @verbose = @verbose, false
164
+ unless migration_info_table_exists?
165
+ execute("CREATE TABLE #{migration_info_table} (#{migration_name_column} VARCHAR(255) UNIQUE)")
166
+ end
167
+ @verbose = save
168
+ end
169
+
170
+ # Quote the name of the migration for use in SQL
171
+ def quoted_name
172
+ "'#{name}'"
173
+ end
174
+
175
+ def migration_info_table_exists?
176
+ adapter.storage_exists?('migration_info')
177
+ end
178
+
179
+ # Fetch the record for this migration out of the migration_info table
180
+ def migration_record
181
+ return [] unless migration_info_table_exists?
182
+ @adapter.select("SELECT #{migration_name_column} FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
183
+ end
184
+
185
+ # True if the migration needs to be run
186
+ def needs_up?
187
+ return true unless migration_info_table_exists?
188
+ migration_record.empty?
189
+ end
190
+
191
+ # True if the migration has already been run
192
+ def needs_down?
193
+ return false unless migration_info_table_exists?
194
+ ! migration_record.empty?
195
+ end
196
+
197
+ # Quoted table name, for the adapter
198
+ def migration_info_table
199
+ @migration_info_table ||= quote_table_name('migration_info')
200
+ end
201
+
202
+ # Quoted `migration_name` column, for the adapter
203
+ def migration_name_column
204
+ @migration_name_column ||= quote_column_name('migration_name')
205
+ end
206
+
207
+ def quote_table_name(table_name)
208
+ # TODO: Fix this for 1.9 - can't use this hack to access a private method
209
+ @adapter.send(:quote_name, table_name.to_s)
210
+ end
211
+
212
+ def quote_column_name(column_name)
213
+ # TODO: Fix this for 1.9 - can't use this hack to access a private method
214
+ @adapter.send(:quote_name, column_name.to_s)
215
+ end
216
+ end
217
+ end
@@ -0,0 +1,85 @@
1
+ require 'dm-migrations/migration'
2
+
3
+ module DataMapper
4
+ module MigrationRunner
5
+ # Creates a new migration, and adds it to the list of migrations to be run.
6
+ # Migrations can be defined in any order, they will be sorted and run in the
7
+ # correct order.
8
+ #
9
+ # The order that migrations are run in is set by the first argument. It is not
10
+ # neccessary that this be unique; migrations with the same version number are
11
+ # expected to be able to be run in any order.
12
+ #
13
+ # The second argument is the name of the migration. This name is used internally
14
+ # to track if the migration has been run. It is required that this name be unique
15
+ # across all migrations.
16
+ #
17
+ # Addtionally, it accepts a number of options:
18
+ # * <tt>:database</tt> If you defined several DataMapper::database instances use this
19
+ # to choose which one to run the migration gagainst. Defaults to <tt>:default</tt>.
20
+ # Migrations are tracked individually per database.
21
+ # * <tt>:verbose</tt> true/false, defaults to true. Determines if the migration should
22
+ # output its status messages when it runs.
23
+ #
24
+ # Example of a simple migration:
25
+ #
26
+ # migration( 1, :create_people_table ) do
27
+ # up do
28
+ # create_table :people do
29
+ # column :id, Integer, :serial => true
30
+ # column :name, String, :size => 50
31
+ # column :age, Integer
32
+ # end
33
+ # end
34
+ # down do
35
+ # drop_table :people
36
+ # end
37
+ # end
38
+ #
39
+ # Its recommended that you stick with raw SQL for migrations that manipulate data. If
40
+ # you write a migration using a model, then later change the model, there's a
41
+ # possibility the migration will no longer work. Using SQL will always work.
42
+ def migration( number, name, opts = {}, &block )
43
+ raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s)
44
+
45
+ migrations << DataMapper::Migration.new( number, name.to_s, opts, &block )
46
+ end
47
+
48
+ # Run all migrations that need to be run. In most cases, this would be called by a
49
+ # rake task as part of a larger project, but this provides the ability to run them
50
+ # in a script or test.
51
+ #
52
+ # has an optional argument 'level' which if supplied, only performs the migrations
53
+ # with a position less than or equal to the level.
54
+ def migrate_up!(level = nil)
55
+ migrations.sort.each do |migration|
56
+ if level.nil?
57
+ migration.perform_up()
58
+ else
59
+ migration.perform_up() if migration.position <= level.to_i
60
+ end
61
+ end
62
+ end
63
+
64
+ # Run all the down steps for the migrations that have already been run.
65
+ #
66
+ # has an optional argument 'level' which, if supplied, only performs the
67
+ # down migrations with a postion greater than the level.
68
+ def migrate_down!(level = nil)
69
+ migrations.sort.reverse.each do |migration|
70
+ if level.nil?
71
+ migration.perform_down()
72
+ else
73
+ migration.perform_down() if migration.position > level.to_i
74
+ end
75
+ end
76
+ end
77
+
78
+ def migrations
79
+ @migrations ||= []
80
+ end
81
+
82
+ end
83
+ end
84
+
85
+ include DataMapper::MigrationRunner
@@ -0,0 +1,5 @@
1
+ require 'dm-migrations/sql/table_creator'
2
+ require 'dm-migrations/sql/table_modifier'
3
+ require 'dm-migrations/sql/sqlite'
4
+ require 'dm-migrations/sql/mysql'
5
+ require 'dm-migrations/sql/postgres'
@@ -0,0 +1,5 @@
1
+ module SQL
2
+ class Column
3
+ attr_accessor :name, :type, :not_null, :default_value, :primary_key, :unique
4
+ end
5
+ end
@@ -0,0 +1,53 @@
1
+ require 'dm-migrations/sql/table'
2
+
3
+ module SQL
4
+ module Mysql
5
+
6
+ def supports_schema_transactions?
7
+ false
8
+ end
9
+
10
+ def table(table_name)
11
+ SQL::Mysql::Table.new(self, table_name)
12
+ end
13
+
14
+ def recreate_database
15
+ execute "DROP DATABASE #{schema_name}"
16
+ execute "CREATE DATABASE #{schema_name}"
17
+ execute "USE #{schema_name}"
18
+ end
19
+
20
+ def supports_serial?
21
+ true
22
+ end
23
+
24
+ def table_options
25
+ " ENGINE = InnoDB CHARACTER SET #{character_set} COLLATE #{collation}"
26
+ end
27
+
28
+ def property_schema_statement(connection, schema)
29
+ if supports_serial? && schema[:serial]
30
+ statement = "#{schema[:quote_column_name]} SERIAL PRIMARY KEY"
31
+ else
32
+ super
33
+ end
34
+ end
35
+
36
+ class Table
37
+ def initialize(adapter, table_name)
38
+ @columns = []
39
+ adapter.table_info(table_name).each do |col_struct|
40
+ @columns << SQL::Mysql::Column.new(col_struct)
41
+ end
42
+ end
43
+ end
44
+
45
+ class Column
46
+ def initialize(col_struct)
47
+ @name, @type, @default_value, @primary_key = col_struct.name, col_struct.type, col_struct.dflt_value, col_struct.pk
48
+
49
+ @not_null = col_struct.notnull == 0
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,78 @@
1
+ module SQL
2
+ module Postgres
3
+
4
+ def supports_schema_transactions?
5
+ true
6
+ end
7
+
8
+ def table(table_name)
9
+ SQL::Postgres::Table.new(self, table_name)
10
+ end
11
+
12
+ def recreate_database
13
+ execute 'DROP SCHEMA IF EXISTS test CASCADE'
14
+ execute 'CREATE SCHEMA test'
15
+ execute 'SET search_path TO test'
16
+ end
17
+
18
+ def supports_serial?
19
+ true
20
+ end
21
+
22
+ def property_schema_statement(connection, schema)
23
+ if supports_serial? && schema[:serial]
24
+ statement = "#{schema[:quote_column_name]} SERIAL PRIMARY KEY"
25
+ else
26
+ statement = super
27
+ if schema.has_key?(:sequence_name)
28
+ statement << " DEFAULT nextval('#{schema[:sequence_name]}') NOT NULL"
29
+ end
30
+ statement
31
+ end
32
+ statement
33
+ end
34
+
35
+ def table_options
36
+ ''
37
+ end
38
+
39
+ class Table < SQL::Table
40
+ def initialize(adapter, table_name)
41
+ @adapter, @name = adapter, table_name
42
+ @columns = []
43
+ adapter.query_table(table_name).each do |col_struct|
44
+ @columns << SQL::Postgres::Column.new(col_struct)
45
+ end
46
+
47
+ query_column_constraints
48
+ end
49
+
50
+ def query_column_constraints
51
+ @adapter.select(
52
+ "SELECT * FROM information_schema.table_constraints WHERE table_name='#{@name}' AND table_schema=current_schema()"
53
+ ).each do |table_constraint|
54
+ @adapter.select(
55
+ "SELECT * FROM information_schema.constraint_column_usage WHERE constraint_name='#{table_constraint.constraint_name}' AND table_schema=current_schema()"
56
+ ).each do |constrained_column|
57
+ @columns.each do |column|
58
+ if column.name == constrained_column.column_name
59
+ case table_constraint.constraint_type
60
+ when "UNIQUE" then column.unique = true
61
+ when "PRIMARY KEY" then column.primary_key = true
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
69
+
70
+ class Column < SQL::Column
71
+ def initialize(col_struct)
72
+ @name, @type, @default_value = col_struct.column_name, col_struct.data_type, col_struct.column_default
73
+
74
+ @not_null = col_struct.is_nullable != "YES"
75
+ end
76
+ end
77
+ end
78
+ end