lib/Odin.pm: New function for inserting records into databases.
authorMark Wooding <mdw@distorted.org.uk>
Fri, 24 Jul 2015 17:52:12 +0000 (18:52 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Fri, 24 Jul 2015 18:18:02 +0000 (19:18 +0100)
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.

lib/Odin.pm

index e373dcc..27b2e8b 100644 (file)
@@ -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;
 }