Sha256: bcadf09f4ef436f864f2ee5c47a94c32613214a78de8c75d50ca95e6221adfc2

Contents?: true

Size: 1.61 KB

Versions: 2

Compression:

Stored size: 1.61 KB

Contents

require 'rom/sql/commands/error_wrapper'
require 'rom/sql/commands/transaction'

module ROM
  module SQL
    module Commands
      # SQL create command
      #
      # @api public
      class Create < ROM::Commands::Create
        adapter :sql

        include Transaction
        include ErrorWrapper

        use :associates
        use :schema

        # Inserts provided tuples into the database table
        #
        # @api public
        def execute(tuples)
          insert_tuples = with_input_tuples(tuples) do |tuple|
            attributes = input[tuple]
            attributes.to_h
          end

          if insert_tuples.length > 1
            multi_insert(insert_tuples)
          else
            insert(insert_tuples)
          end
        end

        private

        # Executes insert statement and returns inserted tuples
        #
        # @api private
        def insert(tuples)
          pks = tuples.map { |tuple| relation.insert(tuple) }
          relation.where(relation.primary_key => pks).to_a
        end

        # Executes multi_insert statement and returns inserted tuples
        #
        # @api private
        def multi_insert(tuples)
          pks = relation.multi_insert(tuples, return: :primary_key)
          relation.where(relation.primary_key => pks).to_a
        end

        # Yields tuples for insertion or return an enumerator
        #
        # @api private
        def with_input_tuples(tuples)
          input_tuples = Array([tuples]).flatten.map
          return input_tuples unless block_given?
          input_tuples.each { |tuple| yield(tuple) }
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-sql-1.0.0.beta2 lib/rom/sql/commands/create.rb
rom-sql-1.0.0.beta1 lib/rom/sql/commands/create.rb