Advertisement
Guest User

Untitled

a guest
May 26th, 2015
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. class InsertQuery
  2. def initialize(model_class, column_names, returning = nil)
  3. @model_class = model_class
  4. @column_names = column_names
  5. @returning = returning
  6.  
  7. @rows = []
  8. @executed = false
  9. end
  10.  
  11. def insert(model_attributes)
  12. ensure_not_executed
  13.  
  14. rows << prepare_model_attributes(model_attributes, Time.zone.now)
  15. end
  16.  
  17. def prepare_model_attributes(model_attributes, now)
  18. column_names.map do |column_name|
  19. prepare_model_attribute(column_name, model_attributes, now)
  20. end
  21. end
  22.  
  23. def prepare_model_attribute(column_name, model_attributes, now)
  24. column_name = column_name.to_sym
  25. if %i(created_at updated_at).include?(column_name)
  26. if model_attributes.include?(column_name)
  27. model_attributes[column_name]
  28. else
  29. now
  30. end
  31. else
  32. model_attributes.fetch(column_name, :default)
  33. end
  34. end
  35.  
  36. def execute
  37. ensure_not_executed
  38.  
  39. yield(self) if block_given?
  40. result = connection.execute(query).values unless rows.empty?
  41. self.executed = true
  42. result
  43. end
  44.  
  45. def self.execute(*constructor_args, &block)
  46. new(*constructor_args).execute(&block)
  47. end
  48.  
  49. private
  50.  
  51. attr_reader :model_class, :column_names, :rows, :returning
  52. attr_accessor :executed
  53.  
  54. delegate :connection, to: :model_class
  55.  
  56. def ensure_not_executed
  57. fail("the query has been already executed") if executed
  58. end
  59.  
  60. def query
  61. <<-SQL
  62. INSERT INTO
  63. #{model_class.table_name}
  64. (#{column_names.join(', ')})
  65. VALUES #{
  66. rows.map do |row|
  67. "(#{row.map { |datum| quote(datum) }.join(', ')})"
  68. end.join(', ')
  69. }
  70. #{returning_clause}
  71. SQL
  72. end
  73.  
  74. def quote(datum)
  75. if datum == :default
  76. 'default'
  77. else
  78. connection.quote(datum)
  79. end
  80. end
  81.  
  82. def returning_clause
  83. %(RETURNING #{returning}) if returning
  84. end
  85. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement