Example: filter (optional)
package MyApp::DB::Filter;
use Aniki::Filter::Declare;
inflate qr/_at$/ => sub {
my $datetime = shift;
return Time::Moment->from_string($datetime.'Z', lenient =>
1);
};
deflate qr/_at$/ => sub {
my $datetime = shift;
return $datetime->at_utc->strftime('%F %T') if blessed
$datetime and $datetime->isa('Time::Moment');
return $datetime;
};
Slide 50
Slide 50 text
Example: filter (optional)
package MyApp::DB::Filter;
trigger insert => sub {
my ($row, $next) = @_;
$row->{created_at} = Time::Moment->now;
return $next->($row);
};
trigger update => sub {
my ($row, $next) = @_;
$row->{updated_at} = Time::Moment->now;
return $next->($row);
};
Slide 51
Slide 51 text
Example: connect to database
use MyApp::DB;
my $connect_info = [
'dbi:mysql:dbname=myapp',
'root',
'',
];
my $db = MyApp::DB->new(
connect_info => $connect_info,
);
Slide 52
Slide 52 text
Example: select
my $row = $db->select(post => {
id => 1,
}, { limit => 1 })->first;
my @rows = $db->select(post => {})->all;
Slide 53
Slide 53 text
Example: relationship
my $row = $db->select(post => {
id => 1,
}, {
limit => 1,
prefetch => [qw/comment/],
})->first;
my @rows = $db->select(post => {
id => { between => [1, 10] },
}, {
prefetch => [qw/comment/],
})->all;
Slide 54
Slide 54 text
Example: row access
my $post = $db->select(post => { id => 1 });
# post.subject
my $subject = $post->subject;
# resolve relationship
# => SELECT * FROM comments WHERE post_id = 1
my @comments = $post->comments;
# You can pre-fetch with select option
# But, It's optional. Not required.
Slide 55
Slide 55 text
Example: insert
$db->insert(post => {
subject => 'YAPC::Hokkaido 2016 Sapporo',
body => '北海道だよ',
});
my $id = $db->insert_and_fetch_id(post => {
...,
});
my $row = $db->insert_and_fetch_row(post => {
...,
});
Slide 56
Slide 56 text
Example: update
my $updated_rows_count = $db->update(post => {
subject => 'YAPC::Kansai 2017 Osaka',
body => '大阪だよ',
}, {
id => 1,
});
$db->update($row => {
body => '新大阪だよ',
});
Slide 57
Slide 57 text
Example: delete
my $deleted_rows_count = $db->delete(post => {
id => 1,
});
$db->delete($row);