Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DBIx::Class handle boolean values?

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.

like image 480
Blaskovicz Avatar asked Nov 12 '22 21:11

Blaskovicz


1 Answers

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
like image 190
Eugen Konkov Avatar answered Dec 18 '22 12:12

Eugen Konkov