From d2b769d4717e2ab1e81eccb909cea4b138bff8bb Mon Sep 17 00:00:00 2001 From: Tom Bloor Date: Wed, 6 Sep 2017 16:10:34 +0100 Subject: [PATCH] Auto inflate correctly based on database type for booleans --- .../LocalLoop/Schema/Result/Organisation.pm | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/lib/Pear/LocalLoop/Schema/Result/Organisation.pm b/lib/Pear/LocalLoop/Schema/Result/Organisation.pm index a178e07..aa75de7 100644 --- a/lib/Pear/LocalLoop/Schema/Result/Organisation.pm +++ b/lib/Pear/LocalLoop/Schema/Result/Organisation.pm @@ -5,7 +5,7 @@ use warnings; use base 'DBIx::Class::Core'; -__PACKAGE__->load_components("InflateColumn::DateTime"); +__PACKAGE__->load_components("InflateColumn::DateTime", "FilterColumn"); __PACKAGE__->table("organisations"); @@ -51,7 +51,7 @@ __PACKAGE__->add_columns( }, pending => { data_type => 'boolean', - default_value => \"0", + default => \"false", is_nullable => 0, }, submitted_by_id => { @@ -68,4 +68,40 @@ __PACKAGE__->belongs_to( "entity_id", ); +__PACKAGE__->filter_column( pending => { + filter_to_storage => 'to_bool', + filter_from_storage => 'from_bool', +}); + +# Only works when calling ->deploy, but atleast helps for tests +sub sqlt_deploy_hook { + my ( $source_instance, $sqlt_table ) = @_; + my $pending_field = $sqlt_table->get_field('pending'); + if ( $sqlt_table->schema->translator->producer_type =~ /SQLite$/ ) { + $pending_field->{default_value} = 0; + } else { + $pending_field->{default_value} = \"false"; + } +} + +sub to_bool { + my ( $self, $val ) = @_; + my $driver_name = $self->result_source->schema->storage->dbh->{Driver}->{Name}; + if ( $driver_name eq 'SQLite' ) { + return $val ? 1 : 0; + } else { + return $val ? 'true' : 'false'; + } +} + +sub from_bool { + my ( $self, $val ) = @_; + my $driver_name = $self->result_source->schema->storage->dbh->{Driver}->{Name}; + if ( $driver_name eq 'SQLite' ) { + return $val; + } else { + return lc $val eq 'true' ? 1 : 0; + } +} + 1;