use App::Class; # Import::Into
class Model::InfoLibrary;
use Data::Printer;
use Log::Any qw($log);
field $dbix :reader :param;
my $table = 'infolib';
my @cols = qw(id title content); # excl. time
# timestamp is GMT, needs to be converted to local timezone:
my $fields = join ',', @cols, q!DATETIME(time, 'localtime') as time!;
method get_all_documents { $dbix->select( $table, $fields )->hashes }
method get_document_by_id ($id) { # return hash for single document:
my $rec = $dbix->select( $table, $fields, { id => $id } )->hash; # p $rec;
return $rec; # returns AoH for template
}
method save_document ($data) { # p $data;
my $cols = join ',', @cols; # global $fields includes DATETIME(time ...)
my $sql = qq!INSERT INTO $table($cols) VALUES(?,?,?) ON CONFLICT(id)
DO UPDATE SET title = ?, content = ?!; # p $sql;
my @bind = ( @{$data}{@cols}, @{$data}{ qw/title content/ });
# if test error from .t:
return { error => $data->{test_err} } if $data->{test_err};
my $result = do { # choice is to capture error, or just die with db error
try { # since user probably cannot do anything about it
$dbix->query( $sql, @bind ) or die $dbix->error;
# record id = $data->{id} from record edit, or get last insert:
my $id = $data->{id} || $dbix->last_insert_id(); # p $id;
return { id => $id };
}
catch ($e) { # dsl->warning $e; # can't do it
return { error => $e };
}
};
return $result;
}
method find_documents ($str) { # $log->debug("searching for '$str'"); # Log::Any example
# sqlite3 regexp is case-sensitive, force all fields to lower-case search:
my @conditions = map { +( qq!LOWER($_)! => { -regexp => lc $str } ) }
qw(title content); # p @conditions;
my %h = ( -or => \@conditions ); # p %h;
my $res = $dbix->select( $table, $fields, \%h, { -asc => 'time' } )->hashes; # p $res;
return $res;
}
1;