hstore_test.rb 9.5 KB
Newer Older
1
# encoding: utf-8
2 3 4 5 6
require "cases/helper"

class PostgresqlHstoreTest < ActiveRecord::TestCase
  class Hstore < ActiveRecord::Base
    self.table_name = 'hstores'
7 8

    store_accessor :settings, :language, :timezone
9 10 11 12
  end

  def setup
    @connection = ActiveRecord::Base.connection
13

14 15
    unless @connection.extension_enabled?('hstore')
      @connection.enable_extension 'hstore'
16
      @connection.commit_db_transaction
17
    end
18

19 20
    @connection.reconnect!

21 22 23
    @connection.transaction do
      @connection.create_table('hstores') do |t|
        t.hstore 'tags', :default => ''
24
        t.hstore 'payload', array: true
25
        t.hstore 'settings'
26 27
      end
    end
28
    @column = Hstore.columns_hash['tags']
29 30
  end

G
Guo Xiang Tan 已提交
31
  teardown do
32 33 34
    @connection.execute 'drop table if exists hstores'
  end

35 36 37 38 39
  if ActiveRecord::Base.connection.supports_extensions?
    def test_hstore_included_in_extensions
      assert @connection.respond_to?(:extensions), "connection should have a list of extensions"
      assert @connection.extensions.include?('hstore'), "extension list should include hstore"
    end
40

41 42 43 44 45 46 47 48 49 50
    def test_disable_enable_hstore
      assert @connection.extension_enabled?('hstore')
      @connection.disable_extension 'hstore'
      assert_not @connection.extension_enabled?('hstore')
      @connection.enable_extension 'hstore'
      assert @connection.extension_enabled?('hstore')
    ensure
      # Restore column(s) dropped by `drop extension hstore cascade;`
      load_schema
    end
51

52 53
    def test_column
      assert_equal :hstore, @column.type
54 55 56 57
      assert_equal "hstore", @column.sql_type
      assert_not @column.number?
      assert_not @column.binary?
      assert_not @column.array
58
    end
59

60 61 62
    def test_default
      @connection.add_column 'hstores', 'permissions', :hstore, default: '"users"=>"read", "articles"=>"write"'
      Hstore.reset_column_information
63

64
      assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.column_defaults['permissions'])
65 66 67 68 69
      assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.new.permissions)
    ensure
      Hstore.reset_column_information
    end

70 71 72 73 74 75
    def test_change_table_supports_hstore
      @connection.transaction do
        @connection.change_table('hstores') do |t|
          t.hstore 'users', default: ''
        end
        Hstore.reset_column_information
76
        column = Hstore.columns_hash['users']
77 78 79
        assert_equal :hstore, column.type

        raise ActiveRecord::Rollback # reset the schema change
80
      end
81
    ensure
82 83 84
      Hstore.reset_column_information
    end

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    def test_hstore_migration
      hstore_migration = Class.new(ActiveRecord::Migration) do
        def change
          change_table("hstores") do |t|
            t.hstore :keys
          end
        end
      end

      hstore_migration.new.suppress_messages do
        hstore_migration.migrate(:up)
        assert_includes @connection.columns(:hstores).map(&:name), "keys"
        hstore_migration.migrate(:down)
        assert_not_includes @connection.columns(:hstores).map(&:name), "keys"
      end
    end

102 103
    def test_cast_value_on_write
      x = Hstore.new tags: {"bool" => true, "number" => 5}
104
      assert_equal({"bool" => true, "number" => 5}, x.tags_before_type_cast)
105 106 107 108
      assert_equal({"bool" => "true", "number" => "5"}, x.tags)
      x.save
      assert_equal({"bool" => "true", "number" => "5"}, x.reload.tags)
    end
109

110
    def test_type_cast_hstore
111
      assert_equal({'1' => '2'}, @column.type_cast_from_database("\"1\"=>\"2\""))
112 113 114
      assert_equal({}, @column.type_cast_from_database(""))
      assert_equal({'key'=>nil}, @column.type_cast_from_database('key => NULL'))
      assert_equal({'c'=>'}','"a"'=>'b "a b'}, @column.type_cast_from_database(%q(c=>"}", "\"a\""=>"b \"a b")))
115
    end
116

117 118 119 120
    def test_with_store_accessors
      x = Hstore.new(language: "fr", timezone: "GMT")
      assert_equal "fr", x.language
      assert_equal "GMT", x.timezone
121

122 123 124 125
      x.save!
      x = Hstore.first
      assert_equal "fr", x.language
      assert_equal "GMT", x.timezone
126

127 128
      x.language = "de"
      x.save!
129

130 131 132 133
      x = Hstore.first
      assert_equal "de", x.language
      assert_equal "GMT", x.timezone
    end
134

135 136 137 138 139 140 141 142 143 144
    def test_duplication_with_store_accessors
      x = Hstore.new(language: "fr", timezone: "GMT")
      assert_equal "fr", x.language
      assert_equal "GMT", x.timezone

      y = x.dup
      assert_equal "fr", y.language
      assert_equal "GMT", y.timezone
    end

145 146 147 148 149 150 151 152 153 154
    def test_yaml_round_trip_with_store_accessors
      x = Hstore.new(language: "fr", timezone: "GMT")
      assert_equal "fr", x.language
      assert_equal "GMT", x.timezone

      y = YAML.load(YAML.dump(x))
      assert_equal "fr", y.language
      assert_equal "GMT", y.timezone
    end

155 156 157 158 159 160 161
    def test_changes_in_place
      hstore = Hstore.create!(settings: { 'one' => 'two' })
      hstore.settings['three'] = 'four'
      hstore.save!
      hstore.reload

      assert_equal 'four', hstore.settings['three']
162
      assert_not hstore.changed?
163 164
    end

165
    def test_gen1
166
      assert_equal(%q(" "=>""), @column.cast_type.type_cast_for_database({' '=>''}))
167
    end
168

169
    def test_gen2
170
      assert_equal(%q(","=>""), @column.cast_type.type_cast_for_database({','=>''}))
171
    end
172

173
    def test_gen3
174
      assert_equal(%q("="=>""), @column.cast_type.type_cast_for_database({'='=>''}))
175
    end
176

177
    def test_gen4
178
      assert_equal(%q(">"=>""), @column.cast_type.type_cast_for_database({'>'=>''}))
179
    end
180

181
    def test_parse1
182
      assert_equal({'a'=>nil,'b'=>nil,'c'=>'NuLl','null'=>'c'}, @column.type_cast_from_database('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
183
    end
184

185
    def test_parse2
186
      assert_equal({" " => " "},  @column.type_cast_from_database("\\ =>\\ "))
187
    end
188

189
    def test_parse3
190
      assert_equal({"=" => ">"},  @column.type_cast_from_database("==>>"))
191
    end
192

193
    def test_parse4
194
      assert_equal({"=a"=>"q=w"},   @column.type_cast_from_database('\=a=>q=w'))
195
    end
196

197
    def test_parse5
198
      assert_equal({"=a"=>"q=w"},   @column.type_cast_from_database('"=a"=>q\=w'))
199
    end
200

201
    def test_parse6
202
      assert_equal({"\"a"=>"q>w"},  @column.type_cast_from_database('"\"a"=>q>w'))
203
    end
204

205
    def test_parse7
206
      assert_equal({"\"a"=>"q\"w"}, @column.type_cast_from_database('\"a=>q"w'))
207
    end
208

209 210 211 212 213 214
    def test_rewrite
      @connection.execute "insert into hstores (tags) VALUES ('1=>2')"
      x = Hstore.first
      x.tags = { '"a\'' => 'b' }
      assert x.save!
    end
215

216 217 218 219 220
    def test_select
      @connection.execute "insert into hstores (tags) VALUES ('1=>2')"
      x = Hstore.first
      assert_equal({'1' => '2'}, x.tags)
    end
A
Aaron Patterson 已提交
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    def test_array_cycle
      assert_array_cycle([{"AA" => "BB", "CC" => "DD"}, {"AA" => nil}])
    end

    def test_array_strings_with_quotes
      assert_array_cycle([{'this has' => 'some "s that need to be escaped"'}])
    end

    def test_array_strings_with_commas
      assert_array_cycle([{'this,has' => 'many,values'}])
    end

    def test_array_strings_with_array_delimiters
      assert_array_cycle(['{' => '}'])
    end

    def test_array_strings_with_null_strings
      assert_array_cycle([{'NULL' => 'NULL'}])
    end

    def test_contains_nils
      assert_array_cycle([{'NULL' => nil}])
    end

246 247 248 249 250
    def test_select_multikey
      @connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')"
      x = Hstore.first
      assert_equal({'1' => '2', '2' => '3'}, x.tags)
    end
251

252 253 254
    def test_create
      assert_cycle('a' => 'b', '1' => '2')
    end
A
Aaron Patterson 已提交
255

256 257 258
    def test_nil
      assert_cycle('a' => nil)
    end
259

260 261 262
    def test_quotes
      assert_cycle('a' => 'b"ar', '1"foo' => '2')
    end
A
Aaron Patterson 已提交
263

264 265 266
    def test_whitespace
      assert_cycle('a b' => 'b ar', '1"foo' => '2')
    end
A
Aaron Patterson 已提交
267

268 269 270
    def test_backslash
      assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2')
    end
A
Aaron Patterson 已提交
271

272 273 274
    def test_comma
      assert_cycle('a, b' => 'bar', '1"foo' => '2')
    end
A
Aaron Patterson 已提交
275

276 277 278
    def test_arrow
      assert_cycle('a=>b' => 'bar', '1"foo' => '2')
    end
A
Aaron Patterson 已提交
279

280 281 282
    def test_quoting_special_characters
      assert_cycle('ca' => 'cà', 'ac' => 'àc')
    end
283

284 285 286
    def test_multiline
      assert_cycle("a\nb" => "c\nd")
    end
287

288 289 290 291 292 293
    class TagCollection
      def initialize(hash); @hash = hash end
      def to_hash; @hash end
      def self.load(hash); new(hash) end
      def self.dump(object); object.to_hash end
    end
294

295 296
    class HstoreWithSerialize < Hstore
      serialize :tags, TagCollection
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    end

    def test_hstore_with_serialized_attributes
      HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"})
      record = HstoreWithSerialize.first
      assert_instance_of TagCollection, record.tags
      assert_equal({"one" => "two"}, record.tags.to_hash)
      record.tags = TagCollection.new("three" => "four")
      record.save!
      assert_equal({"three" => "four"}, HstoreWithSerialize.first.tags.to_hash)
    end

    def test_clone_hstore_with_serialized_attributes
      HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"})
      record = HstoreWithSerialize.first
      dupe = record.dup
      assert_equal({"one" => "two"}, dupe.tags.to_hash)
    end
315 316
  end

A
Aaron Patterson 已提交
317
  private
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332
    def assert_array_cycle(array)
      # test creation
      x = Hstore.create!(payload: array)
      x.reload
      assert_equal(array, x.payload)

      # test updating
      x = Hstore.create!(payload: [])
      x.payload = array
      x.save!
      x.reload
      assert_equal(array, x.payload)
    end

333 334 335 336 337 338 339 340 341 342 343 344 345
    def assert_cycle(hash)
      # test creation
      x = Hstore.create!(:tags => hash)
      x.reload
      assert_equal(hash, x.tags)

      # test updating
      x = Hstore.create!(:tags => {})
      x.tags = hash
      x.save!
      x.reload
      assert_equal(hash, x.tags)
    end
346
end