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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
# File 'lib/pgcp/transport.rb', line 32
def copy_table(src_tablename, dest_tablename=nil, options={})
dest_tablename ||= src_tablename
options[:create_schema] = true if options[:create_schema].nil?
options[:skip_indexes] = false if options[:skipe_indexes].nil?
Pgcp.logger.info "Start to copy from table #{src_tablename} to table #{dest_tablename}"
src_table = QualifiedName.new(src_tablename)
dest_table = QualifiedName.new(dest_tablename)
dest_table.schema_name = options[:force_schema] if not options[:force_schema].nil?
src_conn = Postgres.new(@src_dbconfig)
dest_conn = Postgres.new(@dest_dbconfig)
dest_conn.exec "CREATE SCHEMA IF NOT EXISTS #{dest_table.schema_name};" if options[:create_schema]
src_indexes = src_conn.get_indexes(src_table.schema_name, src_table.table_name)
if dest_conn.table_exist?(src_table.schema_name, src_table.table_name)
Pgcp.logger.info "Destination table already exists, creating temporary table"
temp_table = QualifiedName.new("#{dest_table.schema_name}.temp_#{SecureRandom.hex}")
create_table_statement =
src_conn.get_create_table_statement(src_table.schema_name,
src_table.table_name,
temp_table.schema_name,
temp_table.table_name)
begin
dest_conn.exec(create_table_statement)
Pgcp.logger.info "Copying table data to temporary table. This could take a while..."
direct_copy(src_table.full_name, temp_table.full_name)
Pgcp.logger.info "Hotswapping to destination table #{dest_tablename}"
dest_conn.hotswap_table(dest_table.schema_name, temp_table.table_name, dest_table.table_name)
Pgcp.logger.info "Done copying table data."
rescue Exception => e
Pgcp.logger.error(e.message)
return
ensure
dest_conn.drop_table(temp_table.schema_name, temp_table.table_name)
end
else
Pgcp.logger.info "Destination table does not exist, creating destination table."
create_table_statement =
src_conn.get_create_table_statement(src_table.schema_name,
src_table.table_name,
dest_table.schema_name,
dest_table.table_name)
dest_conn.exec(create_table_statement)
Pgcp.logger.info "Copying table data to destination table. This could take a while..."
direct_copy(src_table.full_name, dest_table.full_name)
Pgcp.logger.info "Copying table data to destination table done."
end
unless options[:skip_indexes]
Pgcp.logger.info "Copying table indexes to destination table..."
dest_conn.create_indexes(dest_table.schema_name, dest_table.table_name, src_indexes)
Pgcp.logger.info "Done copying table indexes."
end
end
|