additional escaping and multiple table options for add_sf9 function
[migration-tools.git] / mig-bin / mig-link
1 #!/usr/bin/perl -w
2 ###############################################################################
3 =pod
4
5 =head1 NAME
6
7 mig-link 
8
9 Associate the specified file with a parent table within the migration schema.
10
11 =head1 SYNOPSIS
12
13 B<mig-link> <file> <parent table>
14
15 =cut
16
17 ###############################################################################
18
19 use strict;
20 use Switch;
21 use Env qw(
22     HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
23     MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
24 );
25 use Pod::Usage;
26 use DBI;
27 use Cwd 'abs_path';
28 use FindBin;
29 my $mig_bin = "$FindBin::Bin/";
30 use lib "$FindBin::Bin/";
31 use Mig;
32
33 pod2usage(-verbose => 2) if ! $ARGV[0] || $ARGV[0] eq '--help';
34
35 Mig::die_if_no_env_migschema();
36 Mig::die_if_mig_tracking_table_does_not_exist();
37
38 my $file = abs_path($ARGV[0]);
39 if ($file =~ /^$MIGBASEWORKDIR/) {
40     link_table(@ARGV);
41 } else {
42     print "File falls outside of MIGWORKDIR ($MIGWORKDIR): $file\n";
43 }
44
45 exit 0;
46
47 ###############################################################################
48
49 sub link_table {
50     my $file = abs_path(shift);
51     my $table = shift;
52
53     if (! Mig::check_db_migschema_for_specific_table($table)) {
54         die "table not found in MIGSCHEMA ($MIGSCHEMA): $table\n";
55     }
56
57     my $tracked_file_id = Mig::check_for_tracked_file($file);
58     if ($tracked_file_id) {
59         my $data = Mig::status_this_file($file);
60
61         print "linking file to parent table: $file -> $table\n";
62
63         my $dbh = Mig::db_connect();
64         my $sth = $dbh->prepare("
65             SELECT base_filename
66             FROM $MIGSCHEMA.tracked_file
67             WHERE parent_table = " . $dbh->quote($table) . "
68             AND base_filename <> " . $dbh->quote($file) . ";"
69         );
70         my $rv = $sth->execute()
71             || die "Error checking $MIGSCHEMA.tracked_file: $!";
72         my @cols = $sth->fetchrow_array;
73         $sth->finish;
74         if ($cols[0]) { # found
75             die "table ($table) already linked to a different file: $cols[0]\n";
76         }
77         $rv = $dbh->do("
78             UPDATE $MIGSCHEMA.tracked_file
79             SET parent_table = " . $dbh->quote($table) . "
80             WHERE base_filename = " . $dbh->quote($file) . "
81             ;
82         ") || die "Error updating table $MIGSCHEMA.tracked_file: $!\n";
83         Mig::db_disconnect($dbh);
84     } else {
85         print "File not currently tracked: $file\n";
86     }
87 }