Skip to content
Browse files

remove :recursive; factor out type mapping

  • Loading branch information...
1 parent 5035a96 commit 850db6f46f8ed05ce14acf2d2973ed196b49a32a @moritz committed
Showing with 20 additions and 18 deletions.
  1. +20 −18 lib/Soonish/Table.pm
View
38 lib/Soonish/Table.pm
@@ -14,17 +14,18 @@ role Soonish::Table {
self.^attributes.map(*.Str.substr(2)).grep({ .substr(0,1) ne '_' }).map({; $_ => self."$_"()}).hash;
}
- method insert-or-create(Bool :$recursive) {
- self.id ?? self.update(:$recursive) !! self.insert(:$recursive)
+ method insert-or-create() {
+ self.id ?? self.update !! self.insert;
}
- method insert(Bool :$recursive) {
+ method insert() {
my %a := self.attributes;
my $id = %a.delete('id');
if $id {
die "Cannot insert an object that already has an id!";
}
my $dbh = $._schema.dbh;
+ my @values = %a.values.map({ self.typemap($_) });
my $sql = join ' ',
"INSERT INTO $dbh.quote-identifier($.table) ( ",
%a.keys.map({$dbh.quote-identifier($_)}).join(', '),
@@ -32,25 +33,21 @@ role Soonish::Table {
('?' xx %a.elems).join(', '),
') RETURNING id';
my $sth = $dbh.prepare($sql);
- if $recursive {
- $sth.execute(%a.values.map({ $_ ~~ Soonish::Table ?? .insert-or-update(:recursive).id !! $_ }));
- }
- else {
- $sth.execute(%a.values.map({ $_ ~~ Soonish::Table ?? .id || .insert.id !! $_}));
- }
+ $sth.execute(@values);
$id = $sth.fetchrow[0].Int;
$.id = $id;
$sth.finish;
self;
}
- method update(Bool :$recursive) {
+ method update() {
my %a := self.attributes;
my $id = %a.delete('id');
unless $.id {
die "Can only update an object that already has an id!";
}
my $dbh = $._schema.dbh;
+ my @values = %a.values.map({ self.typemap($_) });
my $sql = join ' ',
"UPDATE $dbh.quote-identifier($.table) SET ",
%a.keys.map({$dbh.quote-identifier($_) ~ " = ?"}).join(', '),
@@ -59,17 +56,22 @@ role Soonish::Table {
' = ?',
;
my $sth = $dbh.prepare($sql);
- if $recursive {
- $sth.execute(%a.values.map({ $_ ~~ Soonish::Table ?? (.insert-or-update.id) !! $_ } ), $.id);
- }
- else {
- $sth.execute(%a.values.map({ $_ ~~ Soonish::Table ?? (.id || .insert.id) !! $_ } ), $.id);
- }
+ $sth.execute(@values, $.id);
$sth.finish;
self;
}
- method insert-or-update(Bool :$recursive) {
- $.id ?? $.update(:$recursive) !! $.insert(:$recursive);
+ method insert-or-update() {
+ $.id ?? $.update !! $.insert;
}
+
+ method typemap($obj) {
+ if $obj ~~ Soonish::Table {
+ $obj.id ?? $obj !! $obj.insert;
+ }
+ else {
+ $obj;
+ }
+ }
+
}

0 comments on commit 850db6f

Please sign in to comment.
Something went wrong with that request. Please try again.