4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/sqldump.rb', line 4
def sqldump(user, pass, db)
time = Time.new
date = "#{time.year}-#{time.month}-#{time.day}"
begin
my = Mysql.new('localhost', user, pass, db)
res = my.query("show tables")
tables = []
num_tables = res.num_rows
num_tables.times do
tables.push(res.fetch_row)
end
tables.each do |tbl|
res = my.query("show create table #{tbl}")
create = ''
res.each_hash do |x|
create = "#{x['Create Table']};"
end
File.open("#{db}_#{date}.sql", "a") do |file|
file.puts(create)
end
res = my.query("select * from #{tbl}")
num_rows = res.num_rows
content = []
num_rows.times do
content.push(res.fetch_row.join("_____"))
end
res = my.query("select * from #{tbl}")
num_rows = res.num_rows
content = []
num_rows.times do
content.push(res.fetch_row.join("_____"))
end
content.each do |cont|
res = my.query("explain #{tbl}")
num_cats = res.num_rows
y = 1
cats = []
File.open("#{db}_#{date}.sql", "a") do |file|
file.print("insert into #{tbl}(")
end
res.each_hash do |x|
File.open("#{db}_#{date}.sql", "a") do |file|
file.print("#{x['Field']}") if y == num_cats
file.print("#{x['Field']}, ") if y != num_cats
end
y += 1
end
File.open("#{db}_#{date}.sql", "a") do |file|
file.print(") values(")
end
cont = cont.gsub(/'/, "\\\\'")
cont = cont.gsub(/_____/, "', '")
File.open("#{db}_#{date}.sql", "a") do |file|
file.puts("'#{cont}');")
end
end
end
rescue Mysql::Error => e
puts "MySQL dump of #{db} failed!"
puts "#{e.errno}: #{e.error}"
puts "Exiting for safety"
exit
ensure
my.close
end
cpuser = Dir.pwd.split('/')[2]
end
|