6

I'm using DBIx::Class in my perl script to interact with a sqlite database.

When doing inserts/searches, what will DBIx::Class consider 'true' and 'false'?

eg:

$schema->resultset('SomeObject')->create({ some_boolean => 1, primary_key => 1 });

$schema->resultset('SomeObject')->search({ some_boolean => 'true' });

Any help or documentation is appreciated (I haven't been able to find it in the DBIx::Class docs, but maybe I'm missing something.

Thanks in advance.

Blaskovicz
  • 6,122
  • 7
  • 41
  • 50

4 Answers4

2

DBIx::Class handle boolean values with help of DBIx::Class::InflateColumn::Boolean:

Load this component and declare columns as boolean values.

  package Table;
  __PACKAGE__->load_components(qw/InflateColumn::Boolean Core/);
  __PACKAGE__->table('table');
  __PACKAGE__->true_is('Y');
  __PACKAGE__->add_columns(
      foo => {
          data_type => 'varchar',
          is_boolean  => 1,
      },
      bar => {
          data_type => 'varchar',
          is_boolean  => 1,
          true_is     => qr/^(?:yes|ja|oui|si)$/i,
      },
      baz => {
          data_type => 'int',
          is_boolean  => 1,
          false_is    => ['0', '-1'],
      },
  );

Then you can treat the specified column as a boolean:

  print 'table.foo is ', $table->foo ? 'true' : 'false', "\n";
  print 'table.bar is ', $table->bar ? 'true' : 'false', "\n";

The boolean object still stringifies to the actual field value:

  print $table->foo;  # prints "Y" if it is true

UPD How to select rows whose fields are true
Because DBIx::Class uses SQL::Abstract to search fields with TRUE value you should refer to bool unary operator:

my %where  = (
    -bool       => 'is_user',
    -not_bool   => 'is_enabled',
);

Would give you:

WHERE is_user AND NOT is_enabled
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
0

DBIx::Class would treat true and false the way perl does ... 0, '', undef, () and {} are "false" while anything else is "true".

harleypig
  • 1,264
  • 8
  • 25
0

http://sqlite.org/datatype3.html says that SQLite doesn't have a boolean datatype but false is stored as integer 0 and true as integer 1.

Alexander Hartmaier
  • 2,178
  • 12
  • 21
0

Since people are finding this helpful, I thought I'd throw in the get_bool() function I wrote for translating a perl value to a DBIx-acceptable format:

sub get_bool {
  my $self = shift;
  my $bool = shift;
  return undef if(!defined $bool || $bool =~ m/^null$/i);
  return 0 if($bool =~ m/^(fail|not_ok|error|0)/i || $bool =~ m/^\s*$/);
  return 1;
}
Blaskovicz
  • 6,122
  • 7
  • 41
  • 50