aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/adapters/postgresql/json_test.rb
blob: 6fc08ae4f04e14a723baf6cd658743f583d32f5b (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# encoding: utf-8

require "cases/helper"
require 'active_record/base'
require 'active_record/connection_adapters/postgresql_adapter'

class PostgresqlJSONTest < ActiveRecord::TestCase
  class JsonDataType < ActiveRecord::Base
    self.table_name = 'json_data_type'
  end

  def setup
    @connection = ActiveRecord::Base.connection
    begin
      @connection.transaction do
        @connection.create_table('json_data_type') do |t|
          t.json 'payload', :default => {}
        end
      end
    rescue ActiveRecord::StatementInvalid
      return skip "do not test on PG without json"
    end
    @column = JsonDataType.columns.find { |c| c.name == 'payload' }
  end

  def teardown
    @connection.execute 'drop table if exists json_data_type'
  end

  def test_column
    assert_equal :json, @column.type
  end

  def test_change_table_supports_json
    @connection.transaction do
      @connection.change_table('json_data_type') do |t|
        t.json 'users', default: '{}'
      end
      JsonDataType.reset_column_information
      column = JsonDataType.columns.find { |c| c.name == 'users' }
      assert_equal :json, column.type

      raise ActiveRecord::Rollback # reset the schema change
    end
  ensure
    JsonDataType.reset_column_information
  end

  def test_type_cast_json
    assert @column

    data = "{\"a_key\":\"a_value\"}"
    hash = @column.class.string_to_json data
    assert_equal({'a_key' => 'a_value'}, hash)
    assert_equal({'a_key' => 'a_value'}, @column.type_cast(data))

    assert_equal({}, @column.type_cast("{}"))
    assert_equal({'key'=>nil}, @column.type_cast('{"key": null}'))
    assert_equal({'c'=>'}','"a"'=>'b "a b'}, @column.type_cast(%q({"c":"}", "\"a\"":"b \"a b"})))
  end

  def test_rewrite
    @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
    x = JsonDataType.first
    x.payload = { '"a\'' => 'b' }
    assert x.save!
  end

  def test_select
    @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
    x = JsonDataType.first
    assert_equal({'k' => 'v'}, x.payload)
  end

  def test_select_multikey
    @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
    x = JsonDataType.first
    assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload)
  end

  def test_null_json
    @connection.execute %q|insert into json_data_type (payload) VALUES(null)|
    x = JsonDataType.first
    assert_equal(nil, x.payload)
  end
end