RSS Git Download  Clone
Raw Blame History
use App::Class; # Import::Into

class Model::Moongate;

use Data::Printer;
 
field $dbix :reader :param;

my $table = 'moongate';
# timestamp is GMT, needs to be converted to local timezone:
my $fields = join ',', qw( id description comment filename date ),
    q!DATETIME(time, 'localtime') as time!;

method save_document ($data) { # p $data; # return;
    my @cols = qw(id description comment filename date);
	my $flds = join ',', @cols;
	my $sql  = qq!INSERT INTO $table($flds) VALUES(?,?,?,?,?) ON CONFLICT(id)
		 DO UPDATE SET description = ?, comment = ?, filename = ?, date = ?!; # p $sql;
	my @bind = ( @{$data}{@cols}, @{$data}{ @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 = $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 get_all_documents {
	$dbix->select( $table, $fields, {}, { -asc => 'date' } )->hashes;
}

method get_document ($id) {
	my $rec = $dbix->select( $table, $fields, { id => $id } )->hashes; # 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;