Module: Taps::Schema

Extended by:
Schema
Included in:
Schema
Defined in:
lib/taps/schema.rb

Instance Method Summary collapse

Instance Method Details

#connection(database_url) ⇒ Object



35
36
37
38
39
40
# File 'lib/taps/schema.rb', line 35

def connection(database_url)
	config = create_config(database_url)
	c = ActiveRecord::Base.establish_connection(config)
	Taps::AdapterHacks.load(config['adapter'])
	c
end

#create_config(url) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/taps/schema.rb', line 12

def create_config(url)
	uri = URI.parse(url)
	adapter = uri.scheme
	adapter = 'postgresql' if adapter == 'postgres'
	adapter = 'sqlite3' if adapter == 'sqlite'
	config = {
		'adapter' => adapter,
		'database' => uri.path.blank? ? uri.host : uri.path.split('/')[1],
		'username' => uri.user,
		'password' => uri.password,
		'host' => uri.host,
	}
	config = sqlite_config(url) if config['adapter'] == 'sqlite3'
	config
end

#dump(database_url) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/taps/schema.rb', line 42

def dump(database_url)
	connection(database_url)

	stream = StringIO.new
	ActiveRecord::SchemaDumper.ignore_tables = []
	ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
	stream.string
end

#dump_without_indexes(database_url) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/taps/schema.rb', line 51

def dump_without_indexes(database_url)
	schema = dump(database_url)
	schema.split("\n").collect do |line|
		if line =~ /^\s+add_index/
			line = "##{line}"
		end
		line
	end.join("\n")
end

#indexes(database_url) ⇒ Object



61
62
63
64
65
66
# File 'lib/taps/schema.rb', line 61

def indexes(database_url)
	schema = dump(database_url)
	schema.split("\n").collect do |line|
		line if line =~ /^\s+add_index/
	end.uniq.join("\n")
end

#load(database_url, schema) ⇒ Object



68
69
70
71
# File 'lib/taps/schema.rb', line 68

def load(database_url, schema)
	connection(database_url)
	eval(schema)
end

#load_indexes(database_url, indexes) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/taps/schema.rb', line 73

def load_indexes(database_url, indexes)
	connection(database_url)

	schema =<<EORUBY
ActiveRecord::Schema.define do
#{indexes}
end
EORUBY
	eval(schema)
end

#reset_db_sequences(database_url) ⇒ Object



84
85
86
87
88
89
90
91
92
# File 'lib/taps/schema.rb', line 84

def reset_db_sequences(database_url)
	connection(database_url)

	if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
		ActiveRecord::Base.connection.tables.each do |table|
			ActiveRecord::Base.connection.reset_pk_sequence!(table)
		end
	end
end

#sqlite_config(url) ⇒ Object



28
29
30
31
32
33
# File 'lib/taps/schema.rb', line 28

def sqlite_config(url)
	m = %r{(sqlite3?)://(.+)}.match(url)
	database = m[2]
	database, q = database.split('?')
	{ 'adapter' => 'sqlite3', 'database' => database }
end