sqlite3 varchar matching with “like” but not “=”

前端 未结 2 934
走了就别回头了
走了就别回头了 2021-01-03 12:32

Using Rails 3.1 and sqlite3 for development, test environments.

Added a new table in a migration:

create_table :api_keys do |t|
  t.string :api_key
          


        
相关标签:
2条回答
  • 2021-01-03 13:16

    If you are using strings of hex digits, it is important that you have a case match if you want to use an where x = y select. Unlike some databases, SQLite is case sensitive.

    0 讨论(0)
  • 2021-01-03 13:17

    OK, I think I've figured it out. The problem isn't that this is Rails 3.1, it's that you've likely moved from Ruby 1.8.7 to Ruby 1.9.2.

    In Ruby 1.9, all strings are now encoded. By default, all strings should be UTF-8, however, SecureRandom.hex(30) returns an encoding of ASCII-8BIT.

    You can confirm this in sqlite3 by using this command: .dump api_keys and you'll probably see that the api_key field looks something like this:

    INSERT INTO "api_keys" VALUES(1,X'376433356530[...]',1);    
    INSERT INTO "api_keys" VALUES(1,'1234567890[...]',1);
    

    The first one is the api_key generated by SecureRandom. The second is the one created by typing into the console. The X indicates the field is encoded as a blob, not as a string.

    To get around this, change your fill_api_key to this:

    self.api_key = SecureRandom.hex(30).force_encoding('UTF-8')
    

    I just got bit big time by this, so hopefully it helps you out.

    There are some good details about the changes to String in 1.9 here: http://blog.grayproductions.net/articles/ruby_19s_string

    0 讨论(0)
提交回复
热议问题