aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/adapters/postgresql/view_test.rb
blob: 47b7d38eda42720f70a0c6728f55848c5edb81a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
56
57
58
59
60
61
62
63
64
65
66
67
require "cases/helper"

module ViewTestConcern
  extend ActiveSupport::Concern

  included do
    self.use_transactional_fixtures = false
    mattr_accessor :view_type
  end

  SCHEMA_NAME = 'test_schema'
  TABLE_NAME = 'things'
  COLUMNS = [
    'id integer',
    'name character varying(50)',
    'email character varying(50)',
    'moment timestamp without time zone'
  ]

  class ThingView < ActiveRecord::Base
  end

  def setup
    super
    ThingView.table_name = "#{SCHEMA_NAME}.#{view_type}_things"

    @connection = ActiveRecord::Base.connection
    @connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
    @connection.execute "CREATE #{view_type.humanize} #{ThingView.table_name} AS SELECT * FROM #{SCHEMA_NAME}.#{TABLE_NAME}"
  end

  def teardown
    super
    @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE"
  end

  def test_table_exists
    name = ThingView.table_name
    assert @connection.table_exists?(name), "'#{name}' table should exist"
  end

  def test_column_definitions
    assert_nothing_raised do
      assert_equal COLUMNS, columns(ThingView.table_name)
    end
  end

  private
    def columns(table_name)
      @connection.send(:column_definitions, table_name).map do |name, type, default|
        "#{name} #{type}" + (default ? " default #{default}" : '')
      end
    end

end

class ViewTest < ActiveRecord::TestCase
  include ViewTestConcern
  self.view_type = 'view'
end

if ActiveRecord::Base.connection.supports_materialized_views?
  class MaterializedViewTest < ActiveRecord::TestCase
    include ViewTestConcern
    self.view_type = 'materialized_view'
  end
end