10

I'm trying to insert a false boolean value in a SQLite3 table but it always inserts a true value.

Here's my migration:

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :name, :string
      t.column :active, :boolean, :default => false, :null => false
    end
  end

  def self.down
    drop_table :resources
  end
end

When I try to insert using rails it produces the following SQL:

INSERT INTO "users" ("name", "active") VALUES ('test', 'f')

SQLite treats 'f' as true so it inserts true into my database. The query I want it to generate is:

INSERT INTO "users" ("name", "active") VALUES ('test', false)

What am I doing wrong?

rails: 3.0.7

sqlite3 gem: 1.3.3

tereško
  • 58,060
  • 25
  • 98
  • 150
Mike Neumegen
  • 2,436
  • 1
  • 24
  • 39

5 Answers5

21

SQLite uses 1 for true and 0 for false:

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

But SQLite also has a loose type system and automatically casts things so your 'f' is probably being interpreted as having a truthiness of "true" simply because it isn't zero.

A bit of digging indicates that you have found a bug in the Rails 3.0.7 SQLiteAdapter. In active_record/connection_adapters/abstract/quoting.rb, we find these:

def quoted_true
  "'t'"
end

def quoted_false
  "'f'"
end

So, by default, ActiveRecord assumes that the database understands 't' and 'f' for boolean columns. The MySQL adaptor overrides these to work with its tinyint implementation of boolean columns:

QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze

#...

def quoted_true
  QUOTED_TRUE
end

def quoted_false
  QUOTED_FALSE
end

But the SQLite adapter does not provide its own implementations of quoted_true or quoted_false so it gets the defaults which don't work with SQLite's booleans.

The 't' and 'f' booleans work in PostgreSQL so maybe everyone is using PostgreSQL with Rails 3 or they're just not noticing that their queries aren't working properly.

I'm a little surprised by this and hopefully someone can point out where I've gone wrong, you can't be the first person to use a boolean column in SQLite with Rails 3.

Try monkey patching def quoted_true;'1';end and def quoted_false;'0';end into ActiveRecord::ConnectionAdapters::SQLiteAdapter (or temporarily hand-edit them into active_record/connection_adapters/sqlite_adapter.rb) and see if you get sensible SQL.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Yes, I'm aware of that. I just can't work out why it's using 'f' instead of false or 0 because a 0 is passed in the POST. – Mike Neumegen May 16 '11 at 04:46
  • @Mike: Have a look at my update please. I deleted my original answer, then resurrected it, and updated it based on a quick review of the ActiveRecord database adapter source code. – mu is too short May 16 '11 at 05:43
  • That's what I was thinking...I can't be the first person to come across this bug which made me think it was something to do with my environment. I'll wait a bit to see if anyone else has another explanation otherwise I'll give you the credit. – Mike Neumegen May 16 '11 at 21:16
  • @Mike: I find it hard to believe too but the code (usually) doesn't lie and your results back up what I found in the source. Try patching your `sqlite_adapter.rb` and see what happens; if the MySQL approach works for SQLite then you could send the Rails or SQLite3 developers a patch to fix it and gain fame and fortune (or maybe just a "thanks"). – mu is too short May 16 '11 at 21:27
  • 2
    Turns out there's nothing wrong with the sqlite adapter. It was my database viewing software which had the bug in it. Thanks so much for your in depth answer I wish I could give you the credit. – Mike Neumegen May 16 '11 at 22:02
  • 2
    @Mike: Rails is using `'t'` and `'f'` as boolean values in the SQLite database though, right? That would work fine as long as only Rails used the database, SQLite treats everything as a string internally so the column type in the DDL is mostly advisory. I'm just curious if I'm reading the source correctly, maybe I'll set up my own Rails/SQLite test app and see. – mu is too short May 17 '11 at 02:28
  • Correct it stores it as 't' or 'f' in the database. I guess that was the database viewer wasn't expecting that. – Mike Neumegen May 17 '11 at 04:24
  • @Mike: Thanks for checking that for me, much appreciated. The viewer you were using was probably expecting 1 or 0 for booleans (as specified in the SQLite documentation). SQLite's loose data typing means that it doesn't matter as long as the external application always uses the same values. – mu is too short May 17 '11 at 04:30
  • SQLite doesn't treat everything as strings (it's got a more complex type system than that which allows it to beat strings in many important cases, such as numbers) but it also doesn't enforce type constraints as a deliberate policy. – Donal Fellows Jul 03 '11 at 21:00
  • @Donal: Maybe "stored as strings" would be a less simplified view of reality. The real point is that the SQLite type system is (intentionally) rather loose. – mu is too short Jul 03 '11 at 21:05
  • This solved my boolean issue, Thanks a lot! I think indeed a bug in Rails 3??? I am using Rails 3.0.10 and this fixed my issue. – Michael Koper Aug 25 '11 at 18:30
  • This is irritating, I lost 2 days seems because of this. – gljivar Mar 25 '13 at 20:57
4

I ran across this as well, here's how to monkey patch:

require 'active_record/connection_adapters/sqlite_adapter'
module ActiveRecord
  module ConnectionAdapters
    class SQLite3Adapter < SQLiteAdapter
      def quoted_true; '1' end
      def quoted_false; '0' end
    end
  end
end

I don't get how I'm still running across this bug??

Peter P.
  • 3,221
  • 2
  • 25
  • 31
3

You may find useful the following code snippet for adding compatibility with SQLite boolean columns actually working on Rails 4 (also posted at https://gist.github.com/ajoman/9391708):

# config/initializers/sqlite3_adapter_patch.rb

module ActiveRecord
  module ConnectionAdapters
    class SQLite3Adapter < AbstractAdapter
      QUOTED_TRUE, QUOTED_FALSE = "'t'", "'f'"

      def quoted_true
        QUOTED_TRUE
      end

      def quoted_false
        QUOTED_FALSE
      end
    end
  end
end
2

This was fixed on master on 12 Jul 2017. However it is not part of the latest stable release (5.1.4). The most recent release where it's fixed is v5.2.0.rc1.

The behaviour can be set via Rails.application.config.active_record.sqlite3.represent_boolean_as_integer (default is true).

thisismydesign
  • 21,553
  • 9
  • 123
  • 126
0

This version works in Rails 4.1.

require 'active_record/connection_adapters/sqlite_adapter'

module ActiveRecord::ConnectionAdapters::SQLite3Adapter
  QUOTED_TRUE, QUOTED_FALSE = 't'.freeze, 'f'.freeze

  def quoted_true; QUOTED_TRUE end
  def quoted_false; QUOTED_FALSE end
end

The constants and .freeze are for performance, so ruby doesn't have to regenerate those strings and garbage collect them on every call.

Edward Anderson
  • 13,591
  • 4
  • 52
  • 48