Module: ActiveRecord::Jdbc::Import::ClassMethods

Defined in:
lib/active_record/jdbc/import.rb

Instance Method Summary collapse

Instance Method Details

#import(models) ⇒ Object



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
# File 'lib/active_record/jdbc/import.rb', line 14

def import(models)
  return unless models.size > 0

  conn = self.connection.jdbc_connection

  insert_sql = models.first.to_prepared_sql

  pstmt = conn.prepareStatement(insert_sql)

  conn.setAutoCommit(false)

  models.each do |model|
    i = 1
    model.attributes.each_pair do |key, value|
      
      next if key.to_s == 'id'

      model_type = self.columns_hash[key].type
      if model_type == :integer and value.nil?
        pstmt.setInt(i, nil)
      elsif model_type == :integer
        pstmt.setInt(i, value.to_i)
      elsif key.to_s.downcase == 'week_date'
        pstmt.setString(i, value.to_date.strftime("%Y/%m/%d"))
      elsif model_type == :string and value.nil?
        pstmt.setString(i, nil)
      else
        pstmt.setString(i, value.to_s)
      end

      i += 1
    end

    pstmt.addBatch()
  end

  pstmt.executeBatch()

  conn.commit()

  conn.setAutoCommit(true)
end