#!/usr/bin/perl -w
# sql2csv: extract sql table values from sql dump and convert to csv format
# usage: sql2csv < file
# 20140818 erikt(at)xs4all.nl (as sql2txt)

use strict;

my $command = $0;

while (<STDIN>) {
   my $line = $_;
   chomp($line);
   if ($line !~ /^\s*INSERT/) { next; }
   $line =~ s/^[^(]*\(//;
   $line =~ s/\)[^)]*$//;
   my @rows = split(/\),\(/,$line);
   for (my $i=0;$i<=$#rows;$i++) {
      # INSERT INTO `tmp2` VALUES ('A001p','2-1','14a'),('A001p','2-1','14b'),
      my @values = split(/,/,$rows[$i]);
      for (my $j=0;$j<=$#values;$j+=1) {
         if ($j > 0) { print ","; }
         my $value = $values[$j];
         while ($value =~ /^'/ and $value !~ /'$/ and $j < $#values) {
            $value .= ",".$values[$j+1];
            splice(@values,$j+1,1);
         }
         if ($value =~ /^'/ and $value !~ /'$/ and $j >= $#values) {
            die "$command: problem with single quotes on line: $rows[$i]\n";
         }
         $value =~ s/^'/"/;
         $value =~ s/'$/"/;
         if ($value eq "NULL") { $value = "\"NULL\""; }
         print $value;
      }
      print "\n";
   }
}

exit(0);
