Added function attempt_phone (TEXT,TEXT) RETURNS TEXT. First argument is legacy...
[migration-tools.git] / sql / base / base.sql
index 95255e2..59eec2f 100644 (file)
@@ -687,8 +687,26 @@ CREATE OR REPLACE FUNCTION migration_tools.add_codabar_checkdigit (TEXT) RETURNS
     my @digits = split //, $barcode;
     my $total = 0;
     $total += $digits[$_] foreach (1, 3, 5, 7, 9, 11);
-    $total += (2 * $digits[$_] > 10) ? (2 * $digits[$_] - 9) : (2 * $digits[$_]) foreach (0, 2, 4, 6, 8, 10, 12);
+    $total += (2 * $digits[$_] >= 10) ? (2 * $digits[$_] - 9) : (2 * $digits[$_]) foreach (0, 2, 4, 6, 8, 10, 12);
     my $remainder = $total % 10;
     my $checkdigit = ($remainder == 0) ? $remainder : 10 - $remainder;
     return $barcode . $checkdigit; 
 $$ LANGUAGE PLPERL STRICT STABLE;
+
+CREATE OR REPLACE FUNCTION migration_tools.attempt_phone (TEXT,TEXT) RETURNS TEXT AS $$
+  DECLARE
+    phone TEXT := $1;
+    areacode TEXT := $2;
+    output TEXT := '';
+    n_digits INTEGER := 0;
+  BEGIN
+    output := REGEXP_REPLACE(phone, '[^0-9]*([0-9]{3})[^0-9]*([0-9]{3})[^0-9]*([0-9]{4})', E'\\1-\\2-\\3');
+    n_digits := LENGTH(REGEXP_REPLACE(output, '[^0-9]', '', 'g'));
+    IF n_digits = 7 THEN
+      RETURN (areacode || '-' || output);
+    ELSE
+      RETURN output;
+    END IF;
+  END;
+
+$$ LANGUAGE PLPGSQL STRICT VOLATILE;