"mig" tool
[migration-tools.git] / mig-bin / mig-link
diff --git a/mig-bin/mig-link b/mig-bin/mig-link
new file mode 100755 (executable)
index 0000000..1a8ccd7
--- /dev/null
@@ -0,0 +1,87 @@
+#!/usr/bin/perl -w
+###############################################################################
+=pod
+
+=head1 NAME
+
+mig-link 
+
+Associate the specified file with a parent table within the migration schema.
+
+=head1 SYNOPSIS
+
+B<mig-link> <file> <parent table>
+
+=cut
+
+###############################################################################
+
+use strict;
+use Switch;
+use Env qw(
+    HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
+    MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
+);
+use Pod::Usage;
+use DBI;
+use Cwd 'abs_path';
+use FindBin;
+my $mig_bin = "$FindBin::Bin/";
+use lib "$FindBin::Bin/";
+use Mig;
+
+pod2usage(-verbose => 2) if ! $ARGV[0] || $ARGV[0] eq '--help';
+
+Mig::die_if_no_env_migschema();
+Mig::die_if_mig_tracking_table_does_not_exist();
+
+my $file = abs_path($ARGV[0]);
+if ($file =~ /^$MIGBASEWORKDIR/) {
+    link_table(@ARGV);
+} else {
+    print "File falls outside of MIGWORKDIR ($MIGWORKDIR): $file\n";
+}
+
+exit 0;
+
+###############################################################################
+
+sub link_table {
+    my $file = abs_path(shift);
+    my $table = shift;
+
+    if (! Mig::check_db_migschema_for_specific_table($table)) {
+        die "table not found in MIGSCHEMA ($MIGSCHEMA): $table\n";
+    }
+
+    my $tracked_file_id = Mig::check_for_tracked_file($file);
+    if ($tracked_file_id) {
+        my $data = Mig::status_this_file($file);
+
+        print "linking file to parent table: $file -> $table\n";
+
+        my $dbh = Mig::db_connect();
+        my $sth = $dbh->prepare("
+            SELECT base_filename
+            FROM $MIGSCHEMA.tracked_file
+            WHERE parent_table = " . $dbh->quote($table) . "
+            AND base_filename <> " . $dbh->quote($file) . ";"
+        );
+        my $rv = $sth->execute()
+            || die "Error checking $MIGSCHEMA.tracked_file: $!";
+        my @cols = $sth->fetchrow_array;
+        $sth->finish;
+        if ($cols[0]) { # found
+            die "table ($table) already linked to a different file: $cols[0]\n";
+        }
+        $rv = $dbh->do("
+            UPDATE $MIGSCHEMA.tracked_file
+            SET parent_table = " . $dbh->quote($table) . "
+            WHERE base_filename = " . $dbh->quote($file) . "
+            ;
+        ") || die "Error updating table $MIGSCHEMA.tracked_file: $!\n";
+        Mig::db_disconnect($dbh);
+    } else {
+        print "File not currently tracked: $file\n";
+    }
+}