Class: Mysql2psql::PostgresDbWriter

Inherits:
PostgresWriter show all
Defined in:
lib/mysql2psql/postgres_db_writer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from PostgresWriter

#column_description, #column_type, #column_type_info, #process_row, #truncate

Constructor Details

#initialize(options) ⇒ PostgresDbWriter

Returns a new instance of PostgresDbWriter.



10
11
12
13
14
15
16
# File 'lib/mysql2psql/postgres_db_writer.rb', line 10

def initialize(options)
  @hostname, @login, @password, @database, @port =  
    options.pghostname('localhost'), options.pgusername, 
    options.pgpassword, options.pgdatabase, options.pgport(5432).to_s
  @database, @schema = database.split(":")
  open
end

Instance Attribute Details

#connObject (readonly)

Returns the value of attribute conn.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def conn
  @conn
end

#databaseObject (readonly)

Returns the value of attribute database.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def database
  @database
end

#hostnameObject (readonly)

Returns the value of attribute hostname.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def hostname
  @hostname
end

#loginObject (readonly)

Returns the value of attribute login.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def 
  @login
end

#passwordObject (readonly)

Returns the value of attribute password.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def password
  @password
end

#portObject (readonly)

Returns the value of attribute port.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def port
  @port
end

#schemaObject (readonly)

Returns the value of attribute schema.



8
9
10
# File 'lib/mysql2psql/postgres_db_writer.rb', line 8

def schema
  @schema
end

Instance Method Details

#closeObject



27
28
29
# File 'lib/mysql2psql/postgres_db_writer.rb', line 27

def close
  @conn.close
end

#exists?(relname) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
34
# File 'lib/mysql2psql/postgres_db_writer.rb', line 31

def exists?(relname)
  rc = @conn.exec("SELECT COUNT(*) FROM pg_class WHERE relname = '#{relname}'")
  (!rc.nil?) && (rc.to_a.length==1) && (rc.first.count.to_i==1)
end

#format_eta(t) ⇒ Object



133
134
135
136
137
138
139
# File 'lib/mysql2psql/postgres_db_writer.rb', line 133

def format_eta (t)
  t = t.to_i
  sec = t % 60
  min = (t / 60) % 60
  hour = t / 3600
  sprintf("%02dh:%02dm:%02ds", hour, min, sec)
end

#openObject



18
19
20
21
22
23
24
25
# File 'lib/mysql2psql/postgres_db_writer.rb', line 18

def open
  @conn = PGconn.new(hostname, port, '', '', database, , password)
  @conn.exec("SET search_path TO #{PGconn.quote_ident(schema)}") if schema
  @conn.exec("SET client_encoding = 'UTF8'")
  @conn.exec("SET standard_conforming_strings = off") if @conn.server_version >= 80200
  @conn.exec("SET check_function_bodies = false")
  @conn.exec("SET client_min_messages = warning")    
end

#write_constraints(table) ⇒ Object



122
123
124
125
126
127
128
129
130
131
# File 'lib/mysql2psql/postgres_db_writer.rb', line 122

def write_constraints(table)
  table.foreign_keys.each do |key|
    key_sql = "ALTER TABLE #{PGconn.quote_ident(table.name)} ADD FOREIGN KEY (#{PGconn.quote_ident(key[:column])}) REFERENCES #{PGconn.quote_ident(key[:ref_table])}(#{PGconn.quote_ident(key[:ref_column])})"
    begin
      @conn.exec(key_sql)
    rescue Exception => e
      puts "Error: \n#{key_sql}\n#{e}"
    end
  end
end

#write_contents(table, reader) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/mysql2psql/postgres_db_writer.rb', line 141

def write_contents(table, reader)
  _time1 = Time.now
  copy_line = "COPY #{PGconn.quote_ident(table.name)} (#{table.columns.map {|column| PGconn.quote_ident(column[:name])}.join(", ")}) FROM stdin;"
  @conn.exec(copy_line)
  puts "Counting rows of #{table.name}... "
  STDOUT.flush
  rowcount = table.count_rows
  puts "Rows counted"
  puts "Loading #{table.name}..."
  STDOUT.flush
  _counter = reader.paginated_read(table, 1000) do |row, counter|
    line = []
    process_row(table, row)
    @conn.put_copy_data(row.join("\t") + "\n")
     
    if counter != 0 && counter % 20000 == 0
      elapsedTime = Time.now - _time1
      eta = elapsedTime * rowcount / counter - elapsedTime
      etaf = self.format_eta(eta)
      etatimef = (Time.now + eta).strftime("%Y/%m/%d %H:%M")
      printf "\r#{counter} of #{rowcount} rows loaded. [ETA: #{etatimef} (#{etaf})]"
      STDOUT.flush
    end
    
    if counter % 5000 == 0
      @conn.put_copy_end
      @conn.exec(copy_line)
    end
     
  end
  _time2 = Time.now
  puts "\n#{_counter} rows loaded in #{((_time2 - _time1) / 60).round}min #{((_time2 - _time1) % 60).round}s"
#    @conn.putline(".\n")
  @conn.put_copy_end
end

#write_indexes(table) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/mysql2psql/postgres_db_writer.rb', line 87

def write_indexes(table)
  puts "Indexing table #{table.name}..."
  if primary_index = table.indexes.find {|index| index[:primary]}
    @conn.exec("ALTER TABLE #{PGconn.quote_ident(table.name)} ADD CONSTRAINT \"#{table.name}_pkey\" PRIMARY KEY(#{primary_index[:columns].map {|col| PGconn.quote_ident(col)}.join(", ")})")
  end
  
  table.indexes.each do |index|
    next if index[:primary]
    unique = index[:unique] ? "UNIQUE " : nil
    
    #MySQL allows an index name which could be equal to a table name, Postgres doesn't
    indexname = index[:name]
    if indexname.eql?(table.name)
      indexnamenew = "#{indexname}_index"
      puts "WARNING: index \"#{indexname}\" equals table name. This is not allowed by postgres and will be renamed to \"#{indexnamenew}\""
      indexname = indexnamenew
    end
    
    if @conn.server_version < 80200
      @conn.exec("DROP INDEX #{PGconn.quote_ident(indexname)} CASCADE;") if exists?(indexname)
    else
      @conn.exec("DROP INDEX IF EXISTS #{PGconn.quote_ident(indexname)} CASCADE;")
    end
    @conn.exec("CREATE #{unique}INDEX #{PGconn.quote_ident(indexname)} ON #{PGconn.quote_ident(table.name)} (#{index[:columns].map {|col| PGconn.quote_ident(col)}.join(", ")});")
  end
  
  
  #@conn.exec("VACUUM FULL ANALYZE #{PGconn.quote_ident(table.name)}")
  puts "Indexed table #{table.name}"
rescue Exception => e
  puts "Couldn't create indexes on #{table} (#{table.indexes.inspect})"
  puts e
  puts e.backtrace[0,3].join("\n")
end

#write_table(table) ⇒ Object



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
# File 'lib/mysql2psql/postgres_db_writer.rb', line 36

def write_table(table)
  puts "Creating table #{table.name}..."
  primary_keys = []
  serial_key = nil
  maxval = nil
  
  columns = table.columns.map do |column|
    if column[:auto_increment]
      serial_key = column[:name]
      maxval = column[:maxval].to_i < 1 ? 1 : column[:maxval] + 1
    end
    if column[:primary_key]
      primary_keys << column[:name]
    end
    "  " + column_description(column)
  end.join(",\n")
  
  if serial_key
    if @conn.server_version < 80200
      serial_key_seq = "#{table.name}_#{serial_key}_seq"
      @conn.exec("DROP SEQUENCE #{serial_key_seq} CASCADE") if exists?(serial_key_seq)
    else
      @conn.exec("DROP SEQUENCE IF EXISTS #{table.name}_#{serial_key}_seq CASCADE")
    end
    @conn.exec <<-EOF
      CREATE SEQUENCE #{table.name}_#{serial_key}_seq
      INCREMENT BY 1
      NO MAXVALUE
      NO MINVALUE
      CACHE 1
    EOF
  
    @conn.exec "SELECT pg_catalog.setval('#{table.name}_#{serial_key}_seq', #{maxval}, true)"
  end
  
  if @conn.server_version < 80200
    @conn.exec "DROP TABLE #{PGconn.quote_ident(table.name)} CASCADE;" if exists?(table.name)
  else
    @conn.exec "DROP TABLE IF EXISTS #{PGconn.quote_ident(table.name)} CASCADE;"
  end
  create_sql = "CREATE TABLE #{PGconn.quote_ident(table.name)} (\n" + columns + "\n)\nWITHOUT OIDS;"
  begin
    @conn.exec(create_sql)
  rescue Exception => e
    puts "Error: \n#{create_sql}"
    raise
  end
  puts "Created table #{table.name}"
 
end