使用SQLite和Sequel的布尔值

时间:2012-05-24 10:05:00

标签: ruby sqlite boolean sequel

Sequel支持boolean类型。 它将truefalse存储为SQLite中的tf。 如果您再次阅读,数据会转换回truefalse

SQLite本身更喜欢将true存储为1,将false存储为0(以及一些SQLite-administartion工具预期)。 如果我将我的布尔值也存储为'1',则续集还会将值转换为'true':

require 'sequel'
DB = Sequel.sqlite()#'test.db')
DB.create_table(:test){
  boolean :my_truth
  nvarchar :descr, :size => 10
}
DB[:test].insert(1, '1')
p DB[:test].filter(:descr => '1').first #-> {:my_truth=>true, :descr=>"1"}

但如果我选择true,则找不到任何值:

DB[:test].filter(:my_truth => true).each{|ds|
  puts "\t%s" % ds[:descr]
}

找到了值true"t"

DB[:test].insert(true, 'true')
DB[:test].insert('t', '"t"')
DB[:test].filter(:my_truth => true).each{|ds|
  puts "\t%s" % ds[:descr]    #true and 't'
}

0这样的错误值存在类似情况......(请参阅问题后的示例代码)

所以我的问题: 如何让DB[:test].filter(:my_truth => true)检测1 - 值和 DB[:test].filter(:my_truth => false)来检测0 - 值?

我不是在找DB[:test].filter(:my_truth => [true,1])

之类的东西

类似问题的Activerecord Rails 3 SQLite3 Boolean false

我使用Sequel 3.33.0


示例代码:

require 'sequel'
DB = Sequel.sqlite()#'test.db')
DB.create_table(:test){
  boolean :my_truth
  nvarchar :descr, :size => 10
  fixnum :line  #code line, where data is inserted
}

#All true:
DB[:test].insert(true, 'true', __LINE__)
DB[:test].insert('true', '"true"', __LINE__)
DB[:test].insert(1, 'one', __LINE__)
DB[:test].insert('t', 't', __LINE__)

#All false:
DB[:test].insert(false,'false', __LINE__)
DB[:test].insert('false','"false"', __LINE__)
DB[:test].insert(0,'zero', __LINE__)
DB[:test].insert('f', 'f', __LINE__)
DB[:test].insert('F', 'F', __LINE__)
DB[:test].insert(nil, 'nil', __LINE__)
DB[:test].insert('n', 'n', __LINE__)
DB[:test].insert('N', 'N', __LINE__)

#Also true
DB[:test].insert('x', 'x', __LINE__)
DB[:test].insert(' ', 'space', __LINE__)
DB[:test].insert('', 'empty', __LINE__)

puts "All true values:"
DB[:test].filter(:my_truth => true).each{|ds|
  puts "\t%s (line %i)" % [ds[:descr],  ds[:line] ]
}

puts "All false values:"
DB[:test].filter(:my_truth => false).each{|ds|
  puts "\t%s (line %i)" % [ds[:descr],  ds[:line] ]
}

puts "Data:"
DB[:test].each{|ds|
  puts "\t%-5s is <%s> (line %i)" % [ ds[:descr], ds[:my_truth].inspect, ds[:line] ]
}

结果:

All true values:
  true (line 10)
  t (line 13)
All false values:
  false (line 16)
  f (line 19)
Data:
  true  is <true> (line 10)
  "true" is <true> (line 11)
  one   is <true> (line 12)
  t     is <true> (line 13)
  false is <false> (line 16)
  "false" is <false> (line 17)
  zero  is <false> (line 18)
  f     is <false> (line 19)
  F     is <false> (line 20)
  nil   is <nil> (line 21)
  n     is <false> (line 22)
  N     is <false> (line 23)
  x     is <true> (line 26)
  space is <true> (line 27)
  empty is <true> (line 28)

1 个答案:

答案 0 :(得分:4)

您可以使用integer_booleans设置将1/0用作true / false,而不是't'/'f',请参阅http://sequel.rubyforge.org/rdoc-adapters/classes/Sequel/SQLite/DatabaseMethods.html。这是一个例子:

DB = Sequel.sqlite(:integer_booleans=>true)