From: Mark Wooding Date: Fri, 24 Jul 2015 17:52:12 +0000 (+0100) Subject: lib/Odin.pm: New function for inserting records into databases. X-Git-Url: https://git.distorted.org.uk/~mdw/odin-cgi/commitdiff_plain/818d80284739453fb26dfc20a400ed721bc4556b lib/Odin.pm: New function for inserting records into databases. SQL `INSERT' is really annoying because it separates the list of column names from the values. Add a new function which takes column-name/value pairs and sorts out the mess. --- diff --git a/lib/Odin.pm b/lib/Odin.pm index e373dcc..27b2e8b 100644 --- a/lib/Odin.pm +++ b/lib/Odin.pm @@ -152,6 +152,18 @@ sub xact (&$) { die $exc; } +sub insert_record ($$%) { + my ($db, $table, %fields) = @_; + my @var = (); + my @val = (); + + for my $v (keys %fields) { + push @var, $v; + push @val, $fields{$v}; + } + $db->do("INSERT INTO $table (" . join(", ", @var) . ") + VALUES (" . join(", ", map { "?" } @var) . ")", undef, @val); +} ###-------------------------------------------------------------------------- ### Sequence numbers and tagging. @@ -284,9 +296,8 @@ sub new_shorturl ($) { undef, $WHOCMP, $url); unless (defined $tag) { $tag = encode_tag(next_seq($db, "odin_shorturl_seq")); - $db->do("INSERT INTO odin_shorturl (tag, stamp, owner, url) - VALUES (?, ?, ?, ?)", undef, - $tag, $NOW, $WHO, $url); + insert_record $db, "odin_shorturl", + tag => $tag, stamp => $NOW, owner => $WHO, url => $url; } } $db; return $tag; @@ -348,10 +359,9 @@ sub new_pastebin (\%) { merge_hash %$new, %PASTEBIN_DEFAULTS; xact { $tag = encode_tag next_seq $db, "odin_pastebin_seq"; - $db->do("INSERT INTO odin_pastebin - (tag, stamp, edithash, owner, $PASTEBIN_PROPCOLS) - VALUES (?, ?, ?, ?, $PASTEBIN_PROPPLACES)", undef, - $tag, $NOW, $hash, $WHO, @{$new}{@PASTEBIN_PROPS}); + insert_record $db, "odin_pastebin", + tag => $tag, stamp => $NOW, edithash => $hash, owner => $WHO, + %$new; } $db; return $tag, $editkey; }