492507cd0929ef2d326d263dc8ed4bf08d0cef8c
[migration-tools.git] / kmig.d / 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 MYSQL_HOST MYSQL_TCP_PORT MYSQL_USER MYSQL_DATABASE MYSQL_PW
23     MIGSCHEMA 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 KMig;
32
33 pod2usage(-verbose => 2) if ! $ARGV[0] || $ARGV[0] eq '--help';
34
35 KMig::die_if_no_env_migschema();
36 KMig::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 ($table !~ /^m_/) {
54         die "for safety, since kmig 'link'ing really just adds columns to the parent table, this action is restricted to tables prefixed with m_";
55     }
56
57     if (! KMig::check_db_migschema_for_specific_table($table)) {
58         die "table not found in MIGSCHEMA ($MIGSCHEMA): $table\n";
59     }
60
61     my $tracked_file_id = KMig::check_for_tracked_file($file);
62     if ($tracked_file_id) {
63         my $data = KMig::status_this_file($file);
64
65         print "linking file to parent table: $file -> $table\n";
66
67         my $dbh = KMig::db_connect();
68         my $sth = $dbh->prepare("
69             SELECT base_filename
70             FROM m_tracked_file
71             WHERE parent_table = " . $dbh->quote($table) . "
72             AND base_filename <> " . $dbh->quote($file) . ";"
73         );
74         my $rv = $sth->execute()
75             || die "Error checking $MIGSCHEMA.tracked_file: $!";
76         my @cols = $sth->fetchrow_array;
77         $sth->finish;
78         if ($cols[0]) { # found
79             die "table ($table) already linked to a different file: $cols[0]\n";
80         }
81         $rv = $dbh->do("
82             UPDATE m_tracked_file
83             SET parent_table = " . $dbh->quote($table) . "
84             WHERE base_filename = " . $dbh->quote($file) . "
85             ;
86         ") || die "Error updating table m_tracked_file: $!\n";
87         KMig::db_disconnect($dbh);
88     } else {
89         print "File not currently tracked: $file\n";
90     }
91 }