Sha256: a6b067a3652671be62433aea84d384f7235bf5642625bbb2633821804e036b44

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module TableSaw
  module Queries
    class PreparedInsertStatement
      attr_reader :table_name, :options

      Statement = Struct.new(:name, :table_name, :sql)

      def initialize(table_name, options: {})
        @table_name = table_name
        @options = options
      end

      def call
        Statement.new(name, table_name, sql)
      end

      private

      def name
        "#{table_name}_insert_plan"
      end

      def sql
        [prepare_statement, conflict_statement].compact.join(' ') + ';'
      end

      def column_types
        TableSaw.schema_cache.columns(table_name).map(&:sql_type).join(', ')
      end

      def values_clause
        1.upto(TableSaw.schema_cache.columns(table_name).size).map { |i| "$#{i}" }.join(', ')
      end

      def prepare_statement
        <<~SQL.squish
          PREPARE #{name} (#{column_types}) AS INSERT INTO #{table_name} VALUES (#{values_clause})
        SQL
      end

      def conflict_statement
        return unless options['ignore_conflict'] == 'true'

        'ON CONFLICT DO NOTHING'
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
table_saw-2.4.1 lib/table_saw/queries/prepared_insert_statement.rb
table_saw-2.4.0 lib/table_saw/queries/prepared_insert_statement.rb
table_saw-2.3.0 lib/table_saw/queries/prepared_insert_statement.rb