Sha256: b29ba101dcebf93e7e9ef8f4e14280b9c487c92e71ac9209a501ea7c413e0b73

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 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_metadata).map(&:sql_type).join(', ')
      end

      def column_names
        TableSaw.schema_cache.columns(table_name).map(&:name).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} (#{column_names}) 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

1 entries across 1 versions & 1 rubygems

Version Path
table_saw-2.4.3 lib/table_saw/queries/prepared_insert_statement.rb