use App::Class; # Import::Into
class Model::Moongate;
use Data::Printer;
use File::Spec::Functions; # catfile
field $dbix :reader :param;
field $docs_path; # defined in set_docs_path(), :writer not yet supported
my $table = 'moongate';
my @cols = qw(id description comment filename date);
# timestamp is GMT, needs to be converted to local timezone:
my $fields = join ',', @cols, q!DATETIME(time, 'localtime') as time!;
# this can be deleted when Feature::Compat::Class supports :writer
method set_docs_path ($path) { $docs_path = $path }
method save_document ($params, $data_file) {
if ( $data_file ) {
# capture filename, replace spaces with underscores, non-destructive
my $filename = $data_file->filename =~ s{\s}{_}gr;
# generate $filepath from docs_path & filename:
my $filepath = catfile($docs_path, $filename); # p $filepath;
# check if it exists and bail if it does:
if ( -e $filepath ) {
return { error => qq!file "$filename" already exists! }
}
# add filename to params:
$params->{filename} = $filename;
} # p $params;
# if test error from .t:
return { error => $params->{test_err} } if $params->{test_err};
my $cols = join ',', @cols; # global $fields includes DATETIME(time ...)
my $sql = qq!INSERT INTO $table($cols) VALUES(?,?,?,?,?) ON CONFLICT(id)
DO UPDATE SET description = ?, comment = ?, filename = ?, date = ?!; # p $sql;
my @bind = ( @{$params}{@cols}, @{$params}{ @cols[1 .. $#cols] }); # omit 'id'
# p @bind;
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 = $params->{id} from record edit, or get last insert:
my $id = $params->{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 get_all_documents {
$dbix->select( $table, $fields, {}, { -asc => 'date' } )->hashes;
}
method get_document ($id) {
my $rec = $dbix->select( $table, $fields, { id => $id } )->hash; # p $rec;
return $rec; # returns AoH for template
}
method find_documents ($str) {
# sqlite3 regexp is case-sensitive, force all fields to lower-case search:
my @conditions = map { +( qq!LOWER($_)! => { -regexp => lc $str } ) }
qw(description filename comment); # p @conditions;
my %h = ( -or => \@conditions ); # p %where;
my $res = $dbix->select( $table, $fields, \%h, { -asc => 'date' } )->hashes; # p $res;
return $res;
}
1;