tags:

views:

213

answers:

2

This should be an easy question I figure, but I hadn't found this answered else where surprisingly, so I'm posting it here.

I've inherited a Sqlite driven database which contains boolean columns in it, declared like this:

CREATE TABLE example (
  ex_col BOOLEAN NOT NULL DEFAULT 0,
);

This table is trying to be accessed via the sqlite3 C API calls sqlite_column_* functions, now given that sqlite doesn't actually support boolean types, what is the expected behavior here?

It appears sqlite_column_int() always return 0 or false, I assume this is because all columns in sqlite are really text columns...

And what is the proper way to maintain this - fetching as text and then string compare to true? I really don't want to modify the database and all of the other code attached to it.

+1  A: 

One obvious way would be to "declare" it as integer column and then when you do INSERT or UPDATE you pass it 1 (True) or 0 (False). This way, you maintain compatibility with the C language. You don't even need to declare it as int, just make sure you always insert integers to it and you'll be fine.

You mentioned this is an inherited database, how did they do before? If they stored as text then you may need to call sqlite_column_text() and then string match for the "true" or "false" literal strings.

Isak Savo
They didn't have to fetch the boolean column in C code previously, so it wasn't being done. What they had are a lot of #defines for sql stmts (ins, upd, etc) and a whole bunch of views and triggers... basically the value is never directly read or inserted. :-/
Petriborg
But surely somewhere the value is used? Are the triggers using the column value? How about the `#defined` statements? If it's never used, then why is it there? ;-)
Isak Savo
Yes used, like this `#define SQL "UPDATE example SET ex_col='true';"` and then this stmt gets called normally. The sql code does the same, so I guess I need to just do everything as string (yum) or change the column type to `Int` instead, no pretty solutions here!!
Petriborg
You don't have to worry about performance problems though.. remember that everything is already text inside SQLite so you are just doing some of the work that (admittedly) sqlite should do itself. I don't know what your code structure is, but in an OOP design, i'd create a method or property to get the value and inside that method do the conversion. This would also shield you from future changes to the DB schema (if you decide to use ints later for example)
Isak Savo
+1  A: 

I have a data point that might give you a clue.

The SQLite Administrator tool does convert booleans to the strings "true" and "false".

Vinko Vrsalovic